1use std::{ops::ControlFlow, path::PathBuf, sync::Arc};
2
3use crate::TerminalView;
4use collections::{HashMap, HashSet};
5use db::kvp::KEY_VALUE_STORE;
6use futures::future::join_all;
7use gpui::{
8 actions, Action, AppContext, AsyncWindowContext, Entity, EventEmitter, ExternalPaths,
9 FocusHandle, FocusableView, IntoElement, ParentElement, Pixels, Render, Styled, Subscription,
10 Task, View, ViewContext, VisualContext, WeakView, WindowContext,
11};
12use itertools::Itertools;
13use project::{Fs, ProjectEntryId};
14use search::{buffer_search::DivRegistrar, BufferSearchBar};
15use serde::{Deserialize, Serialize};
16use settings::Settings;
17use task::{SpawnInTerminal, TaskId};
18use terminal::{
19 terminal_settings::{Shell, TerminalDockPosition, TerminalSettings},
20 SpawnTask,
21};
22use ui::{h_flex, ButtonCommon, Clickable, IconButton, IconSize, Selectable, Tooltip};
23use util::{ResultExt, TryFutureExt};
24use workspace::{
25 dock::{DockPosition, Panel, PanelEvent},
26 item::Item,
27 pane,
28 ui::IconName,
29 DraggedTab, NewTerminal, Pane, Workspace,
30};
31
32use anyhow::Result;
33
34const TERMINAL_PANEL_KEY: &str = "TerminalPanel";
35
36actions!(terminal_panel, [ToggleFocus]);
37
38pub fn init(cx: &mut AppContext) {
39 cx.observe_new_views(
40 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
41 workspace.register_action(TerminalPanel::new_terminal);
42 workspace.register_action(TerminalPanel::open_terminal);
43 workspace.register_action(|workspace, _: &ToggleFocus, cx| {
44 workspace.toggle_panel_focus::<TerminalPanel>(cx);
45 });
46 },
47 )
48 .detach();
49}
50
51pub struct TerminalPanel {
52 pane: View<Pane>,
53 fs: Arc<dyn Fs>,
54 workspace: WeakView<Workspace>,
55 width: Option<Pixels>,
56 height: Option<Pixels>,
57 pending_serialization: Task<Option<()>>,
58 pending_terminals_to_add: usize,
59 _subscriptions: Vec<Subscription>,
60 deferred_tasks: HashMap<TaskId, Task<()>>,
61}
62
63impl TerminalPanel {
64 fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
65 let terminal_panel = cx.view().downgrade();
66 let pane = cx.new_view(|cx| {
67 let mut pane = Pane::new(
68 workspace.weak_handle(),
69 workspace.project().clone(),
70 Default::default(),
71 None,
72 NewTerminal.boxed_clone(),
73 cx,
74 );
75 pane.set_can_split(false, cx);
76 pane.set_can_navigate(false, cx);
77 pane.display_nav_history_buttons(false);
78 pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
79 let terminal_panel = terminal_panel.clone();
80 h_flex()
81 .gap_2()
82 .child(
83 IconButton::new("plus", IconName::Plus)
84 .icon_size(IconSize::Small)
85 .on_click(move |_, cx| {
86 terminal_panel
87 .update(cx, |panel, cx| panel.add_terminal(None, None, cx))
88 .log_err();
89 })
90 .tooltip(|cx| Tooltip::text("New Terminal", cx)),
91 )
92 .child({
93 let zoomed = pane.is_zoomed();
94 IconButton::new("toggle_zoom", IconName::Maximize)
95 .icon_size(IconSize::Small)
96 .selected(zoomed)
97 .selected_icon(IconName::Minimize)
98 .on_click(cx.listener(|pane, _, cx| {
99 pane.toggle_zoom(&workspace::ToggleZoom, cx);
100 }))
101 .tooltip(move |cx| {
102 Tooltip::text(if zoomed { "Zoom Out" } else { "Zoom In" }, cx)
103 })
104 })
105 .into_any_element()
106 });
107
108 let workspace = workspace.weak_handle();
109 pane.set_custom_drop_handle(cx, move |pane, dropped_item, cx| {
110 if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
111 let item = if &tab.pane == cx.view() {
112 pane.item_for_index(tab.ix)
113 } else {
114 tab.pane.read(cx).item_for_index(tab.ix)
115 };
116 if let Some(item) = item {
117 if item.downcast::<TerminalView>().is_some() {
118 return ControlFlow::Continue(());
119 } else if let Some(project_path) = item.project_path(cx) {
120 if let Some(entry_path) = workspace
121 .update(cx, |workspace, cx| {
122 workspace
123 .project()
124 .read(cx)
125 .absolute_path(&project_path, cx)
126 })
127 .log_err()
128 .flatten()
129 {
130 add_paths_to_terminal(pane, &[entry_path], cx);
131 }
132 }
133 }
134 } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
135 if let Some(entry_path) = workspace
136 .update(cx, |workspace, cx| {
137 let project = workspace.project().read(cx);
138 project
139 .path_for_entry(entry_id, cx)
140 .and_then(|project_path| project.absolute_path(&project_path, cx))
141 })
142 .log_err()
143 .flatten()
144 {
145 add_paths_to_terminal(pane, &[entry_path], cx);
146 }
147 } else if let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
148 add_paths_to_terminal(pane, paths.paths(), cx);
149 }
150
151 ControlFlow::Break(())
152 });
153 let buffer_search_bar = cx.new_view(search::BufferSearchBar::new);
154 pane.toolbar()
155 .update(cx, |toolbar, cx| toolbar.add_item(buffer_search_bar, cx));
156 pane
157 });
158 let subscriptions = vec![
159 cx.observe(&pane, |_, _, cx| cx.notify()),
160 cx.subscribe(&pane, Self::handle_pane_event),
161 ];
162 let this = Self {
163 pane,
164 fs: workspace.app_state().fs.clone(),
165 workspace: workspace.weak_handle(),
166 pending_serialization: Task::ready(None),
167 width: None,
168 height: None,
169 pending_terminals_to_add: 0,
170 deferred_tasks: HashMap::default(),
171 _subscriptions: subscriptions,
172 };
173 this
174 }
175
176 pub async fn load(
177 workspace: WeakView<Workspace>,
178 mut cx: AsyncWindowContext,
179 ) -> Result<View<Self>> {
180 let serialized_panel = cx
181 .background_executor()
182 .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })
183 .await
184 .log_err()
185 .flatten()
186 .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
187 .transpose()
188 .log_err()
189 .flatten();
190
191 let (panel, pane, items) = workspace.update(&mut cx, |workspace, cx| {
192 let panel = cx.new_view(|cx| TerminalPanel::new(workspace, cx));
193 let items = if let Some(serialized_panel) = serialized_panel.as_ref() {
194 panel.update(cx, |panel, cx| {
195 cx.notify();
196 panel.height = serialized_panel.height.map(|h| h.round());
197 panel.width = serialized_panel.width.map(|w| w.round());
198 panel.pane.update(cx, |_, cx| {
199 serialized_panel
200 .items
201 .iter()
202 .map(|item_id| {
203 TerminalView::deserialize(
204 workspace.project().clone(),
205 workspace.weak_handle(),
206 workspace.database_id(),
207 *item_id,
208 cx,
209 )
210 })
211 .collect::<Vec<_>>()
212 })
213 })
214 } else {
215 Vec::new()
216 };
217 let pane = panel.read(cx).pane.clone();
218 (panel, pane, items)
219 })?;
220
221 if let Some(workspace) = workspace.upgrade() {
222 panel
223 .update(&mut cx, |panel, cx| {
224 panel._subscriptions.push(cx.subscribe(
225 &workspace,
226 |terminal_panel, _, e, cx| {
227 if let workspace::Event::SpawnTask(spawn_in_terminal) = e {
228 terminal_panel.spawn_task(spawn_in_terminal, cx);
229 };
230 },
231 ))
232 })
233 .ok();
234 }
235
236 let pane = pane.downgrade();
237 let items = futures::future::join_all(items).await;
238 pane.update(&mut cx, |pane, cx| {
239 let active_item_id = serialized_panel
240 .as_ref()
241 .and_then(|panel| panel.active_item_id);
242 let mut active_ix = None;
243 for item in items {
244 if let Some(item) = item.log_err() {
245 let item_id = item.entity_id().as_u64();
246 pane.add_item(Box::new(item), false, false, None, cx);
247 if Some(item_id) == active_item_id {
248 active_ix = Some(pane.items_len() - 1);
249 }
250 }
251 }
252
253 if let Some(active_ix) = active_ix {
254 pane.activate_item(active_ix, false, false, cx)
255 }
256 })?;
257
258 Ok(panel)
259 }
260
261 fn handle_pane_event(
262 &mut self,
263 _pane: View<Pane>,
264 event: &pane::Event,
265 cx: &mut ViewContext<Self>,
266 ) {
267 match event {
268 pane::Event::ActivateItem { .. } => self.serialize(cx),
269 pane::Event::RemoveItem { .. } => self.serialize(cx),
270 pane::Event::Remove => cx.emit(PanelEvent::Close),
271 pane::Event::ZoomIn => cx.emit(PanelEvent::ZoomIn),
272 pane::Event::ZoomOut => cx.emit(PanelEvent::ZoomOut),
273
274 pane::Event::AddItem { item } => {
275 if let Some(workspace) = self.workspace.upgrade() {
276 let pane = self.pane.clone();
277 workspace.update(cx, |workspace, cx| item.added_to_pane(workspace, pane, cx))
278 }
279 }
280
281 _ => {}
282 }
283 }
284
285 pub fn open_terminal(
286 workspace: &mut Workspace,
287 action: &workspace::OpenTerminal,
288 cx: &mut ViewContext<Workspace>,
289 ) {
290 let Some(this) = workspace.focus_panel::<Self>(cx) else {
291 return;
292 };
293
294 this.update(cx, |this, cx| {
295 this.add_terminal(Some(action.working_directory.clone()), None, cx)
296 })
297 }
298
299 pub fn spawn_task(&mut self, spawn_in_terminal: &SpawnInTerminal, cx: &mut ViewContext<Self>) {
300 let mut spawn_task = SpawnTask {
301 id: spawn_in_terminal.id.clone(),
302 label: spawn_in_terminal.label.clone(),
303 command: spawn_in_terminal.command.clone(),
304 args: spawn_in_terminal.args.clone(),
305 env: spawn_in_terminal.env.clone(),
306 };
307 // Set up shell args unconditionally, as tasks are always spawned inside of a shell.
308 let Some((shell, mut user_args)) = (match TerminalSettings::get_global(cx).shell.clone() {
309 Shell::System => std::env::var("SHELL").ok().map(|shell| (shell, vec![])),
310 Shell::Program(shell) => Some((shell, vec![])),
311 Shell::WithArguments { program, args } => Some((program, args)),
312 }) else {
313 return;
314 };
315
316 let mut command = std::mem::take(&mut spawn_task.command);
317 let args = std::mem::take(&mut spawn_task.args);
318 for arg in args {
319 command.push(' ');
320 command.push_str(&arg);
321 }
322 spawn_task.command = shell;
323 user_args.extend(["-i".to_owned(), "-c".to_owned(), command]);
324 spawn_task.args = user_args;
325
326 let working_directory = spawn_in_terminal.cwd.clone();
327 let allow_concurrent_runs = spawn_in_terminal.allow_concurrent_runs;
328 let use_new_terminal = spawn_in_terminal.use_new_terminal;
329
330 if allow_concurrent_runs && use_new_terminal {
331 self.spawn_in_new_terminal(spawn_task, working_directory, cx);
332 return;
333 }
334
335 let terminals_for_task = self.terminals_for_task(&spawn_in_terminal.id, cx);
336 if terminals_for_task.is_empty() {
337 self.spawn_in_new_terminal(spawn_task, working_directory, cx);
338 return;
339 }
340 let (existing_item_index, existing_terminal) = terminals_for_task
341 .last()
342 .expect("covered no terminals case above")
343 .clone();
344 if allow_concurrent_runs {
345 debug_assert!(
346 !use_new_terminal,
347 "Should have handled 'allow_concurrent_runs && use_new_terminal' case above"
348 );
349 self.replace_terminal(
350 working_directory,
351 spawn_task,
352 existing_item_index,
353 existing_terminal,
354 cx,
355 );
356 } else {
357 self.deferred_tasks.insert(
358 spawn_in_terminal.id.clone(),
359 cx.spawn(|terminal_panel, mut cx| async move {
360 wait_for_terminals_tasks(terminals_for_task, &mut cx).await;
361 terminal_panel
362 .update(&mut cx, |terminal_panel, cx| {
363 if use_new_terminal {
364 terminal_panel.spawn_in_new_terminal(
365 spawn_task,
366 working_directory,
367 cx,
368 );
369 } else {
370 terminal_panel.replace_terminal(
371 working_directory,
372 spawn_task,
373 existing_item_index,
374 existing_terminal,
375 cx,
376 );
377 }
378 })
379 .ok();
380 }),
381 );
382 }
383 }
384
385 fn spawn_in_new_terminal(
386 &mut self,
387 spawn_task: SpawnTask,
388 working_directory: Option<PathBuf>,
389 cx: &mut ViewContext<Self>,
390 ) {
391 self.add_terminal(working_directory, Some(spawn_task), cx);
392 let task_workspace = self.workspace.clone();
393 cx.spawn(|_, mut cx| async move {
394 task_workspace
395 .update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
396 .ok()
397 })
398 .detach();
399 }
400
401 ///Create a new Terminal in the current working directory or the user's home directory
402 fn new_terminal(
403 workspace: &mut Workspace,
404 _: &workspace::NewTerminal,
405 cx: &mut ViewContext<Workspace>,
406 ) {
407 let Some(this) = workspace.focus_panel::<Self>(cx) else {
408 return;
409 };
410
411 this.update(cx, |this, cx| this.add_terminal(None, None, cx))
412 }
413
414 fn terminals_for_task(
415 &self,
416 id: &TaskId,
417 cx: &mut AppContext,
418 ) -> Vec<(usize, View<TerminalView>)> {
419 self.pane
420 .read(cx)
421 .items()
422 .enumerate()
423 .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
424 .filter_map(|(index, terminal_view)| {
425 let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
426 if &task_state.id == id {
427 Some((index, terminal_view))
428 } else {
429 None
430 }
431 })
432 .collect()
433 }
434
435 fn activate_terminal_view(&self, item_index: usize, cx: &mut WindowContext) {
436 self.pane.update(cx, |pane, cx| {
437 pane.activate_item(item_index, true, true, cx)
438 })
439 }
440
441 fn add_terminal(
442 &mut self,
443 working_directory: Option<PathBuf>,
444 spawn_task: Option<SpawnTask>,
445 cx: &mut ViewContext<Self>,
446 ) {
447 let workspace = self.workspace.clone();
448 self.pending_terminals_to_add += 1;
449 cx.spawn(|terminal_panel, mut cx| async move {
450 let pane = terminal_panel.update(&mut cx, |this, _| this.pane.clone())?;
451 workspace.update(&mut cx, |workspace, cx| {
452 let working_directory = if let Some(working_directory) = working_directory {
453 Some(working_directory)
454 } else {
455 let working_directory_strategy =
456 TerminalSettings::get_global(cx).working_directory.clone();
457 crate::get_working_directory(workspace, cx, working_directory_strategy)
458 };
459
460 let window = cx.window_handle();
461 if let Some(terminal) = workspace.project().update(cx, |project, cx| {
462 project
463 .create_terminal(working_directory, spawn_task, window, cx)
464 .log_err()
465 }) {
466 let terminal = Box::new(cx.new_view(|cx| {
467 TerminalView::new(
468 terminal,
469 workspace.weak_handle(),
470 workspace.database_id(),
471 cx,
472 )
473 }));
474 pane.update(cx, |pane, cx| {
475 let focus = pane.has_focus(cx);
476 pane.add_item(terminal, true, focus, None, cx);
477 });
478 }
479 })?;
480 terminal_panel.update(&mut cx, |this, cx| {
481 this.pending_terminals_to_add = this.pending_terminals_to_add.saturating_sub(1);
482 this.serialize(cx)
483 })?;
484 anyhow::Ok(())
485 })
486 .detach_and_log_err(cx);
487 }
488
489 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
490 let mut items_to_serialize = HashSet::default();
491 let items = self
492 .pane
493 .read(cx)
494 .items()
495 .filter_map(|item| {
496 let terminal_view = item.act_as::<TerminalView>(cx)?;
497 if terminal_view.read(cx).terminal().read(cx).task().is_some() {
498 None
499 } else {
500 let id = item.item_id().as_u64();
501 items_to_serialize.insert(id);
502 Some(id)
503 }
504 })
505 .collect::<Vec<_>>();
506 let active_item_id = self
507 .pane
508 .read(cx)
509 .active_item()
510 .map(|item| item.item_id().as_u64())
511 .filter(|active_id| items_to_serialize.contains(active_id));
512 let height = self.height;
513 let width = self.width;
514 self.pending_serialization = cx.background_executor().spawn(
515 async move {
516 KEY_VALUE_STORE
517 .write_kvp(
518 TERMINAL_PANEL_KEY.into(),
519 serde_json::to_string(&SerializedTerminalPanel {
520 items,
521 active_item_id,
522 height,
523 width,
524 })?,
525 )
526 .await?;
527 anyhow::Ok(())
528 }
529 .log_err(),
530 );
531 }
532
533 fn replace_terminal(
534 &self,
535 working_directory: Option<PathBuf>,
536 spawn_task: SpawnTask,
537 terminal_item_index: usize,
538 terminal_to_replace: View<TerminalView>,
539 cx: &mut ViewContext<'_, Self>,
540 ) -> Option<()> {
541 let project = self
542 .workspace
543 .update(cx, |workspace, _| workspace.project().clone())
544 .ok()?;
545 let window = cx.window_handle();
546 let new_terminal = project.update(cx, |project, cx| {
547 project
548 .create_terminal(working_directory, Some(spawn_task), window, cx)
549 .log_err()
550 })?;
551 terminal_to_replace.update(cx, |terminal_to_replace, cx| {
552 terminal_to_replace.set_terminal(new_terminal, cx);
553 });
554 self.activate_terminal_view(terminal_item_index, cx);
555 let task_workspace = self.workspace.clone();
556 cx.spawn(|_, mut cx| async move {
557 task_workspace
558 .update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
559 .ok()
560 })
561 .detach();
562 Some(())
563 }
564}
565
566async fn wait_for_terminals_tasks(
567 terminals_for_task: Vec<(usize, View<TerminalView>)>,
568 cx: &mut AsyncWindowContext,
569) {
570 let pending_tasks = terminals_for_task.iter().filter_map(|(_, terminal)| {
571 terminal
572 .update(cx, |terminal_view, cx| {
573 terminal_view
574 .terminal()
575 .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
576 })
577 .ok()
578 });
579 let _: Vec<()> = join_all(pending_tasks).await;
580}
581
582fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
583 if let Some(terminal_view) = pane
584 .active_item()
585 .and_then(|item| item.downcast::<TerminalView>())
586 {
587 cx.focus_view(&terminal_view);
588 let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
589 new_text.push(' ');
590 terminal_view.update(cx, |terminal_view, cx| {
591 terminal_view.terminal().update(cx, |terminal, _| {
592 terminal.paste(&new_text);
593 });
594 });
595 }
596}
597
598impl EventEmitter<PanelEvent> for TerminalPanel {}
599
600impl Render for TerminalPanel {
601 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
602 let mut registrar = DivRegistrar::new(
603 |panel, cx| {
604 panel
605 .pane
606 .read(cx)
607 .toolbar()
608 .read(cx)
609 .item_of_type::<BufferSearchBar>()
610 },
611 cx,
612 );
613 BufferSearchBar::register(&mut registrar);
614 registrar.into_div().size_full().child(self.pane.clone())
615 }
616}
617
618impl FocusableView for TerminalPanel {
619 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
620 self.pane.focus_handle(cx)
621 }
622}
623
624impl Panel for TerminalPanel {
625 fn position(&self, cx: &WindowContext) -> DockPosition {
626 match TerminalSettings::get_global(cx).dock {
627 TerminalDockPosition::Left => DockPosition::Left,
628 TerminalDockPosition::Bottom => DockPosition::Bottom,
629 TerminalDockPosition::Right => DockPosition::Right,
630 }
631 }
632
633 fn position_is_valid(&self, _: DockPosition) -> bool {
634 true
635 }
636
637 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
638 settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {
639 let dock = match position {
640 DockPosition::Left => TerminalDockPosition::Left,
641 DockPosition::Bottom => TerminalDockPosition::Bottom,
642 DockPosition::Right => TerminalDockPosition::Right,
643 };
644 settings.dock = Some(dock);
645 });
646 }
647
648 fn size(&self, cx: &WindowContext) -> Pixels {
649 let settings = TerminalSettings::get_global(cx);
650 match self.position(cx) {
651 DockPosition::Left | DockPosition::Right => {
652 self.width.unwrap_or_else(|| settings.default_width)
653 }
654 DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
655 }
656 }
657
658 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
659 match self.position(cx) {
660 DockPosition::Left | DockPosition::Right => self.width = size,
661 DockPosition::Bottom => self.height = size,
662 }
663 self.serialize(cx);
664 cx.notify();
665 }
666
667 fn is_zoomed(&self, cx: &WindowContext) -> bool {
668 self.pane.read(cx).is_zoomed()
669 }
670
671 fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
672 self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
673 }
674
675 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
676 if active && self.pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0 {
677 self.add_terminal(None, None, cx)
678 }
679 }
680
681 fn icon_label(&self, cx: &WindowContext) -> Option<String> {
682 let count = self.pane.read(cx).items_len();
683 if count == 0 {
684 None
685 } else {
686 Some(count.to_string())
687 }
688 }
689
690 fn persistent_name() -> &'static str {
691 "TerminalPanel"
692 }
693
694 fn icon(&self, _cx: &WindowContext) -> Option<IconName> {
695 Some(IconName::Terminal)
696 }
697
698 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
699 Some("Terminal Panel")
700 }
701
702 fn toggle_action(&self) -> Box<dyn gpui::Action> {
703 Box::new(ToggleFocus)
704 }
705}
706
707#[derive(Serialize, Deserialize)]
708struct SerializedTerminalPanel {
709 items: Vec<u64>,
710 active_item_id: Option<u64>,
711 width: Option<Pixels>,
712 height: Option<Pixels>,
713}