1use std::{cmp, ops::ControlFlow, path::PathBuf, sync::Arc, time::Duration};
2
3use crate::{
4 default_working_directory,
5 persistence::{
6 deserialize_terminal_panel, serialize_pane_group, SerializedItems, SerializedTerminalPanel,
7 },
8 TerminalView,
9};
10use breadcrumbs::Breadcrumbs;
11use collections::HashMap;
12use db::kvp::KEY_VALUE_STORE;
13use futures::future::join_all;
14use gpui::{
15 actions, Action, AnchorCorner, AnyView, AppContext, AsyncWindowContext, EventEmitter,
16 ExternalPaths, FocusHandle, FocusableView, IntoElement, Model, ParentElement, Pixels, Render,
17 Styled, Task, View, ViewContext, VisualContext, WeakView, WindowContext,
18};
19use itertools::Itertools;
20use project::{terminals::TerminalKind, Fs, Project, ProjectEntryId};
21use search::{buffer_search::DivRegistrar, BufferSearchBar};
22use settings::Settings;
23use task::{RevealStrategy, Shell, SpawnInTerminal, TaskId};
24use terminal::{
25 terminal_settings::{TerminalDockPosition, TerminalSettings},
26 Terminal,
27};
28use ui::{
29 prelude::*, ButtonCommon, Clickable, ContextMenu, FluentBuilder, PopoverMenu, Selectable,
30 Tooltip,
31};
32use util::{ResultExt, TryFutureExt};
33use workspace::{
34 dock::{DockPosition, Panel, PanelEvent},
35 item::SerializableItem,
36 move_item, pane,
37 ui::IconName,
38 ActivateNextPane, ActivatePane, ActivatePaneInDirection, ActivatePreviousPane, DraggedTab,
39 ItemId, NewTerminal, Pane, PaneGroup, SplitDirection, SplitDown, SplitLeft, SplitRight,
40 SplitUp, SwapPaneInDirection, ToggleZoom, Workspace,
41};
42
43use anyhow::Result;
44use zed_actions::InlineAssist;
45
46const TERMINAL_PANEL_KEY: &str = "TerminalPanel";
47
48actions!(terminal_panel, [ToggleFocus]);
49
50pub fn init(cx: &mut AppContext) {
51 cx.observe_new_views(
52 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
53 workspace.register_action(TerminalPanel::new_terminal);
54 workspace.register_action(TerminalPanel::open_terminal);
55 workspace.register_action(|workspace, _: &ToggleFocus, cx| {
56 if workspace
57 .panel::<TerminalPanel>(cx)
58 .as_ref()
59 .is_some_and(|panel| panel.read(cx).enabled)
60 {
61 workspace.toggle_panel_focus::<TerminalPanel>(cx);
62 }
63 });
64 },
65 )
66 .detach();
67}
68
69pub struct TerminalPanel {
70 pub(crate) active_pane: View<Pane>,
71 pub(crate) center: PaneGroup,
72 fs: Arc<dyn Fs>,
73 workspace: WeakView<Workspace>,
74 pub(crate) width: Option<Pixels>,
75 pub(crate) height: Option<Pixels>,
76 pending_serialization: Task<Option<()>>,
77 pending_terminals_to_add: usize,
78 deferred_tasks: HashMap<TaskId, Task<()>>,
79 enabled: bool,
80 assistant_enabled: bool,
81 assistant_tab_bar_button: Option<AnyView>,
82}
83
84impl TerminalPanel {
85 pub fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
86 let project = workspace.project();
87 let pane = new_terminal_pane(workspace.weak_handle(), project.clone(), cx);
88 let center = PaneGroup::new(pane.clone());
89 let enabled = project.read(cx).supports_terminal(cx);
90 let terminal_panel = Self {
91 center,
92 active_pane: pane,
93 fs: workspace.app_state().fs.clone(),
94 workspace: workspace.weak_handle(),
95 pending_serialization: Task::ready(None),
96 width: None,
97 height: None,
98 pending_terminals_to_add: 0,
99 deferred_tasks: HashMap::default(),
100 enabled,
101 assistant_enabled: false,
102 assistant_tab_bar_button: None,
103 };
104 terminal_panel.apply_tab_bar_buttons(&terminal_panel.active_pane, cx);
105 terminal_panel
106 }
107
108 pub fn asssistant_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
109 self.assistant_enabled = enabled;
110 if enabled {
111 let focus_handle = self
112 .active_pane
113 .read(cx)
114 .active_item()
115 .map(|item| item.focus_handle(cx))
116 .unwrap_or(self.focus_handle(cx));
117 self.assistant_tab_bar_button = Some(
118 cx.new_view(move |_| InlineAssistTabBarButton { focus_handle })
119 .into(),
120 );
121 } else {
122 self.assistant_tab_bar_button = None;
123 }
124 for pane in self.center.panes() {
125 self.apply_tab_bar_buttons(pane, cx);
126 }
127 }
128
129 fn apply_tab_bar_buttons(&self, terminal_pane: &View<Pane>, cx: &mut ViewContext<Self>) {
130 let assistant_tab_bar_button = self.assistant_tab_bar_button.clone();
131 terminal_pane.update(cx, |pane, cx| {
132 pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
133 let split_context = pane
134 .active_item()
135 .and_then(|item| item.downcast::<TerminalView>())
136 .map(|terminal_view| terminal_view.read(cx).focus_handle.clone());
137 if !pane.has_focus(cx) && !pane.context_menu_focused(cx) {
138 return (None, None);
139 }
140 let focus_handle = pane.focus_handle(cx);
141 let right_children = h_flex()
142 .gap(DynamicSpacing::Base02.rems(cx))
143 .child(
144 PopoverMenu::new("terminal-tab-bar-popover-menu")
145 .trigger(
146 IconButton::new("plus", IconName::Plus)
147 .icon_size(IconSize::Small)
148 .tooltip(|cx| Tooltip::text("Newβ¦", cx)),
149 )
150 .anchor(AnchorCorner::TopRight)
151 .with_handle(pane.new_item_context_menu_handle.clone())
152 .menu(move |cx| {
153 let focus_handle = focus_handle.clone();
154 let menu = ContextMenu::build(cx, |menu, _| {
155 menu.context(focus_handle.clone())
156 .action(
157 "New Terminal",
158 workspace::NewTerminal.boxed_clone(),
159 )
160 // We want the focus to go back to terminal panel once task modal is dismissed,
161 // hence we focus that first. Otherwise, we'd end up without a focused element, as
162 // context menu will be gone the moment we spawn the modal.
163 .action(
164 "Spawn task",
165 zed_actions::Spawn::modal().boxed_clone(),
166 )
167 });
168
169 Some(menu)
170 }),
171 )
172 .children(assistant_tab_bar_button.clone())
173 .child(
174 PopoverMenu::new("terminal-pane-tab-bar-split")
175 .trigger(
176 IconButton::new("terminal-pane-split", IconName::Split)
177 .icon_size(IconSize::Small)
178 .tooltip(|cx| Tooltip::text("Split Pane", cx)),
179 )
180 .anchor(AnchorCorner::TopRight)
181 .with_handle(pane.split_item_context_menu_handle.clone())
182 .menu({
183 let split_context = split_context.clone();
184 move |cx| {
185 ContextMenu::build(cx, |menu, _| {
186 menu.when_some(
187 split_context.clone(),
188 |menu, split_context| menu.context(split_context),
189 )
190 .action("Split Right", SplitRight.boxed_clone())
191 .action("Split Left", SplitLeft.boxed_clone())
192 .action("Split Up", SplitUp.boxed_clone())
193 .action("Split Down", SplitDown.boxed_clone())
194 })
195 .into()
196 }
197 }),
198 )
199 .child({
200 let zoomed = pane.is_zoomed();
201 IconButton::new("toggle_zoom", IconName::Maximize)
202 .icon_size(IconSize::Small)
203 .selected(zoomed)
204 .selected_icon(IconName::Minimize)
205 .on_click(cx.listener(|pane, _, cx| {
206 pane.toggle_zoom(&workspace::ToggleZoom, cx);
207 }))
208 .tooltip(move |cx| {
209 Tooltip::for_action(
210 if zoomed { "Zoom Out" } else { "Zoom In" },
211 &ToggleZoom,
212 cx,
213 )
214 })
215 })
216 .into_any_element()
217 .into();
218 (None, right_children)
219 });
220 });
221 }
222
223 pub async fn load(
224 workspace: WeakView<Workspace>,
225 mut cx: AsyncWindowContext,
226 ) -> Result<View<Self>> {
227 let serialized_panel = cx
228 .background_executor()
229 .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })
230 .await
231 .log_err()
232 .flatten()
233 .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
234 .transpose()
235 .log_err()
236 .flatten();
237
238 let terminal_panel = workspace
239 .update(&mut cx, |workspace, cx| {
240 match serialized_panel.zip(workspace.database_id()) {
241 Some((serialized_panel, database_id)) => deserialize_terminal_panel(
242 workspace.weak_handle(),
243 workspace.project().clone(),
244 database_id,
245 serialized_panel,
246 cx,
247 ),
248 None => Task::ready(Ok(cx.new_view(|cx| TerminalPanel::new(workspace, cx)))),
249 }
250 })?
251 .await?;
252
253 if let Some(workspace) = workspace.upgrade() {
254 terminal_panel
255 .update(&mut cx, |_, cx| {
256 cx.subscribe(&workspace, |terminal_panel, _, e, cx| {
257 if let workspace::Event::SpawnTask(spawn_in_terminal) = e {
258 terminal_panel.spawn_task(spawn_in_terminal, cx);
259 };
260 })
261 .detach();
262 })
263 .ok();
264 }
265
266 // Since panels/docks are loaded outside from the workspace, we cleanup here, instead of through the workspace.
267 if let Some(workspace) = workspace.upgrade() {
268 let cleanup_task = workspace.update(&mut cx, |workspace, cx| {
269 let alive_item_ids = terminal_panel
270 .read(cx)
271 .center
272 .panes()
273 .into_iter()
274 .flat_map(|pane| pane.read(cx).items())
275 .map(|item| item.item_id().as_u64() as ItemId)
276 .collect();
277 workspace
278 .database_id()
279 .map(|workspace_id| TerminalView::cleanup(workspace_id, alive_item_ids, cx))
280 })?;
281 if let Some(task) = cleanup_task {
282 task.await.log_err();
283 }
284 }
285
286 Ok(terminal_panel)
287 }
288
289 fn handle_pane_event(
290 &mut self,
291 pane: View<Pane>,
292 event: &pane::Event,
293 cx: &mut ViewContext<Self>,
294 ) {
295 match event {
296 pane::Event::ActivateItem { .. } => self.serialize(cx),
297 pane::Event::RemovedItem { .. } => self.serialize(cx),
298 pane::Event::Remove { focus_on_pane } => {
299 let pane_count_before_removal = self.center.panes().len();
300 let _removal_result = self.center.remove(&pane);
301 if pane_count_before_removal == 1 {
302 cx.emit(PanelEvent::Close);
303 } else {
304 if let Some(focus_on_pane) =
305 focus_on_pane.as_ref().or_else(|| self.center.panes().pop())
306 {
307 focus_on_pane.focus_handle(cx).focus(cx);
308 }
309 }
310 }
311 pane::Event::ZoomIn => cx.emit(PanelEvent::ZoomIn),
312 pane::Event::ZoomOut => cx.emit(PanelEvent::ZoomOut),
313 pane::Event::AddItem { item } => {
314 if let Some(workspace) = self.workspace.upgrade() {
315 workspace.update(cx, |workspace, cx| {
316 item.added_to_pane(workspace, pane.clone(), cx)
317 })
318 }
319 }
320 pane::Event::Split(direction) => {
321 let new_pane = self.new_pane_with_cloned_active_terminal(cx);
322 let pane = pane.clone();
323 let direction = *direction;
324 cx.spawn(move |this, mut cx| async move {
325 let Some(new_pane) = new_pane.await else {
326 return;
327 };
328 this.update(&mut cx, |this, _| {
329 this.center.split(&pane, &new_pane, direction).log_err();
330 })
331 .ok();
332 })
333 .detach();
334 }
335 pane::Event::Focus => {
336 self.active_pane = pane.clone();
337 }
338
339 _ => {}
340 }
341 }
342
343 fn new_pane_with_cloned_active_terminal(
344 &mut self,
345 cx: &mut ViewContext<Self>,
346 ) -> Task<Option<View<Pane>>> {
347 let Some(workspace) = self.workspace.clone().upgrade() else {
348 return Task::ready(None);
349 };
350 let database_id = workspace.read(cx).database_id();
351 let weak_workspace = self.workspace.clone();
352 let project = workspace.read(cx).project().clone();
353 let working_directory = self
354 .active_pane
355 .read(cx)
356 .active_item()
357 .and_then(|item| item.downcast::<TerminalView>())
358 .and_then(|terminal_view| {
359 terminal_view
360 .read(cx)
361 .terminal()
362 .read(cx)
363 .working_directory()
364 })
365 .or_else(|| default_working_directory(workspace.read(cx), cx));
366 let kind = TerminalKind::Shell(working_directory);
367 let window = cx.window_handle();
368 cx.spawn(move |this, mut cx| async move {
369 let terminal = project
370 .update(&mut cx, |project, cx| {
371 project.create_terminal(kind, window, cx)
372 })
373 .log_err()?
374 .await
375 .log_err()?;
376
377 let terminal_view = Box::new(
378 cx.new_view(|cx| {
379 TerminalView::new(terminal.clone(), weak_workspace.clone(), database_id, cx)
380 })
381 .ok()?,
382 );
383 let pane = this
384 .update(&mut cx, |this, cx| {
385 let pane = new_terminal_pane(weak_workspace, project, cx);
386 this.apply_tab_bar_buttons(&pane, cx);
387 pane
388 })
389 .ok()?;
390
391 pane.update(&mut cx, |pane, cx| {
392 pane.add_item(terminal_view, true, true, None, cx);
393 })
394 .ok()?;
395 cx.focus_view(&pane).ok()?;
396
397 Some(pane)
398 })
399 }
400
401 pub fn open_terminal(
402 workspace: &mut Workspace,
403 action: &workspace::OpenTerminal,
404 cx: &mut ViewContext<Workspace>,
405 ) {
406 let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
407 return;
408 };
409
410 terminal_panel
411 .update(cx, |panel, cx| {
412 panel.add_terminal(
413 TerminalKind::Shell(Some(action.working_directory.clone())),
414 RevealStrategy::Always,
415 cx,
416 )
417 })
418 .detach_and_log_err(cx);
419 }
420
421 fn spawn_task(&mut self, spawn_in_terminal: &SpawnInTerminal, cx: &mut ViewContext<Self>) {
422 let mut spawn_task = spawn_in_terminal.clone();
423 // Set up shell args unconditionally, as tasks are always spawned inside of a shell.
424 let Some((shell, mut user_args)) = (match spawn_in_terminal.shell.clone() {
425 Shell::System => {
426 match self
427 .workspace
428 .update(cx, |workspace, cx| workspace.project().read(cx).is_local())
429 {
430 Ok(local) => {
431 if local {
432 retrieve_system_shell().map(|shell| (shell, Vec::new()))
433 } else {
434 Some(("\"${SHELL:-sh}\"".to_string(), Vec::new()))
435 }
436 }
437 Err(_no_window_e) => return,
438 }
439 }
440 Shell::Program(shell) => Some((shell, Vec::new())),
441 Shell::WithArguments { program, args, .. } => Some((program, args)),
442 }) else {
443 return;
444 };
445 #[cfg(target_os = "windows")]
446 let windows_shell_type = to_windows_shell_type(&shell);
447
448 #[cfg(not(target_os = "windows"))]
449 {
450 spawn_task.command_label = format!("{shell} -i -c '{}'", spawn_task.command_label);
451 }
452 #[cfg(target_os = "windows")]
453 {
454 use crate::terminal_panel::WindowsShellType;
455
456 match windows_shell_type {
457 WindowsShellType::Powershell => {
458 spawn_task.command_label = format!("{shell} -C '{}'", spawn_task.command_label)
459 }
460 WindowsShellType::Cmd => {
461 spawn_task.command_label = format!("{shell} /C '{}'", spawn_task.command_label)
462 }
463 WindowsShellType::Other => {
464 spawn_task.command_label =
465 format!("{shell} -i -c '{}'", spawn_task.command_label)
466 }
467 }
468 }
469
470 let task_command = std::mem::replace(&mut spawn_task.command, shell);
471 let task_args = std::mem::take(&mut spawn_task.args);
472 let combined_command = task_args
473 .into_iter()
474 .fold(task_command, |mut command, arg| {
475 command.push(' ');
476 #[cfg(not(target_os = "windows"))]
477 command.push_str(&arg);
478 #[cfg(target_os = "windows")]
479 command.push_str(&to_windows_shell_variable(windows_shell_type, arg));
480 command
481 });
482
483 #[cfg(not(target_os = "windows"))]
484 user_args.extend(["-i".to_owned(), "-c".to_owned(), combined_command]);
485 #[cfg(target_os = "windows")]
486 {
487 use crate::terminal_panel::WindowsShellType;
488
489 match windows_shell_type {
490 WindowsShellType::Powershell => {
491 user_args.extend(["-C".to_owned(), combined_command])
492 }
493 WindowsShellType::Cmd => user_args.extend(["/C".to_owned(), combined_command]),
494 WindowsShellType::Other => {
495 user_args.extend(["-i".to_owned(), "-c".to_owned(), combined_command])
496 }
497 }
498 }
499 spawn_task.args = user_args;
500 let spawn_task = spawn_task;
501
502 let allow_concurrent_runs = spawn_in_terminal.allow_concurrent_runs;
503 let use_new_terminal = spawn_in_terminal.use_new_terminal;
504
505 if allow_concurrent_runs && use_new_terminal {
506 self.spawn_in_new_terminal(spawn_task, cx)
507 .detach_and_log_err(cx);
508 return;
509 }
510
511 let terminals_for_task = self.terminals_for_task(&spawn_in_terminal.full_label, cx);
512 if terminals_for_task.is_empty() {
513 self.spawn_in_new_terminal(spawn_task, cx)
514 .detach_and_log_err(cx);
515 return;
516 }
517 let (existing_item_index, task_pane, existing_terminal) = terminals_for_task
518 .last()
519 .expect("covered no terminals case above")
520 .clone();
521 let id = spawn_in_terminal.id.clone();
522 cx.spawn(move |this, mut cx| async move {
523 if allow_concurrent_runs {
524 debug_assert!(
525 !use_new_terminal,
526 "Should have handled 'allow_concurrent_runs && use_new_terminal' case above"
527 );
528 this.update(&mut cx, |this, cx| {
529 this.replace_terminal(
530 spawn_task,
531 task_pane,
532 existing_item_index,
533 existing_terminal,
534 cx,
535 )
536 })?
537 .await;
538 } else {
539 this.update(&mut cx, |this, cx| {
540 this.deferred_tasks.insert(
541 id,
542 cx.spawn(|terminal_panel, mut cx| async move {
543 wait_for_terminals_tasks(terminals_for_task, &mut cx).await;
544 let Ok(Some(new_terminal_task)) =
545 terminal_panel.update(&mut cx, |terminal_panel, cx| {
546 if use_new_terminal {
547 terminal_panel
548 .spawn_in_new_terminal(spawn_task, cx)
549 .detach_and_log_err(cx);
550 None
551 } else {
552 Some(terminal_panel.replace_terminal(
553 spawn_task,
554 task_pane,
555 existing_item_index,
556 existing_terminal,
557 cx,
558 ))
559 }
560 })
561 else {
562 return;
563 };
564 new_terminal_task.await;
565 }),
566 );
567 })
568 .ok();
569 }
570 anyhow::Result::<_, anyhow::Error>::Ok(())
571 })
572 .detach()
573 }
574
575 pub fn spawn_in_new_terminal(
576 &mut self,
577 spawn_task: SpawnInTerminal,
578 cx: &mut ViewContext<Self>,
579 ) -> Task<Result<Model<Terminal>>> {
580 let reveal = spawn_task.reveal;
581 self.add_terminal(TerminalKind::Task(spawn_task), reveal, cx)
582 }
583
584 /// Create a new Terminal in the current working directory or the user's home directory
585 fn new_terminal(
586 workspace: &mut Workspace,
587 _: &workspace::NewTerminal,
588 cx: &mut ViewContext<Workspace>,
589 ) {
590 let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
591 return;
592 };
593
594 let kind = TerminalKind::Shell(default_working_directory(workspace, cx));
595
596 terminal_panel
597 .update(cx, |this, cx| {
598 this.add_terminal(kind, RevealStrategy::Always, cx)
599 })
600 .detach_and_log_err(cx);
601 }
602
603 fn terminals_for_task(
604 &self,
605 label: &str,
606 cx: &mut AppContext,
607 ) -> Vec<(usize, View<Pane>, View<TerminalView>)> {
608 self.center
609 .panes()
610 .into_iter()
611 .flat_map(|pane| {
612 pane.read(cx)
613 .items()
614 .enumerate()
615 .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
616 .filter_map(|(index, terminal_view)| {
617 let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
618 if &task_state.full_label == label {
619 Some((index, terminal_view))
620 } else {
621 None
622 }
623 })
624 .map(|(index, terminal_view)| (index, pane.clone(), terminal_view))
625 })
626 .collect()
627 }
628
629 fn activate_terminal_view(
630 &self,
631 pane: &View<Pane>,
632 item_index: usize,
633 focus: bool,
634 cx: &mut WindowContext,
635 ) {
636 pane.update(cx, |pane, cx| {
637 pane.activate_item(item_index, true, focus, cx)
638 })
639 }
640
641 fn add_terminal(
642 &mut self,
643 kind: TerminalKind,
644 reveal_strategy: RevealStrategy,
645 cx: &mut ViewContext<Self>,
646 ) -> Task<Result<Model<Terminal>>> {
647 if !self.enabled {
648 return Task::ready(Err(anyhow::anyhow!(
649 "terminal not yet supported for remote projects"
650 )));
651 }
652
653 let workspace = self.workspace.clone();
654 self.pending_terminals_to_add += 1;
655
656 cx.spawn(|terminal_panel, mut cx| async move {
657 let pane = terminal_panel.update(&mut cx, |this, _| this.active_pane.clone())?;
658 let project = workspace.update(&mut cx, |workspace, _| workspace.project().clone())?;
659 let window = cx.window_handle();
660 let terminal = project
661 .update(&mut cx, |project, cx| {
662 project.create_terminal(kind, window, cx)
663 })?
664 .await?;
665 let result = workspace.update(&mut cx, |workspace, cx| {
666 let terminal_view = Box::new(cx.new_view(|cx| {
667 TerminalView::new(
668 terminal.clone(),
669 workspace.weak_handle(),
670 workspace.database_id(),
671 cx,
672 )
673 }));
674 pane.update(cx, |pane, cx| {
675 let focus = pane.has_focus(cx);
676 pane.add_item(terminal_view, true, focus, None, cx);
677 });
678
679 match reveal_strategy {
680 RevealStrategy::Always => {
681 workspace.focus_panel::<Self>(cx);
682 }
683 RevealStrategy::NoFocus => {
684 workspace.open_panel::<Self>(cx);
685 }
686 RevealStrategy::Never => {}
687 }
688 Ok(terminal)
689 })?;
690 terminal_panel.update(&mut cx, |this, cx| {
691 this.pending_terminals_to_add = this.pending_terminals_to_add.saturating_sub(1);
692 this.serialize(cx)
693 })?;
694 result
695 })
696 }
697
698 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
699 let height = self.height;
700 let width = self.width;
701 self.pending_serialization = cx.spawn(|terminal_panel, mut cx| async move {
702 cx.background_executor()
703 .timer(Duration::from_millis(50))
704 .await;
705 let terminal_panel = terminal_panel.upgrade()?;
706 let items = terminal_panel
707 .update(&mut cx, |terminal_panel, cx| {
708 SerializedItems::WithSplits(serialize_pane_group(
709 &terminal_panel.center,
710 &terminal_panel.active_pane,
711 cx,
712 ))
713 })
714 .ok()?;
715 cx.background_executor()
716 .spawn(
717 async move {
718 KEY_VALUE_STORE
719 .write_kvp(
720 TERMINAL_PANEL_KEY.into(),
721 serde_json::to_string(&SerializedTerminalPanel {
722 items,
723 active_item_id: None,
724 height,
725 width,
726 })?,
727 )
728 .await?;
729 anyhow::Ok(())
730 }
731 .log_err(),
732 )
733 .await;
734 Some(())
735 });
736 }
737
738 fn replace_terminal(
739 &self,
740 spawn_task: SpawnInTerminal,
741 task_pane: View<Pane>,
742 terminal_item_index: usize,
743 terminal_to_replace: View<TerminalView>,
744 cx: &mut ViewContext<'_, Self>,
745 ) -> Task<Option<()>> {
746 let reveal = spawn_task.reveal;
747 let window = cx.window_handle();
748 let task_workspace = self.workspace.clone();
749 cx.spawn(move |this, mut cx| async move {
750 let project = this
751 .update(&mut cx, |this, cx| {
752 this.workspace
753 .update(cx, |workspace, _| workspace.project().clone())
754 .ok()
755 })
756 .ok()
757 .flatten()?;
758 let new_terminal = project
759 .update(&mut cx, |project, cx| {
760 project.create_terminal(TerminalKind::Task(spawn_task), window, cx)
761 })
762 .ok()?
763 .await
764 .log_err()?;
765 terminal_to_replace
766 .update(&mut cx, |terminal_to_replace, cx| {
767 terminal_to_replace.set_terminal(new_terminal, cx);
768 })
769 .ok()?;
770
771 match reveal {
772 RevealStrategy::Always => {
773 this.update(&mut cx, |this, cx| {
774 this.activate_terminal_view(&task_pane, terminal_item_index, true, cx)
775 })
776 .ok()?;
777
778 cx.spawn(|mut cx| async move {
779 task_workspace
780 .update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
781 .ok()
782 })
783 .detach();
784 }
785 RevealStrategy::NoFocus => {
786 this.update(&mut cx, |this, cx| {
787 this.activate_terminal_view(&task_pane, terminal_item_index, false, cx)
788 })
789 .ok()?;
790
791 cx.spawn(|mut cx| async move {
792 task_workspace
793 .update(&mut cx, |workspace, cx| workspace.open_panel::<Self>(cx))
794 .ok()
795 })
796 .detach();
797 }
798 RevealStrategy::Never => {}
799 }
800
801 Some(())
802 })
803 }
804
805 fn has_no_terminals(&self, cx: &WindowContext) -> bool {
806 self.active_pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
807 }
808
809 pub fn assistant_enabled(&self) -> bool {
810 self.assistant_enabled
811 }
812}
813
814pub fn new_terminal_pane(
815 workspace: WeakView<Workspace>,
816 project: Model<Project>,
817 cx: &mut ViewContext<TerminalPanel>,
818) -> View<Pane> {
819 let is_local = project.read(cx).is_local();
820 let terminal_panel = cx.view().clone();
821 let pane = cx.new_view(|cx| {
822 let mut pane = Pane::new(
823 workspace.clone(),
824 project.clone(),
825 Default::default(),
826 None,
827 NewTerminal.boxed_clone(),
828 cx,
829 );
830 pane.set_can_navigate(false, cx);
831 pane.display_nav_history_buttons(None);
832 pane.set_should_display_tab_bar(|_| true);
833
834 let terminal_panel_for_split_check = terminal_panel.clone();
835 pane.set_can_split(Some(Arc::new(move |pane, dragged_item, cx| {
836 if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
837 let current_pane = cx.view().clone();
838 let can_drag_away =
839 terminal_panel_for_split_check.update(cx, |terminal_panel, _| {
840 let current_panes = terminal_panel.center.panes();
841 !current_panes.contains(&&tab.pane)
842 || current_panes.len() > 1
843 || (tab.pane != current_pane || pane.items_len() > 1)
844 });
845 if can_drag_away {
846 let item = if tab.pane == current_pane {
847 pane.item_for_index(tab.ix)
848 } else {
849 tab.pane.read(cx).item_for_index(tab.ix)
850 };
851 if let Some(item) = item {
852 return item.downcast::<TerminalView>().is_some();
853 }
854 }
855 }
856 false
857 })));
858
859 let buffer_search_bar = cx.new_view(search::BufferSearchBar::new);
860 let breadcrumbs = cx.new_view(|_| Breadcrumbs::new());
861 pane.toolbar().update(cx, |toolbar, cx| {
862 toolbar.add_item(buffer_search_bar, cx);
863 toolbar.add_item(breadcrumbs, cx);
864 });
865
866 pane.set_custom_drop_handle(cx, move |pane, dropped_item, cx| {
867 if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
868 let this_pane = cx.view().clone();
869 let belongs_to_this_pane = tab.pane == this_pane;
870 let item = if belongs_to_this_pane {
871 pane.item_for_index(tab.ix)
872 } else {
873 tab.pane.read(cx).item_for_index(tab.ix)
874 };
875 if let Some(item) = item {
876 if item.downcast::<TerminalView>().is_some() {
877 let source = tab.pane.clone();
878 let item_id_to_move = item.item_id();
879
880 let new_pane = pane.drag_split_direction().and_then(|split_direction| {
881 terminal_panel.update(cx, |terminal_panel, cx| {
882 let new_pane =
883 new_terminal_pane(workspace.clone(), project.clone(), cx);
884 terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
885 terminal_panel
886 .center
887 .split(&this_pane, &new_pane, split_direction)
888 .log_err()?;
889 Some(new_pane)
890 })
891 });
892
893 let destination;
894 let destination_index;
895 if let Some(new_pane) = new_pane {
896 destination_index = new_pane.read(cx).active_item_index();
897 destination = new_pane;
898 } else if belongs_to_this_pane {
899 return ControlFlow::Break(());
900 } else {
901 destination = cx.view().clone();
902 destination_index = pane.active_item_index();
903 }
904 // Destination pane may be the one currently updated, so defer the move.
905 cx.spawn(|_, mut cx| async move {
906 cx.update(|cx| {
907 move_item(
908 &source,
909 &destination,
910 item_id_to_move,
911 destination_index,
912 cx,
913 );
914 })
915 .ok();
916 })
917 .detach();
918 } else if let Some(project_path) = item.project_path(cx) {
919 if let Some(entry_path) = project.read(cx).absolute_path(&project_path, cx)
920 {
921 add_paths_to_terminal(pane, &[entry_path], cx);
922 }
923 }
924 }
925 } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
926 if let Some(entry_path) = project
927 .read(cx)
928 .path_for_entry(entry_id, cx)
929 .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx))
930 {
931 add_paths_to_terminal(pane, &[entry_path], cx);
932 }
933 } else if is_local {
934 if let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
935 add_paths_to_terminal(pane, paths.paths(), cx);
936 }
937 }
938
939 ControlFlow::Break(())
940 });
941
942 pane
943 });
944
945 cx.subscribe(&pane, TerminalPanel::handle_pane_event)
946 .detach();
947 cx.observe(&pane, |_, _, cx| cx.notify()).detach();
948
949 pane
950}
951
952async fn wait_for_terminals_tasks(
953 terminals_for_task: Vec<(usize, View<Pane>, View<TerminalView>)>,
954 cx: &mut AsyncWindowContext,
955) {
956 let pending_tasks = terminals_for_task.iter().filter_map(|(_, _, terminal)| {
957 terminal
958 .update(cx, |terminal_view, cx| {
959 terminal_view
960 .terminal()
961 .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
962 })
963 .ok()
964 });
965 let _: Vec<()> = join_all(pending_tasks).await;
966}
967
968fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
969 if let Some(terminal_view) = pane
970 .active_item()
971 .and_then(|item| item.downcast::<TerminalView>())
972 {
973 cx.focus_view(&terminal_view);
974 let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
975 new_text.push(' ');
976 terminal_view.update(cx, |terminal_view, cx| {
977 terminal_view.terminal().update(cx, |terminal, _| {
978 terminal.paste(&new_text);
979 });
980 });
981 }
982}
983
984impl EventEmitter<PanelEvent> for TerminalPanel {}
985
986impl Render for TerminalPanel {
987 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
988 let mut registrar = DivRegistrar::new(
989 |panel, cx| {
990 panel
991 .active_pane
992 .read(cx)
993 .toolbar()
994 .read(cx)
995 .item_of_type::<BufferSearchBar>()
996 },
997 cx,
998 );
999 BufferSearchBar::register(&mut registrar);
1000 let registrar = registrar.into_div();
1001 self.workspace
1002 .update(cx, |workspace, cx| {
1003 registrar.size_full().child(self.center.render(
1004 workspace.project(),
1005 &HashMap::default(),
1006 None,
1007 &self.active_pane,
1008 workspace.zoomed_item(),
1009 workspace.app_state(),
1010 cx,
1011 ))
1012 })
1013 .ok()
1014 .map(|div| {
1015 div.on_action({
1016 cx.listener(|terminal_panel, action: &ActivatePaneInDirection, cx| {
1017 if let Some(pane) = terminal_panel.center.find_pane_in_direction(
1018 &terminal_panel.active_pane,
1019 action.0,
1020 cx,
1021 ) {
1022 cx.focus_view(&pane);
1023 } else {
1024 terminal_panel
1025 .workspace
1026 .update(cx, |workspace, cx| {
1027 workspace.activate_pane_in_direction(action.0, cx)
1028 })
1029 .ok();
1030 }
1031 })
1032 })
1033 .on_action(
1034 cx.listener(|terminal_panel, _action: &ActivateNextPane, cx| {
1035 let panes = terminal_panel.center.panes();
1036 if let Some(ix) = panes
1037 .iter()
1038 .position(|pane| **pane == terminal_panel.active_pane)
1039 {
1040 let next_ix = (ix + 1) % panes.len();
1041 let next_pane = panes[next_ix].clone();
1042 cx.focus_view(&next_pane);
1043 }
1044 }),
1045 )
1046 .on_action(
1047 cx.listener(|terminal_panel, _action: &ActivatePreviousPane, cx| {
1048 let panes = terminal_panel.center.panes();
1049 if let Some(ix) = panes
1050 .iter()
1051 .position(|pane| **pane == terminal_panel.active_pane)
1052 {
1053 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1054 let prev_pane = panes[prev_ix].clone();
1055 cx.focus_view(&prev_pane);
1056 }
1057 }),
1058 )
1059 .on_action(cx.listener(|terminal_panel, action: &ActivatePane, cx| {
1060 let panes = terminal_panel.center.panes();
1061 if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
1062 cx.focus_view(&pane);
1063 } else {
1064 let new_pane = terminal_panel.new_pane_with_cloned_active_terminal(cx);
1065 cx.spawn(|this, mut cx| async move {
1066 if let Some(new_pane) = new_pane.await {
1067 this.update(&mut cx, |this, _| {
1068 this.center
1069 .split(&this.active_pane, &new_pane, SplitDirection::Right)
1070 .log_err();
1071 })
1072 .ok();
1073 }
1074 })
1075 .detach();
1076 }
1077 }))
1078 .on_action(cx.listener(
1079 |terminal_panel, action: &SwapPaneInDirection, cx| {
1080 if let Some(to) = terminal_panel
1081 .center
1082 .find_pane_in_direction(&terminal_panel.active_pane, action.0, cx)
1083 .cloned()
1084 {
1085 terminal_panel
1086 .center
1087 .swap(&terminal_panel.active_pane.clone(), &to);
1088 cx.notify();
1089 }
1090 },
1091 ))
1092 })
1093 .unwrap_or_else(|| div())
1094 }
1095}
1096
1097impl FocusableView for TerminalPanel {
1098 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
1099 self.active_pane.focus_handle(cx)
1100 }
1101}
1102
1103impl Panel for TerminalPanel {
1104 fn position(&self, cx: &WindowContext) -> DockPosition {
1105 match TerminalSettings::get_global(cx).dock {
1106 TerminalDockPosition::Left => DockPosition::Left,
1107 TerminalDockPosition::Bottom => DockPosition::Bottom,
1108 TerminalDockPosition::Right => DockPosition::Right,
1109 }
1110 }
1111
1112 fn position_is_valid(&self, _: DockPosition) -> bool {
1113 true
1114 }
1115
1116 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
1117 settings::update_settings_file::<TerminalSettings>(
1118 self.fs.clone(),
1119 cx,
1120 move |settings, _| {
1121 let dock = match position {
1122 DockPosition::Left => TerminalDockPosition::Left,
1123 DockPosition::Bottom => TerminalDockPosition::Bottom,
1124 DockPosition::Right => TerminalDockPosition::Right,
1125 };
1126 settings.dock = Some(dock);
1127 },
1128 );
1129 }
1130
1131 fn size(&self, cx: &WindowContext) -> Pixels {
1132 let settings = TerminalSettings::get_global(cx);
1133 match self.position(cx) {
1134 DockPosition::Left | DockPosition::Right => {
1135 self.width.unwrap_or(settings.default_width)
1136 }
1137 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1138 }
1139 }
1140
1141 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
1142 match self.position(cx) {
1143 DockPosition::Left | DockPosition::Right => self.width = size,
1144 DockPosition::Bottom => self.height = size,
1145 }
1146 self.serialize(cx);
1147 cx.notify();
1148 }
1149
1150 fn is_zoomed(&self, cx: &WindowContext) -> bool {
1151 self.active_pane.read(cx).is_zoomed()
1152 }
1153
1154 fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
1155 self.active_pane
1156 .update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
1157 }
1158
1159 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
1160 if !active || !self.has_no_terminals(cx) {
1161 return;
1162 }
1163 cx.defer(|this, cx| {
1164 let Ok(kind) = this.workspace.update(cx, |workspace, cx| {
1165 TerminalKind::Shell(default_working_directory(workspace, cx))
1166 }) else {
1167 return;
1168 };
1169
1170 this.add_terminal(kind, RevealStrategy::Never, cx)
1171 .detach_and_log_err(cx)
1172 })
1173 }
1174
1175 fn icon_label(&self, cx: &WindowContext) -> Option<String> {
1176 let count = self
1177 .center
1178 .panes()
1179 .into_iter()
1180 .map(|pane| pane.read(cx).items_len())
1181 .sum::<usize>();
1182 if count == 0 {
1183 None
1184 } else {
1185 Some(count.to_string())
1186 }
1187 }
1188
1189 fn persistent_name() -> &'static str {
1190 "TerminalPanel"
1191 }
1192
1193 fn icon(&self, cx: &WindowContext) -> Option<IconName> {
1194 if (self.enabled || !self.has_no_terminals(cx)) && TerminalSettings::get_global(cx).button {
1195 Some(IconName::Terminal)
1196 } else {
1197 None
1198 }
1199 }
1200
1201 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
1202 Some("Terminal Panel")
1203 }
1204
1205 fn toggle_action(&self) -> Box<dyn gpui::Action> {
1206 Box::new(ToggleFocus)
1207 }
1208
1209 fn pane(&self) -> Option<View<Pane>> {
1210 Some(self.active_pane.clone())
1211 }
1212}
1213
1214struct InlineAssistTabBarButton {
1215 focus_handle: FocusHandle,
1216}
1217
1218impl Render for InlineAssistTabBarButton {
1219 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1220 let focus_handle = self.focus_handle.clone();
1221 IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1222 .icon_size(IconSize::Small)
1223 .on_click(cx.listener(|_, _, cx| {
1224 cx.dispatch_action(InlineAssist::default().boxed_clone());
1225 }))
1226 .tooltip(move |cx| {
1227 Tooltip::for_action_in("Inline Assist", &InlineAssist::default(), &focus_handle, cx)
1228 })
1229 }
1230}
1231
1232fn retrieve_system_shell() -> Option<String> {
1233 #[cfg(not(target_os = "windows"))]
1234 {
1235 use anyhow::Context;
1236 use util::ResultExt;
1237
1238 std::env::var("SHELL")
1239 .context("Error finding SHELL in env.")
1240 .log_err()
1241 }
1242 // `alacritty_terminal` uses this as default on Windows. See:
1243 // https://github.com/alacritty/alacritty/blob/0d4ab7bca43213d96ddfe40048fc0f922543c6f8/alacritty_terminal/src/tty/windows/mod.rs#L130
1244 #[cfg(target_os = "windows")]
1245 return Some("powershell".to_owned());
1246}
1247
1248#[cfg(target_os = "windows")]
1249fn to_windows_shell_variable(shell_type: WindowsShellType, input: String) -> String {
1250 match shell_type {
1251 WindowsShellType::Powershell => to_powershell_variable(input),
1252 WindowsShellType::Cmd => to_cmd_variable(input),
1253 WindowsShellType::Other => input,
1254 }
1255}
1256
1257#[cfg(target_os = "windows")]
1258fn to_windows_shell_type(shell: &str) -> WindowsShellType {
1259 if shell == "powershell"
1260 || shell.ends_with("powershell.exe")
1261 || shell == "pwsh"
1262 || shell.ends_with("pwsh.exe")
1263 {
1264 WindowsShellType::Powershell
1265 } else if shell == "cmd" || shell.ends_with("cmd.exe") {
1266 WindowsShellType::Cmd
1267 } else {
1268 // Someother shell detected, the user might install and use a
1269 // unix-like shell.
1270 WindowsShellType::Other
1271 }
1272}
1273
1274/// Convert `${SOME_VAR}`, `$SOME_VAR` to `%SOME_VAR%`.
1275#[inline]
1276#[cfg(target_os = "windows")]
1277fn to_cmd_variable(input: String) -> String {
1278 if let Some(var_str) = input.strip_prefix("${") {
1279 if var_str.find(':').is_none() {
1280 // If the input starts with "${", remove the trailing "}"
1281 format!("%{}%", &var_str[..var_str.len() - 1])
1282 } else {
1283 // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
1284 // which will result in the task failing to run in such cases.
1285 input
1286 }
1287 } else if let Some(var_str) = input.strip_prefix('$') {
1288 // If the input starts with "$", directly append to "$env:"
1289 format!("%{}%", var_str)
1290 } else {
1291 // If no prefix is found, return the input as is
1292 input
1293 }
1294}
1295
1296/// Convert `${SOME_VAR}`, `$SOME_VAR` to `$env:SOME_VAR`.
1297#[inline]
1298#[cfg(target_os = "windows")]
1299fn to_powershell_variable(input: String) -> String {
1300 if let Some(var_str) = input.strip_prefix("${") {
1301 if var_str.find(':').is_none() {
1302 // If the input starts with "${", remove the trailing "}"
1303 format!("$env:{}", &var_str[..var_str.len() - 1])
1304 } else {
1305 // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
1306 // which will result in the task failing to run in such cases.
1307 input
1308 }
1309 } else if let Some(var_str) = input.strip_prefix('$') {
1310 // If the input starts with "$", directly append to "$env:"
1311 format!("$env:{}", var_str)
1312 } else {
1313 // If no prefix is found, return the input as is
1314 input
1315 }
1316}
1317
1318#[cfg(target_os = "windows")]
1319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1320enum WindowsShellType {
1321 Powershell,
1322 Cmd,
1323 Other,
1324}