1use gpui::{ModelHandle, ViewContext};
2use workspace::Workspace;
3
4use crate::{get_wd_for_workspace, DeployModal, Event, Terminal, TerminalConnection};
5
6struct StoredConnection(ModelHandle<TerminalConnection>);
7
8pub fn deploy_modal(workspace: &mut Workspace, _: &DeployModal, cx: &mut ViewContext<Workspace>) {
9 // Pull the terminal connection out of the global if it has been stored
10 let possible_connection =
11 cx.update_default_global::<Option<StoredConnection>, _, _>(|possible_connection, _| {
12 possible_connection.take()
13 });
14
15 if let Some(StoredConnection(stored_connection)) = possible_connection {
16 // Create a view from the stored connection
17 workspace.toggle_modal(cx, |_, cx| {
18 cx.add_view(|cx| Terminal::from_connection(stored_connection, true, cx))
19 });
20 } else {
21 // No connection was stored, create a new terminal
22 if let Some(closed_terminal_handle) = workspace.toggle_modal(cx, |workspace, cx| {
23 let wd = get_wd_for_workspace(workspace, cx);
24 let this = cx.add_view(|cx| Terminal::new(wd, true, cx));
25 let connection_handle = this.read(cx).connection.clone();
26 cx.subscribe(&connection_handle, on_event).detach();
27 this
28 }) {
29 let connection = closed_terminal_handle.read(cx).connection.clone();
30 cx.set_global(Some(StoredConnection(connection)));
31 }
32 }
33}
34
35pub fn on_event(
36 workspace: &mut Workspace,
37 _: ModelHandle<TerminalConnection>,
38 event: &Event,
39 cx: &mut ViewContext<Workspace>,
40) {
41 // Dismiss the modal if the terminal quit
42 if let Event::CloseTerminal = event {
43 cx.set_global::<Option<StoredConnection>>(None);
44 if workspace
45 .modal()
46 .cloned()
47 .and_then(|modal| modal.downcast::<Terminal>())
48 .is_some()
49 {
50 workspace.dismiss_modal(cx)
51 }
52 }
53}