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