1use std::{cmp, path::PathBuf, process::ExitStatus, sync::Arc, time::Duration};
2
3use crate::{
4 TerminalView, default_working_directory,
5 persistence::{
6 SerializedItems, SerializedTerminalPanel, deserialize_terminal_panel, serialize_pane_group,
7 },
8};
9use breadcrumbs::Breadcrumbs;
10use collections::HashMap;
11use db::kvp::KEY_VALUE_STORE;
12use futures::{channel::oneshot, future::join_all};
13use gpui::{
14 Action, AnyView, App, AsyncApp, AsyncWindowContext, Context, Corner, Entity, EventEmitter,
15 FocusHandle, Focusable, IntoElement, ParentElement, Pixels, Render, Styled, Task, WeakEntity,
16 Window, actions,
17};
18use itertools::Itertools;
19use project::{Fs, Project};
20
21use settings::{Settings, TerminalDockPosition};
22use task::{RevealStrategy, RevealTarget, Shell, ShellBuilder, SpawnInTerminal, TaskId};
23use terminal::{Terminal, terminal_settings::TerminalSettings};
24use ui::{
25 ButtonLike, Clickable, ContextMenu, FluentBuilder, PopoverMenu, SplitButton, Toggleable,
26 Tooltip, prelude::*,
27};
28use util::{ResultExt, TryFutureExt};
29use workspace::{
30 ActivateNextPane, ActivatePane, ActivatePaneDown, ActivatePaneLeft, ActivatePaneRight,
31 ActivatePaneUp, ActivatePreviousPane, DraggedTab, ItemId, MoveItemToPane,
32 MoveItemToPaneInDirection, MovePaneDown, MovePaneLeft, MovePaneRight, MovePaneUp, Pane,
33 PaneGroup, SplitDirection, SplitDown, SplitLeft, SplitMode, SplitRight, SplitUp, SwapPaneDown,
34 SwapPaneLeft, SwapPaneRight, SwapPaneUp, ToggleZoom, Workspace,
35 dock::{DockPosition, Panel, PanelEvent, PanelHandle},
36 item::SerializableItem,
37 move_active_item, pane,
38};
39
40use anyhow::{Result, anyhow};
41use zed_actions::assistant::InlineAssist;
42
43const TERMINAL_PANEL_KEY: &str = "TerminalPanel";
44
45actions!(
46 terminal_panel,
47 [
48 /// Toggles the terminal panel.
49 Toggle,
50 /// Toggles focus on the terminal panel.
51 ToggleFocus
52 ]
53);
54
55pub fn init(cx: &mut App) {
56 cx.observe_new(
57 |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
58 workspace.register_action(TerminalPanel::new_terminal);
59 workspace.register_action(TerminalPanel::open_terminal);
60 workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
61 if is_enabled_in_workspace(workspace, cx) {
62 workspace.toggle_panel_focus::<TerminalPanel>(window, cx);
63 }
64 });
65 workspace.register_action(|workspace, _: &Toggle, window, cx| {
66 if is_enabled_in_workspace(workspace, cx) {
67 if !workspace.toggle_panel_focus::<TerminalPanel>(window, cx) {
68 workspace.close_panel::<TerminalPanel>(window, cx);
69 }
70 }
71 });
72 },
73 )
74 .detach();
75}
76
77pub struct TerminalPanel {
78 pub(crate) active_pane: Entity<Pane>,
79 pub(crate) center: PaneGroup,
80 fs: Arc<dyn Fs>,
81 workspace: WeakEntity<Workspace>,
82 pub(crate) width: Option<Pixels>,
83 pub(crate) height: Option<Pixels>,
84 pending_serialization: Task<Option<()>>,
85 pending_terminals_to_add: usize,
86 deferred_tasks: HashMap<TaskId, Task<()>>,
87 assistant_enabled: bool,
88 assistant_tab_bar_button: Option<AnyView>,
89 active: bool,
90}
91
92impl TerminalPanel {
93 pub fn new(workspace: &Workspace, window: &mut Window, cx: &mut Context<Self>) -> Self {
94 let project = workspace.project();
95 let pane = new_terminal_pane(workspace.weak_handle(), project.clone(), false, window, cx);
96 let center = PaneGroup::new(pane.clone());
97 let terminal_panel = Self {
98 center,
99 active_pane: pane,
100 fs: workspace.app_state().fs.clone(),
101 workspace: workspace.weak_handle(),
102 pending_serialization: Task::ready(None),
103 width: None,
104 height: None,
105 pending_terminals_to_add: 0,
106 deferred_tasks: HashMap::default(),
107 assistant_enabled: false,
108 assistant_tab_bar_button: None,
109 active: false,
110 };
111 terminal_panel.apply_tab_bar_buttons(&terminal_panel.active_pane, cx);
112 terminal_panel
113 }
114
115 pub fn set_assistant_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
116 self.assistant_enabled = enabled;
117 if enabled {
118 let focus_handle = self
119 .active_pane
120 .read(cx)
121 .active_item()
122 .map(|item| item.item_focus_handle(cx))
123 .unwrap_or(self.focus_handle(cx));
124 self.assistant_tab_bar_button = Some(
125 cx.new(move |_| InlineAssistTabBarButton { focus_handle })
126 .into(),
127 );
128 } else {
129 self.assistant_tab_bar_button = None;
130 }
131 for pane in self.center.panes() {
132 self.apply_tab_bar_buttons(pane, cx);
133 }
134 }
135
136 pub(crate) fn apply_tab_bar_buttons(
137 &self,
138 terminal_pane: &Entity<Pane>,
139 cx: &mut Context<Self>,
140 ) {
141 let assistant_tab_bar_button = self.assistant_tab_bar_button.clone();
142 terminal_pane.update(cx, |pane, cx| {
143 pane.set_render_tab_bar_buttons(cx, move |pane, window, cx| {
144 let split_context = pane
145 .active_item()
146 .and_then(|item| item.downcast::<TerminalView>())
147 .map(|terminal_view| terminal_view.read(cx).focus_handle.clone());
148 let has_focused_rename_editor = pane
149 .active_item()
150 .and_then(|item| item.downcast::<TerminalView>())
151 .is_some_and(|view| view.read(cx).rename_editor_is_focused(window, cx));
152 if !pane.has_focus(window, cx)
153 && !pane.context_menu_focused(window, cx)
154 && !has_focused_rename_editor
155 {
156 return (None, None);
157 }
158 let focus_handle = pane.focus_handle(cx);
159 let right_children = h_flex()
160 .gap(DynamicSpacing::Base02.rems(cx))
161 .child(
162 PopoverMenu::new("terminal-tab-bar-popover-menu")
163 .trigger_with_tooltip(
164 IconButton::new("plus", IconName::Plus).icon_size(IconSize::Small),
165 Tooltip::text("New…"),
166 )
167 .anchor(Corner::TopRight)
168 .with_handle(pane.new_item_context_menu_handle.clone())
169 .menu(move |window, cx| {
170 let focus_handle = focus_handle.clone();
171 let menu = ContextMenu::build(window, cx, |menu, _, _| {
172 menu.context(focus_handle.clone())
173 .action(
174 "New Terminal",
175 workspace::NewTerminal::default().boxed_clone(),
176 )
177 // We want the focus to go back to terminal panel once task modal is dismissed,
178 // hence we focus that first. Otherwise, we'd end up without a focused element, as
179 // context menu will be gone the moment we spawn the modal.
180 .action(
181 "Spawn Task",
182 zed_actions::Spawn::modal().boxed_clone(),
183 )
184 });
185
186 Some(menu)
187 }),
188 )
189 .children(assistant_tab_bar_button.clone())
190 .child(
191 PopoverMenu::new("terminal-pane-tab-bar-split")
192 .trigger_with_tooltip(
193 IconButton::new("terminal-pane-split", IconName::Split)
194 .icon_size(IconSize::Small),
195 Tooltip::text("Split Pane"),
196 )
197 .anchor(Corner::TopRight)
198 .with_handle(pane.split_item_context_menu_handle.clone())
199 .menu({
200 move |window, cx| {
201 ContextMenu::build(window, cx, |menu, _, _| {
202 menu.when_some(
203 split_context.clone(),
204 |menu, split_context| menu.context(split_context),
205 )
206 .action("Split Right", SplitRight::default().boxed_clone())
207 .action("Split Left", SplitLeft::default().boxed_clone())
208 .action("Split Up", SplitUp::default().boxed_clone())
209 .action("Split Down", SplitDown::default().boxed_clone())
210 })
211 .into()
212 }
213 }),
214 )
215 .child({
216 let zoomed = pane.is_zoomed();
217 IconButton::new("toggle_zoom", IconName::Maximize)
218 .icon_size(IconSize::Small)
219 .toggle_state(zoomed)
220 .selected_icon(IconName::Minimize)
221 .on_click(cx.listener(|pane, _, window, cx| {
222 pane.toggle_zoom(&workspace::ToggleZoom, window, cx);
223 }))
224 .tooltip(move |_window, cx| {
225 Tooltip::for_action(
226 if zoomed { "Zoom Out" } else { "Zoom In" },
227 &ToggleZoom,
228 cx,
229 )
230 })
231 })
232 .into_any_element()
233 .into();
234 (None, right_children)
235 });
236 });
237 }
238
239 fn serialization_key(workspace: &Workspace) -> Option<String> {
240 workspace
241 .database_id()
242 .map(|id| i64::from(id).to_string())
243 .or(workspace.session_id())
244 .map(|id| format!("{:?}-{:?}", TERMINAL_PANEL_KEY, id))
245 }
246
247 pub async fn load(
248 workspace: WeakEntity<Workspace>,
249 mut cx: AsyncWindowContext,
250 ) -> Result<Entity<Self>> {
251 let mut terminal_panel = None;
252
253 if let Some((database_id, serialization_key)) = workspace
254 .read_with(&cx, |workspace, _| {
255 workspace
256 .database_id()
257 .zip(TerminalPanel::serialization_key(workspace))
258 })
259 .ok()
260 .flatten()
261 && let Some(serialized_panel) = cx
262 .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
263 .await
264 .log_err()
265 .flatten()
266 .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
267 .transpose()
268 .log_err()
269 .flatten()
270 && let Ok(serialized) = workspace
271 .update_in(&mut cx, |workspace, window, cx| {
272 deserialize_terminal_panel(
273 workspace.weak_handle(),
274 workspace.project().clone(),
275 database_id,
276 serialized_panel,
277 window,
278 cx,
279 )
280 })?
281 .await
282 {
283 terminal_panel = Some(serialized);
284 }
285
286 let terminal_panel = if let Some(panel) = terminal_panel {
287 panel
288 } else {
289 workspace.update_in(&mut cx, |workspace, window, cx| {
290 cx.new(|cx| TerminalPanel::new(workspace, window, cx))
291 })?
292 };
293
294 if let Some(workspace) = workspace.upgrade() {
295 workspace.update(&mut cx, |workspace, _| {
296 workspace.set_terminal_provider(TerminalProvider(terminal_panel.clone()))
297 });
298 }
299
300 // Since panels/docks are loaded outside from the workspace, we cleanup here, instead of through the workspace.
301 if let Some(workspace) = workspace.upgrade() {
302 let cleanup_task = workspace.update_in(&mut cx, |workspace, window, cx| {
303 let alive_item_ids = terminal_panel
304 .read(cx)
305 .center
306 .panes()
307 .into_iter()
308 .flat_map(|pane| pane.read(cx).items())
309 .map(|item| item.item_id().as_u64() as ItemId)
310 .collect();
311 workspace.database_id().map(|workspace_id| {
312 TerminalView::cleanup(workspace_id, alive_item_ids, window, cx)
313 })
314 })?;
315 if let Some(task) = cleanup_task {
316 task.await.log_err();
317 }
318 }
319
320 if let Some(workspace) = workspace.upgrade() {
321 let should_focus = workspace
322 .update_in(&mut cx, |workspace, window, cx| {
323 workspace.active_item(cx).is_none()
324 && workspace
325 .is_dock_at_position_open(terminal_panel.position(window, cx), cx)
326 })
327 .unwrap_or(false);
328
329 if should_focus {
330 terminal_panel
331 .update_in(&mut cx, |panel, window, cx| {
332 panel.active_pane.update(cx, |pane, cx| {
333 pane.focus_active_item(window, cx);
334 });
335 })
336 .ok();
337 }
338 }
339 Ok(terminal_panel)
340 }
341
342 fn handle_pane_event(
343 &mut self,
344 pane: &Entity<Pane>,
345 event: &pane::Event,
346 window: &mut Window,
347 cx: &mut Context<Self>,
348 ) {
349 match event {
350 pane::Event::ActivateItem { .. } => self.serialize(cx),
351 pane::Event::RemovedItem { .. } => self.serialize(cx),
352 pane::Event::Remove { focus_on_pane } => {
353 let pane_count_before_removal = self.center.panes().len();
354 let _removal_result = self.center.remove(pane, cx);
355 if pane_count_before_removal == 1 {
356 self.center.first_pane().update(cx, |pane, cx| {
357 pane.set_zoomed(false, cx);
358 });
359 cx.emit(PanelEvent::Close);
360 } else if let Some(focus_on_pane) =
361 focus_on_pane.as_ref().or_else(|| self.center.panes().pop())
362 {
363 focus_on_pane.focus_handle(cx).focus(window, cx);
364 }
365 }
366 pane::Event::ZoomIn => {
367 for pane in self.center.panes() {
368 pane.update(cx, |pane, cx| {
369 pane.set_zoomed(true, cx);
370 })
371 }
372 cx.emit(PanelEvent::ZoomIn);
373 cx.notify();
374 }
375 pane::Event::ZoomOut => {
376 for pane in self.center.panes() {
377 pane.update(cx, |pane, cx| {
378 pane.set_zoomed(false, cx);
379 })
380 }
381 cx.emit(PanelEvent::ZoomOut);
382 cx.notify();
383 }
384 pane::Event::AddItem { item } => {
385 if let Some(workspace) = self.workspace.upgrade() {
386 workspace.update(cx, |workspace, cx| {
387 item.added_to_pane(workspace, pane.clone(), window, cx)
388 })
389 }
390 self.serialize(cx);
391 }
392 &pane::Event::Split { direction, mode } => {
393 match mode {
394 SplitMode::ClonePane | SplitMode::EmptyPane => {
395 let clone = matches!(mode, SplitMode::ClonePane);
396 let new_pane = self.new_pane_with_active_terminal(clone, window, cx);
397 let pane = pane.clone();
398 cx.spawn_in(window, async move |panel, cx| {
399 let Some(new_pane) = new_pane.await else {
400 return;
401 };
402 panel
403 .update_in(cx, |panel, window, cx| {
404 panel.center.split(&pane, &new_pane, direction, cx);
405 window.focus(&new_pane.focus_handle(cx), cx);
406 })
407 .ok();
408 })
409 .detach();
410 }
411 SplitMode::MovePane => {
412 let Some(item) =
413 pane.update(cx, |pane, cx| pane.take_active_item(window, cx))
414 else {
415 return;
416 };
417 let Ok(project) = self
418 .workspace
419 .update(cx, |workspace, _| workspace.project().clone())
420 else {
421 return;
422 };
423 let new_pane =
424 new_terminal_pane(self.workspace.clone(), project, false, window, cx);
425 new_pane.update(cx, |pane, cx| {
426 pane.add_item(item, true, true, None, window, cx);
427 });
428 self.center.split(&pane, &new_pane, direction, cx);
429 window.focus(&new_pane.focus_handle(cx), cx);
430 }
431 };
432 }
433 pane::Event::Focus => {
434 self.active_pane = pane.clone();
435 }
436 pane::Event::ItemPinned | pane::Event::ItemUnpinned => {
437 self.serialize(cx);
438 }
439
440 _ => {}
441 }
442 }
443
444 fn new_pane_with_active_terminal(
445 &mut self,
446 clone: bool,
447 window: &mut Window,
448 cx: &mut Context<Self>,
449 ) -> Task<Option<Entity<Pane>>> {
450 let Some(workspace) = self.workspace.upgrade() else {
451 return Task::ready(None);
452 };
453 let workspace = workspace.read(cx);
454 let database_id = workspace.database_id();
455 let weak_workspace = self.workspace.clone();
456 let project = workspace.project().clone();
457 let active_pane = &self.active_pane;
458 let terminal_view = if clone {
459 active_pane
460 .read(cx)
461 .active_item()
462 .and_then(|item| item.downcast::<TerminalView>())
463 } else {
464 None
465 };
466 let working_directory = if clone {
467 terminal_view
468 .as_ref()
469 .and_then(|terminal_view| {
470 terminal_view
471 .read(cx)
472 .terminal()
473 .read(cx)
474 .working_directory()
475 })
476 .or_else(|| default_working_directory(workspace, cx))
477 } else {
478 default_working_directory(workspace, cx)
479 };
480
481 let is_zoomed = if clone {
482 active_pane.read(cx).is_zoomed()
483 } else {
484 false
485 };
486 cx.spawn_in(window, async move |panel, cx| {
487 let terminal = project
488 .update(cx, |project, cx| match terminal_view {
489 Some(view) => project.clone_terminal(
490 &view.read(cx).terminal.clone(),
491 cx,
492 working_directory,
493 ),
494 None => project.create_terminal_shell(working_directory, cx),
495 })
496 .await
497 .log_err()?;
498
499 panel
500 .update_in(cx, move |terminal_panel, window, cx| {
501 let terminal_view = Box::new(cx.new(|cx| {
502 TerminalView::new(
503 terminal.clone(),
504 weak_workspace.clone(),
505 database_id,
506 project.downgrade(),
507 window,
508 cx,
509 )
510 }));
511 let pane = new_terminal_pane(weak_workspace, project, is_zoomed, window, cx);
512 terminal_panel.apply_tab_bar_buttons(&pane, cx);
513 pane.update(cx, |pane, cx| {
514 pane.add_item(terminal_view, true, true, None, window, cx);
515 });
516 Some(pane)
517 })
518 .ok()
519 .flatten()
520 })
521 }
522
523 pub fn open_terminal(
524 workspace: &mut Workspace,
525 action: &workspace::OpenTerminal,
526 window: &mut Window,
527 cx: &mut Context<Workspace>,
528 ) {
529 let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
530 return;
531 };
532
533 terminal_panel
534 .update(cx, |panel, cx| {
535 if action.local {
536 panel.add_local_terminal_shell(RevealStrategy::Always, window, cx)
537 } else {
538 panel.add_terminal_shell(
539 Some(action.working_directory.clone()),
540 RevealStrategy::Always,
541 window,
542 cx,
543 )
544 }
545 })
546 .detach_and_log_err(cx);
547 }
548
549 pub fn spawn_task(
550 &mut self,
551 task: &SpawnInTerminal,
552 window: &mut Window,
553 cx: &mut Context<Self>,
554 ) -> Task<Result<WeakEntity<Terminal>>> {
555 let Some(workspace) = self.workspace.upgrade() else {
556 return Task::ready(Err(anyhow!("failed to read workspace")));
557 };
558
559 let project = workspace.read(cx).project().read(cx);
560
561 if project.is_via_collab() {
562 return Task::ready(Err(anyhow!("cannot spawn tasks as a guest")));
563 }
564
565 let remote_client = project.remote_client();
566 let is_windows = project.path_style(cx).is_windows();
567 let remote_shell = remote_client
568 .as_ref()
569 .and_then(|remote_client| remote_client.read(cx).shell());
570
571 let shell = if let Some(remote_shell) = remote_shell
572 && task.shell == Shell::System
573 {
574 Shell::Program(remote_shell)
575 } else {
576 task.shell.clone()
577 };
578
579 let task = prepare_task_for_spawn(task, &shell, is_windows);
580
581 if task.allow_concurrent_runs && task.use_new_terminal {
582 return self.spawn_in_new_terminal(task, window, cx);
583 }
584
585 let mut terminals_for_task = self.terminals_for_task(&task.full_label, cx);
586 let Some(existing) = terminals_for_task.pop() else {
587 return self.spawn_in_new_terminal(task, window, cx);
588 };
589
590 let (existing_item_index, task_pane, existing_terminal) = existing;
591 if task.allow_concurrent_runs {
592 return self.replace_terminal(
593 task,
594 task_pane,
595 existing_item_index,
596 existing_terminal,
597 window,
598 cx,
599 );
600 }
601
602 let (tx, rx) = oneshot::channel();
603
604 self.deferred_tasks.insert(
605 task.id.clone(),
606 cx.spawn_in(window, async move |terminal_panel, cx| {
607 wait_for_terminals_tasks(terminals_for_task, cx).await;
608 let task = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
609 if task.use_new_terminal {
610 terminal_panel.spawn_in_new_terminal(task, window, cx)
611 } else {
612 terminal_panel.replace_terminal(
613 task,
614 task_pane,
615 existing_item_index,
616 existing_terminal,
617 window,
618 cx,
619 )
620 }
621 });
622 if let Ok(task) = task {
623 tx.send(task.await).ok();
624 }
625 }),
626 );
627
628 cx.spawn(async move |_, _| rx.await?)
629 }
630
631 fn spawn_in_new_terminal(
632 &mut self,
633 spawn_task: SpawnInTerminal,
634 window: &mut Window,
635 cx: &mut Context<Self>,
636 ) -> Task<Result<WeakEntity<Terminal>>> {
637 let reveal = spawn_task.reveal;
638 let reveal_target = spawn_task.reveal_target;
639 match reveal_target {
640 RevealTarget::Center => self
641 .workspace
642 .update(cx, |workspace, cx| {
643 Self::add_center_terminal(workspace, window, cx, |project, cx| {
644 project.create_terminal_task(spawn_task, cx)
645 })
646 })
647 .unwrap_or_else(|e| Task::ready(Err(e))),
648 RevealTarget::Dock => self.add_terminal_task(spawn_task, reveal, window, cx),
649 }
650 }
651
652 /// Create a new Terminal in the current working directory or the user's home directory
653 fn new_terminal(
654 workspace: &mut Workspace,
655 action: &workspace::NewTerminal,
656 window: &mut Window,
657 cx: &mut Context<Workspace>,
658 ) {
659 let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
660 return;
661 };
662
663 terminal_panel
664 .update(cx, |this, cx| {
665 if action.local {
666 this.add_local_terminal_shell(RevealStrategy::Always, window, cx)
667 } else {
668 this.add_terminal_shell(
669 default_working_directory(workspace, cx),
670 RevealStrategy::Always,
671 window,
672 cx,
673 )
674 }
675 })
676 .detach_and_log_err(cx);
677 }
678
679 fn terminals_for_task(
680 &self,
681 label: &str,
682 cx: &mut App,
683 ) -> Vec<(usize, Entity<Pane>, Entity<TerminalView>)> {
684 let Some(workspace) = self.workspace.upgrade() else {
685 return Vec::new();
686 };
687
688 let pane_terminal_views = |pane: Entity<Pane>| {
689 pane.read(cx)
690 .items()
691 .enumerate()
692 .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
693 .filter_map(|(index, terminal_view)| {
694 let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
695 if &task_state.spawned_task.full_label == label {
696 Some((index, terminal_view))
697 } else {
698 None
699 }
700 })
701 .map(move |(index, terminal_view)| (index, pane.clone(), terminal_view))
702 };
703
704 self.center
705 .panes()
706 .into_iter()
707 .cloned()
708 .flat_map(pane_terminal_views)
709 .chain(
710 workspace
711 .read(cx)
712 .panes()
713 .iter()
714 .cloned()
715 .flat_map(pane_terminal_views),
716 )
717 .sorted_by_key(|(_, _, terminal_view)| terminal_view.entity_id())
718 .collect()
719 }
720
721 fn activate_terminal_view(
722 &self,
723 pane: &Entity<Pane>,
724 item_index: usize,
725 focus: bool,
726 window: &mut Window,
727 cx: &mut App,
728 ) {
729 pane.update(cx, |pane, cx| {
730 pane.activate_item(item_index, true, focus, window, cx)
731 })
732 }
733
734 pub fn add_center_terminal(
735 workspace: &mut Workspace,
736 window: &mut Window,
737 cx: &mut Context<Workspace>,
738 create_terminal: impl FnOnce(
739 &mut Project,
740 &mut Context<Project>,
741 ) -> Task<Result<Entity<Terminal>>>
742 + 'static,
743 ) -> Task<Result<WeakEntity<Terminal>>> {
744 if !is_enabled_in_workspace(workspace, cx) {
745 return Task::ready(Err(anyhow!(
746 "terminal not yet supported for remote projects"
747 )));
748 }
749 let project = workspace.project().downgrade();
750 cx.spawn_in(window, async move |workspace, cx| {
751 let terminal = project.update(cx, create_terminal)?.await?;
752
753 workspace.update_in(cx, |workspace, window, cx| {
754 let terminal_view = cx.new(|cx| {
755 TerminalView::new(
756 terminal.clone(),
757 workspace.weak_handle(),
758 workspace.database_id(),
759 workspace.project().downgrade(),
760 window,
761 cx,
762 )
763 });
764 workspace.add_item_to_active_pane(Box::new(terminal_view), None, true, window, cx);
765 })?;
766 Ok(terminal.downgrade())
767 })
768 }
769
770 pub fn add_terminal_task(
771 &mut self,
772 task: SpawnInTerminal,
773 reveal_strategy: RevealStrategy,
774 window: &mut Window,
775 cx: &mut Context<Self>,
776 ) -> Task<Result<WeakEntity<Terminal>>> {
777 let workspace = self.workspace.clone();
778 cx.spawn_in(window, async move |terminal_panel, cx| {
779 if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
780 anyhow::bail!("terminal not yet supported for remote projects");
781 }
782 let pane = terminal_panel.update(cx, |terminal_panel, _| {
783 terminal_panel.pending_terminals_to_add += 1;
784 terminal_panel.active_pane.clone()
785 })?;
786 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
787 let terminal = project
788 .update(cx, |project, cx| project.create_terminal_task(task, cx))
789 .await?;
790 let result = workspace.update_in(cx, |workspace, window, cx| {
791 let terminal_view = Box::new(cx.new(|cx| {
792 TerminalView::new(
793 terminal.clone(),
794 workspace.weak_handle(),
795 workspace.database_id(),
796 workspace.project().downgrade(),
797 window,
798 cx,
799 )
800 }));
801
802 match reveal_strategy {
803 RevealStrategy::Always => {
804 workspace.focus_panel::<Self>(window, cx);
805 }
806 RevealStrategy::NoFocus => {
807 workspace.open_panel::<Self>(window, cx);
808 }
809 RevealStrategy::Never => {}
810 }
811
812 pane.update(cx, |pane, cx| {
813 let focus = matches!(reveal_strategy, RevealStrategy::Always);
814 pane.add_item(terminal_view, true, focus, None, window, cx);
815 });
816
817 Ok(terminal.downgrade())
818 })?;
819 terminal_panel.update(cx, |terminal_panel, cx| {
820 terminal_panel.pending_terminals_to_add =
821 terminal_panel.pending_terminals_to_add.saturating_sub(1);
822 terminal_panel.serialize(cx)
823 })?;
824 result
825 })
826 }
827
828 fn add_terminal_shell(
829 &mut self,
830 cwd: Option<PathBuf>,
831 reveal_strategy: RevealStrategy,
832 window: &mut Window,
833 cx: &mut Context<Self>,
834 ) -> Task<Result<WeakEntity<Terminal>>> {
835 self.add_terminal_shell_internal(false, cwd, reveal_strategy, window, cx)
836 }
837
838 fn add_local_terminal_shell(
839 &mut self,
840 reveal_strategy: RevealStrategy,
841 window: &mut Window,
842 cx: &mut Context<Self>,
843 ) -> Task<Result<WeakEntity<Terminal>>> {
844 self.add_terminal_shell_internal(true, None, reveal_strategy, window, cx)
845 }
846
847 fn add_terminal_shell_internal(
848 &mut self,
849 force_local: bool,
850 cwd: Option<PathBuf>,
851 reveal_strategy: RevealStrategy,
852 window: &mut Window,
853 cx: &mut Context<Self>,
854 ) -> Task<Result<WeakEntity<Terminal>>> {
855 let workspace = self.workspace.clone();
856
857 cx.spawn_in(window, async move |terminal_panel, cx| {
858 if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
859 anyhow::bail!("terminal not yet supported for collaborative projects");
860 }
861 let pane = terminal_panel.update(cx, |terminal_panel, _| {
862 terminal_panel.pending_terminals_to_add += 1;
863 terminal_panel.active_pane.clone()
864 })?;
865 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
866 let terminal = if force_local {
867 project
868 .update(cx, |project, cx| project.create_local_terminal(cx))
869 .await
870 } else {
871 project
872 .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))
873 .await
874 };
875
876 match terminal {
877 Ok(terminal) => {
878 let result = workspace.update_in(cx, |workspace, window, cx| {
879 let terminal_view = Box::new(cx.new(|cx| {
880 TerminalView::new(
881 terminal.clone(),
882 workspace.weak_handle(),
883 workspace.database_id(),
884 workspace.project().downgrade(),
885 window,
886 cx,
887 )
888 }));
889
890 match reveal_strategy {
891 RevealStrategy::Always => {
892 workspace.focus_panel::<Self>(window, cx);
893 }
894 RevealStrategy::NoFocus => {
895 workspace.open_panel::<Self>(window, cx);
896 }
897 RevealStrategy::Never => {}
898 }
899
900 pane.update(cx, |pane, cx| {
901 let focus = matches!(reveal_strategy, RevealStrategy::Always);
902 pane.add_item(terminal_view, true, focus, None, window, cx);
903 });
904
905 Ok(terminal.downgrade())
906 })?;
907 terminal_panel.update(cx, |terminal_panel, cx| {
908 terminal_panel.pending_terminals_to_add =
909 terminal_panel.pending_terminals_to_add.saturating_sub(1);
910 terminal_panel.serialize(cx)
911 })?;
912 result
913 }
914 Err(error) => {
915 pane.update_in(cx, |pane, window, cx| {
916 let focus = pane.has_focus(window, cx);
917 let failed_to_spawn = cx.new(|cx| FailedToSpawnTerminal {
918 error: error.to_string(),
919 focus_handle: cx.focus_handle(),
920 });
921 pane.add_item(Box::new(failed_to_spawn), true, focus, None, window, cx);
922 })?;
923 Err(error)
924 }
925 }
926 })
927 }
928
929 fn serialize(&mut self, cx: &mut Context<Self>) {
930 let height = self.height;
931 let width = self.width;
932 let Some(serialization_key) = self
933 .workspace
934 .read_with(cx, |workspace, _| {
935 TerminalPanel::serialization_key(workspace)
936 })
937 .ok()
938 .flatten()
939 else {
940 return;
941 };
942 self.pending_serialization = cx.spawn(async move |terminal_panel, cx| {
943 cx.background_executor()
944 .timer(Duration::from_millis(50))
945 .await;
946 let terminal_panel = terminal_panel.upgrade()?;
947 let items = terminal_panel.update(cx, |terminal_panel, cx| {
948 SerializedItems::WithSplits(serialize_pane_group(
949 &terminal_panel.center,
950 &terminal_panel.active_pane,
951 cx,
952 ))
953 });
954 cx.background_spawn(
955 async move {
956 KEY_VALUE_STORE
957 .write_kvp(
958 serialization_key,
959 serde_json::to_string(&SerializedTerminalPanel {
960 items,
961 active_item_id: None,
962 height,
963 width,
964 })?,
965 )
966 .await?;
967 anyhow::Ok(())
968 }
969 .log_err(),
970 )
971 .await;
972 Some(())
973 });
974 }
975
976 fn replace_terminal(
977 &self,
978 spawn_task: SpawnInTerminal,
979 task_pane: Entity<Pane>,
980 terminal_item_index: usize,
981 terminal_to_replace: Entity<TerminalView>,
982 window: &mut Window,
983 cx: &mut Context<Self>,
984 ) -> Task<Result<WeakEntity<Terminal>>> {
985 let reveal = spawn_task.reveal;
986 let task_workspace = self.workspace.clone();
987 cx.spawn_in(window, async move |terminal_panel, cx| {
988 let project = terminal_panel.update(cx, |this, cx| {
989 this.workspace
990 .update(cx, |workspace, _| workspace.project().clone())
991 })??;
992 let new_terminal = project
993 .update(cx, |project, cx| {
994 project.create_terminal_task(spawn_task, cx)
995 })
996 .await?;
997 terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| {
998 terminal_to_replace.set_terminal(new_terminal.clone(), window, cx);
999 })?;
1000
1001 let reveal_target = terminal_panel.update(cx, |panel, _| {
1002 if panel.center.panes().iter().any(|p| **p == task_pane) {
1003 RevealTarget::Dock
1004 } else {
1005 RevealTarget::Center
1006 }
1007 })?;
1008
1009 match reveal {
1010 RevealStrategy::Always => match reveal_target {
1011 RevealTarget::Center => {
1012 task_workspace.update_in(cx, |workspace, window, cx| {
1013 let did_activate = workspace.activate_item(
1014 &terminal_to_replace,
1015 true,
1016 true,
1017 window,
1018 cx,
1019 );
1020
1021 anyhow::ensure!(did_activate, "Failed to retrieve terminal pane");
1022
1023 anyhow::Ok(())
1024 })??;
1025 }
1026 RevealTarget::Dock => {
1027 terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1028 terminal_panel.activate_terminal_view(
1029 &task_pane,
1030 terminal_item_index,
1031 true,
1032 window,
1033 cx,
1034 )
1035 })?;
1036
1037 cx.spawn(async move |cx| {
1038 task_workspace
1039 .update_in(cx, |workspace, window, cx| {
1040 workspace.focus_panel::<Self>(window, cx)
1041 })
1042 .ok()
1043 })
1044 .detach();
1045 }
1046 },
1047 RevealStrategy::NoFocus => match reveal_target {
1048 RevealTarget::Center => {
1049 task_workspace.update_in(cx, |workspace, window, cx| {
1050 workspace.active_pane().focus_handle(cx).focus(window, cx);
1051 })?;
1052 }
1053 RevealTarget::Dock => {
1054 terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1055 terminal_panel.activate_terminal_view(
1056 &task_pane,
1057 terminal_item_index,
1058 false,
1059 window,
1060 cx,
1061 )
1062 })?;
1063
1064 cx.spawn(async move |cx| {
1065 task_workspace
1066 .update_in(cx, |workspace, window, cx| {
1067 workspace.open_panel::<Self>(window, cx)
1068 })
1069 .ok()
1070 })
1071 .detach();
1072 }
1073 },
1074 RevealStrategy::Never => {}
1075 }
1076
1077 Ok(new_terminal.downgrade())
1078 })
1079 }
1080
1081 fn has_no_terminals(&self, cx: &App) -> bool {
1082 self.active_pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
1083 }
1084
1085 pub fn assistant_enabled(&self) -> bool {
1086 self.assistant_enabled
1087 }
1088
1089 /// Returns all panes in the terminal panel.
1090 pub fn panes(&self) -> Vec<&Entity<Pane>> {
1091 self.center.panes()
1092 }
1093
1094 /// Returns all non-empty terminal selections from all terminal views in all panes.
1095 pub fn terminal_selections(&self, cx: &App) -> Vec<String> {
1096 self.center
1097 .panes()
1098 .iter()
1099 .flat_map(|pane| {
1100 pane.read(cx).items().filter_map(|item| {
1101 let terminal_view = item.downcast::<crate::TerminalView>()?;
1102 terminal_view
1103 .read(cx)
1104 .terminal()
1105 .read(cx)
1106 .last_content
1107 .selection_text
1108 .clone()
1109 .filter(|text| !text.is_empty())
1110 })
1111 })
1112 .collect()
1113 }
1114
1115 fn is_enabled(&self, cx: &App) -> bool {
1116 self.workspace
1117 .upgrade()
1118 .is_some_and(|workspace| is_enabled_in_workspace(workspace.read(cx), cx))
1119 }
1120
1121 fn activate_pane_in_direction(
1122 &mut self,
1123 direction: SplitDirection,
1124 window: &mut Window,
1125 cx: &mut Context<Self>,
1126 ) {
1127 if let Some(pane) = self
1128 .center
1129 .find_pane_in_direction(&self.active_pane, direction, cx)
1130 {
1131 window.focus(&pane.focus_handle(cx), cx);
1132 } else {
1133 self.workspace
1134 .update(cx, |workspace, cx| {
1135 workspace.activate_pane_in_direction(direction, window, cx)
1136 })
1137 .ok();
1138 }
1139 }
1140
1141 fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1142 if let Some(to) = self
1143 .center
1144 .find_pane_in_direction(&self.active_pane, direction, cx)
1145 .cloned()
1146 {
1147 self.center.swap(&self.active_pane, &to, cx);
1148 cx.notify();
1149 }
1150 }
1151
1152 fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1153 if self
1154 .center
1155 .move_to_border(&self.active_pane, direction, cx)
1156 .unwrap()
1157 {
1158 cx.notify();
1159 }
1160 }
1161}
1162
1163/// Prepares a `SpawnInTerminal` by computing the command, args, and command_label
1164/// based on the shell configuration. This is a pure function that can be tested
1165/// without spawning actual terminals.
1166pub fn prepare_task_for_spawn(
1167 task: &SpawnInTerminal,
1168 shell: &Shell,
1169 is_windows: bool,
1170) -> SpawnInTerminal {
1171 let builder = ShellBuilder::new(shell, is_windows);
1172 let command_label = builder.command_label(task.command.as_deref().unwrap_or(""));
1173 let (command, args) = builder.build_no_quote(task.command.clone(), &task.args);
1174
1175 SpawnInTerminal {
1176 command_label,
1177 command: Some(command),
1178 args,
1179 ..task.clone()
1180 }
1181}
1182
1183fn is_enabled_in_workspace(workspace: &Workspace, cx: &App) -> bool {
1184 workspace.project().read(cx).supports_terminal(cx)
1185}
1186
1187pub fn new_terminal_pane(
1188 workspace: WeakEntity<Workspace>,
1189 project: Entity<Project>,
1190 zoomed: bool,
1191 window: &mut Window,
1192 cx: &mut Context<TerminalPanel>,
1193) -> Entity<Pane> {
1194 let terminal_panel = cx.entity();
1195 let pane = cx.new(|cx| {
1196 let mut pane = Pane::new(
1197 workspace.clone(),
1198 project.clone(),
1199 Default::default(),
1200 None,
1201 workspace::NewTerminal::default().boxed_clone(),
1202 false,
1203 window,
1204 cx,
1205 );
1206 pane.set_zoomed(zoomed, cx);
1207 pane.set_can_navigate(false, cx);
1208 pane.display_nav_history_buttons(None);
1209 pane.set_should_display_tab_bar(|_, _| true);
1210 pane.set_zoom_out_on_close(false);
1211
1212 let split_closure_terminal_panel = terminal_panel.downgrade();
1213 pane.set_can_split(Some(Arc::new(move |pane, dragged_item, _window, cx| {
1214 if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
1215 let is_current_pane = tab.pane == cx.entity();
1216 let Some(can_drag_away) = split_closure_terminal_panel
1217 .read_with(cx, |terminal_panel, _| {
1218 let current_panes = terminal_panel.center.panes();
1219 !current_panes.contains(&&tab.pane)
1220 || current_panes.len() > 1
1221 || (!is_current_pane || pane.items_len() > 1)
1222 })
1223 .ok()
1224 else {
1225 return false;
1226 };
1227 if can_drag_away {
1228 let item = if is_current_pane {
1229 pane.item_for_index(tab.ix)
1230 } else {
1231 tab.pane.read(cx).item_for_index(tab.ix)
1232 };
1233 if let Some(item) = item {
1234 return item.downcast::<TerminalView>().is_some();
1235 }
1236 }
1237 }
1238 false
1239 })));
1240
1241 let toolbar = pane.toolbar().clone();
1242 if let Some(callbacks) = cx.try_global::<workspace::PaneSearchBarCallbacks>() {
1243 let languages = Some(project.read(cx).languages().clone());
1244 (callbacks.setup_search_bar)(languages, &toolbar, window, cx);
1245 }
1246 let breadcrumbs = cx.new(|_| Breadcrumbs::new());
1247 toolbar.update(cx, |toolbar, cx| {
1248 toolbar.add_item(breadcrumbs, window, cx);
1249 });
1250
1251 pane
1252 });
1253
1254 cx.subscribe_in(&pane, window, TerminalPanel::handle_pane_event)
1255 .detach();
1256 cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1257
1258 pane
1259}
1260
1261async fn wait_for_terminals_tasks(
1262 terminals_for_task: Vec<(usize, Entity<Pane>, Entity<TerminalView>)>,
1263 cx: &mut AsyncApp,
1264) {
1265 let pending_tasks = terminals_for_task.iter().map(|(_, _, terminal)| {
1266 terminal.update(cx, |terminal_view, cx| {
1267 terminal_view
1268 .terminal()
1269 .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1270 })
1271 });
1272 join_all(pending_tasks).await;
1273}
1274
1275struct FailedToSpawnTerminal {
1276 error: String,
1277 focus_handle: FocusHandle,
1278}
1279
1280impl Focusable for FailedToSpawnTerminal {
1281 fn focus_handle(&self, _: &App) -> FocusHandle {
1282 self.focus_handle.clone()
1283 }
1284}
1285
1286impl Render for FailedToSpawnTerminal {
1287 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1288 let popover_menu = PopoverMenu::new("settings-popover")
1289 .trigger(
1290 IconButton::new("icon-button-popover", IconName::ChevronDown)
1291 .icon_size(IconSize::XSmall),
1292 )
1293 .menu(move |window, cx| {
1294 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
1295 context_menu
1296 .action("Open Settings", zed_actions::OpenSettings.boxed_clone())
1297 .action(
1298 "Edit settings.json",
1299 zed_actions::OpenSettingsFile.boxed_clone(),
1300 )
1301 }))
1302 })
1303 .anchor(Corner::TopRight)
1304 .offset(gpui::Point {
1305 x: px(0.0),
1306 y: px(2.0),
1307 });
1308
1309 v_flex()
1310 .track_focus(&self.focus_handle)
1311 .size_full()
1312 .p_4()
1313 .items_center()
1314 .justify_center()
1315 .bg(cx.theme().colors().editor_background)
1316 .child(
1317 v_flex()
1318 .max_w_112()
1319 .items_center()
1320 .justify_center()
1321 .text_center()
1322 .child(Label::new("Failed to spawn terminal"))
1323 .child(
1324 Label::new(self.error.to_string())
1325 .size(LabelSize::Small)
1326 .color(Color::Muted)
1327 .mb_4(),
1328 )
1329 .child(SplitButton::new(
1330 ButtonLike::new("open-settings-ui")
1331 .child(Label::new("Edit Settings").size(LabelSize::Small))
1332 .on_click(|_, window, cx| {
1333 window.dispatch_action(zed_actions::OpenSettings.boxed_clone(), cx);
1334 }),
1335 popover_menu.into_any_element(),
1336 )),
1337 )
1338 }
1339}
1340
1341impl EventEmitter<()> for FailedToSpawnTerminal {}
1342
1343impl workspace::Item for FailedToSpawnTerminal {
1344 type Event = ();
1345
1346 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1347 SharedString::new_static("Failed to spawn terminal")
1348 }
1349}
1350
1351impl EventEmitter<PanelEvent> for TerminalPanel {}
1352
1353impl Render for TerminalPanel {
1354 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1355 let registrar = cx
1356 .try_global::<workspace::PaneSearchBarCallbacks>()
1357 .map(|callbacks| {
1358 (callbacks.wrap_div_with_search_actions)(div(), self.active_pane.clone())
1359 })
1360 .unwrap_or_else(div);
1361 self.workspace
1362 .update(cx, |workspace, cx| {
1363 registrar.size_full().child(self.center.render(
1364 workspace.zoomed_item(),
1365 &workspace::PaneRenderContext {
1366 follower_states: &HashMap::default(),
1367 active_call: workspace.active_call(),
1368 active_pane: &self.active_pane,
1369 app_state: workspace.app_state(),
1370 project: workspace.project(),
1371 workspace: &workspace.weak_handle(),
1372 },
1373 window,
1374 cx,
1375 ))
1376 })
1377 .ok()
1378 .map(|div| {
1379 div.on_action({
1380 cx.listener(|terminal_panel, _: &ActivatePaneLeft, window, cx| {
1381 terminal_panel.activate_pane_in_direction(SplitDirection::Left, window, cx);
1382 })
1383 })
1384 .on_action({
1385 cx.listener(|terminal_panel, _: &ActivatePaneRight, window, cx| {
1386 terminal_panel.activate_pane_in_direction(
1387 SplitDirection::Right,
1388 window,
1389 cx,
1390 );
1391 })
1392 })
1393 .on_action({
1394 cx.listener(|terminal_panel, _: &ActivatePaneUp, window, cx| {
1395 terminal_panel.activate_pane_in_direction(SplitDirection::Up, window, cx);
1396 })
1397 })
1398 .on_action({
1399 cx.listener(|terminal_panel, _: &ActivatePaneDown, window, cx| {
1400 terminal_panel.activate_pane_in_direction(SplitDirection::Down, window, cx);
1401 })
1402 })
1403 .on_action(
1404 cx.listener(|terminal_panel, _action: &ActivateNextPane, window, cx| {
1405 let panes = terminal_panel.center.panes();
1406 if let Some(ix) = panes
1407 .iter()
1408 .position(|pane| **pane == terminal_panel.active_pane)
1409 {
1410 let next_ix = (ix + 1) % panes.len();
1411 window.focus(&panes[next_ix].focus_handle(cx), cx);
1412 }
1413 }),
1414 )
1415 .on_action(cx.listener(
1416 |terminal_panel, _action: &ActivatePreviousPane, window, cx| {
1417 let panes = terminal_panel.center.panes();
1418 if let Some(ix) = panes
1419 .iter()
1420 .position(|pane| **pane == terminal_panel.active_pane)
1421 {
1422 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1423 window.focus(&panes[prev_ix].focus_handle(cx), cx);
1424 }
1425 },
1426 ))
1427 .on_action(
1428 cx.listener(|terminal_panel, action: &ActivatePane, window, cx| {
1429 let panes = terminal_panel.center.panes();
1430 if let Some(&pane) = panes.get(action.0) {
1431 window.focus(&pane.read(cx).focus_handle(cx), cx);
1432 } else {
1433 let future =
1434 terminal_panel.new_pane_with_active_terminal(true, window, cx);
1435 cx.spawn_in(window, async move |terminal_panel, cx| {
1436 if let Some(new_pane) = future.await {
1437 _ = terminal_panel.update_in(
1438 cx,
1439 |terminal_panel, window, cx| {
1440 terminal_panel.center.split(
1441 &terminal_panel.active_pane,
1442 &new_pane,
1443 SplitDirection::Right,
1444 cx,
1445 );
1446 let new_pane = new_pane.read(cx);
1447 window.focus(&new_pane.focus_handle(cx), cx);
1448 },
1449 );
1450 }
1451 })
1452 .detach();
1453 }
1454 }),
1455 )
1456 .on_action(cx.listener(|terminal_panel, _: &SwapPaneLeft, _, cx| {
1457 terminal_panel.swap_pane_in_direction(SplitDirection::Left, cx);
1458 }))
1459 .on_action(cx.listener(|terminal_panel, _: &SwapPaneRight, _, cx| {
1460 terminal_panel.swap_pane_in_direction(SplitDirection::Right, cx);
1461 }))
1462 .on_action(cx.listener(|terminal_panel, _: &SwapPaneUp, _, cx| {
1463 terminal_panel.swap_pane_in_direction(SplitDirection::Up, cx);
1464 }))
1465 .on_action(cx.listener(|terminal_panel, _: &SwapPaneDown, _, cx| {
1466 terminal_panel.swap_pane_in_direction(SplitDirection::Down, cx);
1467 }))
1468 .on_action(cx.listener(|terminal_panel, _: &MovePaneLeft, _, cx| {
1469 terminal_panel.move_pane_to_border(SplitDirection::Left, cx);
1470 }))
1471 .on_action(cx.listener(|terminal_panel, _: &MovePaneRight, _, cx| {
1472 terminal_panel.move_pane_to_border(SplitDirection::Right, cx);
1473 }))
1474 .on_action(cx.listener(|terminal_panel, _: &MovePaneUp, _, cx| {
1475 terminal_panel.move_pane_to_border(SplitDirection::Up, cx);
1476 }))
1477 .on_action(cx.listener(|terminal_panel, _: &MovePaneDown, _, cx| {
1478 terminal_panel.move_pane_to_border(SplitDirection::Down, cx);
1479 }))
1480 .on_action(
1481 cx.listener(|terminal_panel, action: &MoveItemToPane, window, cx| {
1482 let Some(&target_pane) =
1483 terminal_panel.center.panes().get(action.destination)
1484 else {
1485 return;
1486 };
1487 move_active_item(
1488 &terminal_panel.active_pane,
1489 target_pane,
1490 action.focus,
1491 true,
1492 window,
1493 cx,
1494 );
1495 }),
1496 )
1497 .on_action(cx.listener(
1498 |terminal_panel, action: &MoveItemToPaneInDirection, window, cx| {
1499 let source_pane = &terminal_panel.active_pane;
1500 if let Some(destination_pane) = terminal_panel
1501 .center
1502 .find_pane_in_direction(source_pane, action.direction, cx)
1503 {
1504 move_active_item(
1505 source_pane,
1506 destination_pane,
1507 action.focus,
1508 true,
1509 window,
1510 cx,
1511 );
1512 };
1513 },
1514 ))
1515 })
1516 .unwrap_or_else(|| div())
1517 }
1518}
1519
1520impl Focusable for TerminalPanel {
1521 fn focus_handle(&self, cx: &App) -> FocusHandle {
1522 self.active_pane.focus_handle(cx)
1523 }
1524}
1525
1526impl Panel for TerminalPanel {
1527 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1528 match TerminalSettings::get_global(cx).dock {
1529 TerminalDockPosition::Left => DockPosition::Left,
1530 TerminalDockPosition::Bottom => DockPosition::Bottom,
1531 TerminalDockPosition::Right => DockPosition::Right,
1532 }
1533 }
1534
1535 fn position_is_valid(&self, _: DockPosition) -> bool {
1536 true
1537 }
1538
1539 fn set_position(
1540 &mut self,
1541 position: DockPosition,
1542 _window: &mut Window,
1543 cx: &mut Context<Self>,
1544 ) {
1545 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1546 let dock = match position {
1547 DockPosition::Left => TerminalDockPosition::Left,
1548 DockPosition::Bottom => TerminalDockPosition::Bottom,
1549 DockPosition::Right => TerminalDockPosition::Right,
1550 };
1551 settings.terminal.get_or_insert_default().dock = Some(dock);
1552 });
1553 }
1554
1555 fn size(&self, window: &Window, cx: &App) -> Pixels {
1556 let settings = TerminalSettings::get_global(cx);
1557 match self.position(window, cx) {
1558 DockPosition::Left | DockPosition::Right => {
1559 self.width.unwrap_or(settings.default_width)
1560 }
1561 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1562 }
1563 }
1564
1565 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1566 match self.position(window, cx) {
1567 DockPosition::Left | DockPosition::Right => self.width = size,
1568 DockPosition::Bottom => self.height = size,
1569 }
1570 cx.notify();
1571 cx.defer_in(window, |this, _, cx| {
1572 this.serialize(cx);
1573 })
1574 }
1575
1576 fn is_zoomed(&self, _window: &Window, cx: &App) -> bool {
1577 self.active_pane.read(cx).is_zoomed()
1578 }
1579
1580 fn set_zoomed(&mut self, zoomed: bool, _: &mut Window, cx: &mut Context<Self>) {
1581 for pane in self.center.panes() {
1582 pane.update(cx, |pane, cx| {
1583 pane.set_zoomed(zoomed, cx);
1584 })
1585 }
1586 cx.notify();
1587 }
1588
1589 fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
1590 let old_active = self.active;
1591 self.active = active;
1592 if !active || old_active == active || !self.has_no_terminals(cx) {
1593 return;
1594 }
1595 cx.defer_in(window, |this, window, cx| {
1596 let Ok(kind) = this
1597 .workspace
1598 .update(cx, |workspace, cx| default_working_directory(workspace, cx))
1599 else {
1600 return;
1601 };
1602
1603 this.add_terminal_shell(kind, RevealStrategy::Always, window, cx)
1604 .detach_and_log_err(cx)
1605 })
1606 }
1607
1608 fn icon_label(&self, _window: &Window, cx: &App) -> Option<String> {
1609 let count = self
1610 .center
1611 .panes()
1612 .into_iter()
1613 .map(|pane| pane.read(cx).items_len())
1614 .sum::<usize>();
1615 if count == 0 {
1616 None
1617 } else {
1618 Some(count.to_string())
1619 }
1620 }
1621
1622 fn persistent_name() -> &'static str {
1623 "TerminalPanel"
1624 }
1625
1626 fn panel_key() -> &'static str {
1627 TERMINAL_PANEL_KEY
1628 }
1629
1630 fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1631 if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1632 && TerminalSettings::get_global(cx).button
1633 {
1634 Some(IconName::TerminalAlt)
1635 } else {
1636 None
1637 }
1638 }
1639
1640 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1641 Some("Terminal Panel")
1642 }
1643
1644 fn toggle_action(&self) -> Box<dyn gpui::Action> {
1645 Box::new(ToggleFocus)
1646 }
1647
1648 fn pane(&self) -> Option<Entity<Pane>> {
1649 Some(self.active_pane.clone())
1650 }
1651
1652 fn activation_priority(&self) -> u32 {
1653 1
1654 }
1655}
1656
1657struct TerminalProvider(Entity<TerminalPanel>);
1658
1659impl workspace::TerminalProvider for TerminalProvider {
1660 fn spawn(
1661 &self,
1662 task: SpawnInTerminal,
1663 window: &mut Window,
1664 cx: &mut App,
1665 ) -> Task<Option<Result<ExitStatus>>> {
1666 let terminal_panel = self.0.clone();
1667 window.spawn(cx, async move |cx| {
1668 let terminal = terminal_panel
1669 .update_in(cx, |terminal_panel, window, cx| {
1670 terminal_panel.spawn_task(&task, window, cx)
1671 })
1672 .ok()?
1673 .await;
1674 match terminal {
1675 Ok(terminal) => {
1676 let exit_status = terminal
1677 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1678 .ok()?
1679 .await?;
1680 Some(Ok(exit_status))
1681 }
1682 Err(e) => Some(Err(e)),
1683 }
1684 })
1685 }
1686}
1687
1688struct InlineAssistTabBarButton {
1689 focus_handle: FocusHandle,
1690}
1691
1692impl Render for InlineAssistTabBarButton {
1693 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1694 let focus_handle = self.focus_handle.clone();
1695 IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1696 .icon_size(IconSize::Small)
1697 .on_click(cx.listener(|_, _, window, cx| {
1698 window.dispatch_action(InlineAssist::default().boxed_clone(), cx);
1699 }))
1700 .tooltip(move |_window, cx| {
1701 Tooltip::for_action_in("Inline Assist", &InlineAssist::default(), &focus_handle, cx)
1702 })
1703 }
1704}
1705
1706#[cfg(test)]
1707mod tests {
1708 use std::num::NonZero;
1709
1710 use super::*;
1711 use gpui::{TestAppContext, UpdateGlobal as _};
1712 use pretty_assertions::assert_eq;
1713 use project::FakeFs;
1714 use settings::SettingsStore;
1715 use workspace::MultiWorkspace;
1716
1717 #[test]
1718 fn test_prepare_empty_task() {
1719 let input = SpawnInTerminal::default();
1720 let shell = Shell::System;
1721
1722 let result = prepare_task_for_spawn(&input, &shell, false);
1723
1724 let expected_shell = util::get_system_shell();
1725 assert_eq!(result.env, HashMap::default());
1726 assert_eq!(result.cwd, None);
1727 assert_eq!(result.shell, Shell::System);
1728 assert_eq!(
1729 result.command,
1730 Some(expected_shell.clone()),
1731 "Empty tasks should spawn a -i shell"
1732 );
1733 assert_eq!(result.args, Vec::<String>::new());
1734 assert_eq!(
1735 result.command_label, expected_shell,
1736 "We show the shell launch for empty commands"
1737 );
1738 }
1739
1740 #[gpui::test]
1741 async fn test_bypass_max_tabs_limit(cx: &mut TestAppContext) {
1742 cx.executor().allow_parking();
1743 init_test(cx);
1744
1745 let fs = FakeFs::new(cx.executor());
1746 let project = Project::test(fs, [], cx).await;
1747 let window_handle =
1748 cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
1749
1750 let terminal_panel = window_handle
1751 .update(cx, |multi_workspace, window, cx| {
1752 multi_workspace.workspace().update(cx, |workspace, cx| {
1753 cx.new(|cx| TerminalPanel::new(workspace, window, cx))
1754 })
1755 })
1756 .unwrap();
1757
1758 set_max_tabs(cx, Some(3));
1759
1760 for _ in 0..5 {
1761 let task = window_handle
1762 .update(cx, |_, window, cx| {
1763 terminal_panel.update(cx, |panel, cx| {
1764 panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1765 })
1766 })
1767 .unwrap();
1768 task.await.unwrap();
1769 }
1770
1771 cx.run_until_parked();
1772
1773 let item_count =
1774 terminal_panel.read_with(cx, |panel, cx| panel.active_pane.read(cx).items_len());
1775
1776 assert_eq!(
1777 item_count, 5,
1778 "Terminal panel should bypass max_tabs limit and have all 5 terminals"
1779 );
1780 }
1781
1782 #[cfg(unix)]
1783 #[test]
1784 fn test_prepare_script_like_task() {
1785 let user_command = r#"REPO_URL=$(git remote get-url origin | sed -e \"s/^git@\\(.*\\):\\(.*\\)\\.git$/https:\\/\\/\\1\\/\\2/\"); COMMIT_SHA=$(git log -1 --format=\"%H\" -- \"${ZED_RELATIVE_FILE}\"); echo \"${REPO_URL}/blob/${COMMIT_SHA}/${ZED_RELATIVE_FILE}#L${ZED_ROW}-$(echo $(($(wc -l <<< \"$ZED_SELECTED_TEXT\") + $ZED_ROW - 1)))\" | xclip -selection clipboard"#.to_string();
1786 let expected_cwd = PathBuf::from("/some/work");
1787
1788 let input = SpawnInTerminal {
1789 command: Some(user_command.clone()),
1790 cwd: Some(expected_cwd.clone()),
1791 ..SpawnInTerminal::default()
1792 };
1793 let shell = Shell::System;
1794
1795 let result = prepare_task_for_spawn(&input, &shell, false);
1796
1797 let system_shell = util::get_system_shell();
1798 assert_eq!(result.env, HashMap::default());
1799 assert_eq!(result.cwd, Some(expected_cwd));
1800 assert_eq!(result.shell, Shell::System);
1801 assert_eq!(result.command, Some(system_shell.clone()));
1802 assert_eq!(
1803 result.args,
1804 vec!["-i".to_string(), "-c".to_string(), user_command.clone()],
1805 "User command should have been moved into the arguments, as we're spawning a new -i shell",
1806 );
1807 assert_eq!(
1808 result.command_label,
1809 format!(
1810 "{system_shell} {interactive}-c '{user_command}'",
1811 interactive = if cfg!(windows) { "" } else { "-i " }
1812 ),
1813 "We want to show to the user the entire command spawned"
1814 );
1815 }
1816
1817 #[gpui::test]
1818 async fn renders_error_if_default_shell_fails(cx: &mut TestAppContext) {
1819 cx.executor().allow_parking();
1820 init_test(cx);
1821
1822 cx.update(|cx| {
1823 SettingsStore::update_global(cx, |store, cx| {
1824 store.update_user_settings(cx, |settings| {
1825 settings.terminal.get_or_insert_default().project.shell =
1826 Some(settings::Shell::Program("__nonexistent_shell__".to_owned()));
1827 });
1828 });
1829 });
1830
1831 let fs = FakeFs::new(cx.executor());
1832 let project = Project::test(fs, [], cx).await;
1833 let window_handle =
1834 cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
1835
1836 let terminal_panel = window_handle
1837 .update(cx, |multi_workspace, window, cx| {
1838 multi_workspace.workspace().update(cx, |workspace, cx| {
1839 cx.new(|cx| TerminalPanel::new(workspace, window, cx))
1840 })
1841 })
1842 .unwrap();
1843
1844 window_handle
1845 .update(cx, |_, window, cx| {
1846 terminal_panel.update(cx, |terminal_panel, cx| {
1847 terminal_panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1848 })
1849 })
1850 .unwrap()
1851 .await
1852 .unwrap_err();
1853
1854 window_handle
1855 .update(cx, |_, _, cx| {
1856 terminal_panel.update(cx, |terminal_panel, cx| {
1857 assert!(
1858 terminal_panel
1859 .active_pane
1860 .read(cx)
1861 .items()
1862 .any(|item| item.downcast::<FailedToSpawnTerminal>().is_some()),
1863 "should spawn `FailedToSpawnTerminal` pane"
1864 );
1865 })
1866 })
1867 .unwrap();
1868 }
1869
1870 #[gpui::test]
1871 async fn test_local_terminal_in_local_project(cx: &mut TestAppContext) {
1872 cx.executor().allow_parking();
1873 init_test(cx);
1874
1875 let fs = FakeFs::new(cx.executor());
1876 let project = Project::test(fs, [], cx).await;
1877 let window_handle =
1878 cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
1879
1880 let terminal_panel = window_handle
1881 .update(cx, |multi_workspace, window, cx| {
1882 multi_workspace.workspace().update(cx, |workspace, cx| {
1883 cx.new(|cx| TerminalPanel::new(workspace, window, cx))
1884 })
1885 })
1886 .unwrap();
1887
1888 let result = window_handle
1889 .update(cx, |_, window, cx| {
1890 terminal_panel.update(cx, |terminal_panel, cx| {
1891 terminal_panel.add_local_terminal_shell(RevealStrategy::Always, window, cx)
1892 })
1893 })
1894 .unwrap()
1895 .await;
1896
1897 assert!(
1898 result.is_ok(),
1899 "local terminal should successfully create in local project"
1900 );
1901 }
1902
1903 fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
1904 cx.update_global(|store: &mut SettingsStore, cx| {
1905 store.update_user_settings(cx, |settings| {
1906 settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
1907 });
1908 });
1909 }
1910
1911 pub fn init_test(cx: &mut TestAppContext) {
1912 cx.update(|cx| {
1913 let store = SettingsStore::test(cx);
1914 cx.set_global(store);
1915 theme::init(theme::LoadThemes::JustBase, cx);
1916 editor::init(cx);
1917 crate::init(cx);
1918 });
1919 }
1920}