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: &'static 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;
196 panel.width = serialized_panel.width;
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 if spawn_in_terminal.separate_shell {
307 let Some((shell, mut user_args)) = (match TerminalSettings::get_global(cx).shell.clone()
308 {
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 command = std::mem::take(&mut spawn_task.command);
317 let args = std::mem::take(&mut spawn_task.args);
318 spawn_task.command = shell;
319 user_args.extend(["-i".to_owned(), "-c".to_owned(), command]);
320 user_args.extend(args);
321 spawn_task.args = user_args;
322 }
323 let working_directory = spawn_in_terminal.cwd.clone();
324 let allow_concurrent_runs = spawn_in_terminal.allow_concurrent_runs;
325 let use_new_terminal = spawn_in_terminal.use_new_terminal;
326
327 if allow_concurrent_runs && use_new_terminal {
328 self.spawn_in_new_terminal(spawn_task, working_directory, cx);
329 return;
330 }
331
332 let terminals_for_task = self.terminals_for_task(&spawn_in_terminal.id, cx);
333 if terminals_for_task.is_empty() {
334 self.spawn_in_new_terminal(spawn_task, working_directory, cx);
335 return;
336 }
337 let (existing_item_index, existing_terminal) = terminals_for_task
338 .last()
339 .expect("covered no terminals case above")
340 .clone();
341 if allow_concurrent_runs {
342 debug_assert!(
343 !use_new_terminal,
344 "Should have handled 'allow_concurrent_runs && use_new_terminal' case above"
345 );
346 self.replace_terminal(
347 working_directory,
348 spawn_task,
349 existing_item_index,
350 existing_terminal,
351 cx,
352 );
353 } else {
354 self.deferred_tasks.insert(
355 spawn_in_terminal.id.clone(),
356 cx.spawn(|terminal_panel, mut cx| async move {
357 wait_for_terminals_tasks(terminals_for_task, &mut cx).await;
358 terminal_panel
359 .update(&mut cx, |terminal_panel, cx| {
360 if use_new_terminal {
361 terminal_panel.spawn_in_new_terminal(
362 spawn_task,
363 working_directory,
364 cx,
365 );
366 } else {
367 terminal_panel.replace_terminal(
368 working_directory,
369 spawn_task,
370 existing_item_index,
371 existing_terminal,
372 cx,
373 );
374 }
375 })
376 .ok();
377 }),
378 );
379 }
380 }
381
382 fn spawn_in_new_terminal(
383 &mut self,
384 spawn_task: SpawnTask,
385 working_directory: Option<PathBuf>,
386 cx: &mut ViewContext<Self>,
387 ) {
388 self.add_terminal(working_directory, Some(spawn_task), cx);
389 let task_workspace = self.workspace.clone();
390 cx.spawn(|_, mut cx| async move {
391 task_workspace
392 .update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
393 .ok()
394 })
395 .detach();
396 }
397
398 ///Create a new Terminal in the current working directory or the user's home directory
399 fn new_terminal(
400 workspace: &mut Workspace,
401 _: &workspace::NewTerminal,
402 cx: &mut ViewContext<Workspace>,
403 ) {
404 let Some(this) = workspace.focus_panel::<Self>(cx) else {
405 return;
406 };
407
408 this.update(cx, |this, cx| this.add_terminal(None, None, cx))
409 }
410
411 fn terminals_for_task(
412 &self,
413 id: &TaskId,
414 cx: &mut AppContext,
415 ) -> Vec<(usize, View<TerminalView>)> {
416 self.pane
417 .read(cx)
418 .items()
419 .enumerate()
420 .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
421 .filter_map(|(index, terminal_view)| {
422 let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
423 if &task_state.id == id {
424 Some((index, terminal_view))
425 } else {
426 None
427 }
428 })
429 .collect()
430 }
431
432 fn activate_terminal_view(&self, item_index: usize, cx: &mut WindowContext) {
433 self.pane.update(cx, |pane, cx| {
434 pane.activate_item(item_index, true, true, cx)
435 })
436 }
437
438 fn add_terminal(
439 &mut self,
440 working_directory: Option<PathBuf>,
441 spawn_task: Option<SpawnTask>,
442 cx: &mut ViewContext<Self>,
443 ) {
444 let workspace = self.workspace.clone();
445 self.pending_terminals_to_add += 1;
446 cx.spawn(|terminal_panel, mut cx| async move {
447 let pane = terminal_panel.update(&mut cx, |this, _| this.pane.clone())?;
448 workspace.update(&mut cx, |workspace, cx| {
449 let working_directory = if let Some(working_directory) = working_directory {
450 Some(working_directory)
451 } else {
452 let working_directory_strategy =
453 TerminalSettings::get_global(cx).working_directory.clone();
454 crate::get_working_directory(workspace, cx, working_directory_strategy)
455 };
456
457 let window = cx.window_handle();
458 if let Some(terminal) = workspace.project().update(cx, |project, cx| {
459 project
460 .create_terminal(working_directory, spawn_task, window, cx)
461 .log_err()
462 }) {
463 let terminal = Box::new(cx.new_view(|cx| {
464 TerminalView::new(
465 terminal,
466 workspace.weak_handle(),
467 workspace.database_id(),
468 cx,
469 )
470 }));
471 pane.update(cx, |pane, cx| {
472 let focus = pane.has_focus(cx);
473 pane.add_item(terminal, true, focus, None, cx);
474 });
475 }
476 })?;
477 terminal_panel.update(&mut cx, |this, cx| {
478 this.pending_terminals_to_add = this.pending_terminals_to_add.saturating_sub(1);
479 this.serialize(cx)
480 })?;
481 anyhow::Ok(())
482 })
483 .detach_and_log_err(cx);
484 }
485
486 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
487 let mut items_to_serialize = HashSet::default();
488 let items = self
489 .pane
490 .read(cx)
491 .items()
492 .filter_map(|item| {
493 let terminal_view = item.act_as::<TerminalView>(cx)?;
494 if terminal_view.read(cx).terminal().read(cx).task().is_some() {
495 None
496 } else {
497 let id = item.item_id().as_u64();
498 items_to_serialize.insert(id);
499 Some(id)
500 }
501 })
502 .collect::<Vec<_>>();
503 let active_item_id = self
504 .pane
505 .read(cx)
506 .active_item()
507 .map(|item| item.item_id().as_u64())
508 .filter(|active_id| items_to_serialize.contains(active_id));
509 let height = self.height;
510 let width = self.width;
511 self.pending_serialization = cx.background_executor().spawn(
512 async move {
513 KEY_VALUE_STORE
514 .write_kvp(
515 TERMINAL_PANEL_KEY.into(),
516 serde_json::to_string(&SerializedTerminalPanel {
517 items,
518 active_item_id,
519 height,
520 width,
521 })?,
522 )
523 .await?;
524 anyhow::Ok(())
525 }
526 .log_err(),
527 );
528 }
529
530 fn replace_terminal(
531 &self,
532 working_directory: Option<PathBuf>,
533 spawn_task: SpawnTask,
534 terminal_item_index: usize,
535 terminal_to_replace: View<TerminalView>,
536 cx: &mut ViewContext<'_, Self>,
537 ) -> Option<()> {
538 let project = self
539 .workspace
540 .update(cx, |workspace, _| workspace.project().clone())
541 .ok()?;
542 let window = cx.window_handle();
543 let new_terminal = project.update(cx, |project, cx| {
544 project
545 .create_terminal(working_directory, Some(spawn_task), window, cx)
546 .log_err()
547 })?;
548 terminal_to_replace.update(cx, |terminal_to_replace, cx| {
549 terminal_to_replace.set_terminal(new_terminal, cx);
550 });
551 self.activate_terminal_view(terminal_item_index, cx);
552 let task_workspace = self.workspace.clone();
553 cx.spawn(|_, mut cx| async move {
554 task_workspace
555 .update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
556 .ok()
557 })
558 .detach();
559 Some(())
560 }
561}
562
563async fn wait_for_terminals_tasks(
564 terminals_for_task: Vec<(usize, View<TerminalView>)>,
565 cx: &mut AsyncWindowContext,
566) {
567 let pending_tasks = terminals_for_task.iter().filter_map(|(_, terminal)| {
568 terminal
569 .update(cx, |terminal_view, cx| {
570 terminal_view
571 .terminal()
572 .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
573 })
574 .ok()
575 });
576 let _: Vec<()> = join_all(pending_tasks).await;
577}
578
579fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
580 if let Some(terminal_view) = pane
581 .active_item()
582 .and_then(|item| item.downcast::<TerminalView>())
583 {
584 cx.focus_view(&terminal_view);
585 let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
586 new_text.push(' ');
587 terminal_view.update(cx, |terminal_view, cx| {
588 terminal_view.terminal().update(cx, |terminal, _| {
589 terminal.paste(&new_text);
590 });
591 });
592 }
593}
594
595impl EventEmitter<PanelEvent> for TerminalPanel {}
596
597impl Render for TerminalPanel {
598 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
599 let mut registrar = DivRegistrar::new(
600 |panel, cx| {
601 panel
602 .pane
603 .read(cx)
604 .toolbar()
605 .read(cx)
606 .item_of_type::<BufferSearchBar>()
607 },
608 cx,
609 );
610 BufferSearchBar::register(&mut registrar);
611 registrar.into_div().size_full().child(self.pane.clone())
612 }
613}
614
615impl FocusableView for TerminalPanel {
616 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
617 self.pane.focus_handle(cx)
618 }
619}
620
621impl Panel for TerminalPanel {
622 fn position(&self, cx: &WindowContext) -> DockPosition {
623 match TerminalSettings::get_global(cx).dock {
624 TerminalDockPosition::Left => DockPosition::Left,
625 TerminalDockPosition::Bottom => DockPosition::Bottom,
626 TerminalDockPosition::Right => DockPosition::Right,
627 }
628 }
629
630 fn position_is_valid(&self, _: DockPosition) -> bool {
631 true
632 }
633
634 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
635 settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {
636 let dock = match position {
637 DockPosition::Left => TerminalDockPosition::Left,
638 DockPosition::Bottom => TerminalDockPosition::Bottom,
639 DockPosition::Right => TerminalDockPosition::Right,
640 };
641 settings.dock = Some(dock);
642 });
643 }
644
645 fn size(&self, cx: &WindowContext) -> Pixels {
646 let settings = TerminalSettings::get_global(cx);
647 match self.position(cx) {
648 DockPosition::Left | DockPosition::Right => {
649 self.width.unwrap_or_else(|| settings.default_width)
650 }
651 DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
652 }
653 }
654
655 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
656 match self.position(cx) {
657 DockPosition::Left | DockPosition::Right => self.width = size,
658 DockPosition::Bottom => self.height = size,
659 }
660 self.serialize(cx);
661 cx.notify();
662 }
663
664 fn is_zoomed(&self, cx: &WindowContext) -> bool {
665 self.pane.read(cx).is_zoomed()
666 }
667
668 fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
669 self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
670 }
671
672 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
673 if active && self.pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0 {
674 self.add_terminal(None, None, cx)
675 }
676 }
677
678 fn icon_label(&self, cx: &WindowContext) -> Option<String> {
679 let count = self.pane.read(cx).items_len();
680 if count == 0 {
681 None
682 } else {
683 Some(count.to_string())
684 }
685 }
686
687 fn persistent_name() -> &'static str {
688 "TerminalPanel"
689 }
690
691 fn icon(&self, _cx: &WindowContext) -> Option<IconName> {
692 Some(IconName::Terminal)
693 }
694
695 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
696 Some("Terminal Panel")
697 }
698
699 fn toggle_action(&self) -> Box<dyn gpui::Action> {
700 Box::new(ToggleFocus)
701 }
702}
703
704#[derive(Serialize, Deserialize)]
705struct SerializedTerminalPanel {
706 items: Vec<u64>,
707 active_item_id: Option<u64>,
708 width: Option<Pixels>,
709 height: Option<Pixels>,
710}