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