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, None, 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| {
789 project.create_terminal_task(task, None, cx)
790 })
791 .await?;
792 let result = workspace.update_in(cx, |workspace, window, cx| {
793 let terminal_view = Box::new(cx.new(|cx| {
794 TerminalView::new(
795 terminal.clone(),
796 workspace.weak_handle(),
797 workspace.database_id(),
798 workspace.project().downgrade(),
799 window,
800 cx,
801 )
802 }));
803
804 match reveal_strategy {
805 RevealStrategy::Always => {
806 workspace.focus_panel::<Self>(window, cx);
807 }
808 RevealStrategy::NoFocus => {
809 workspace.open_panel::<Self>(window, cx);
810 }
811 RevealStrategy::Never => {}
812 }
813
814 pane.update(cx, |pane, cx| {
815 let focus = matches!(reveal_strategy, RevealStrategy::Always);
816 pane.add_item(terminal_view, true, focus, None, window, cx);
817 });
818
819 Ok(terminal.downgrade())
820 })?;
821 terminal_panel.update(cx, |terminal_panel, cx| {
822 terminal_panel.pending_terminals_to_add =
823 terminal_panel.pending_terminals_to_add.saturating_sub(1);
824 terminal_panel.serialize(cx)
825 })?;
826 result
827 })
828 }
829
830 fn add_terminal_shell(
831 &mut self,
832 cwd: Option<PathBuf>,
833 reveal_strategy: RevealStrategy,
834 window: &mut Window,
835 cx: &mut Context<Self>,
836 ) -> Task<Result<WeakEntity<Terminal>>> {
837 self.add_terminal_shell_internal(false, cwd, reveal_strategy, window, cx)
838 }
839
840 fn add_local_terminal_shell(
841 &mut self,
842 reveal_strategy: RevealStrategy,
843 window: &mut Window,
844 cx: &mut Context<Self>,
845 ) -> Task<Result<WeakEntity<Terminal>>> {
846 self.add_terminal_shell_internal(true, None, reveal_strategy, window, cx)
847 }
848
849 fn add_terminal_shell_internal(
850 &mut self,
851 force_local: bool,
852 cwd: Option<PathBuf>,
853 reveal_strategy: RevealStrategy,
854 window: &mut Window,
855 cx: &mut Context<Self>,
856 ) -> Task<Result<WeakEntity<Terminal>>> {
857 let workspace = self.workspace.clone();
858
859 cx.spawn_in(window, async move |terminal_panel, cx| {
860 if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
861 anyhow::bail!("terminal not yet supported for collaborative projects");
862 }
863 let pane = terminal_panel.update(cx, |terminal_panel, _| {
864 terminal_panel.pending_terminals_to_add += 1;
865 terminal_panel.active_pane.clone()
866 })?;
867 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
868 let terminal = if force_local {
869 project
870 .update(cx, |project, cx| project.create_local_terminal(cx))
871 .await
872 } else {
873 project
874 .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))
875 .await
876 };
877
878 match terminal {
879 Ok(terminal) => {
880 let result = workspace.update_in(cx, |workspace, window, cx| {
881 let terminal_view = Box::new(cx.new(|cx| {
882 TerminalView::new(
883 terminal.clone(),
884 workspace.weak_handle(),
885 workspace.database_id(),
886 workspace.project().downgrade(),
887 window,
888 cx,
889 )
890 }));
891
892 match reveal_strategy {
893 RevealStrategy::Always => {
894 workspace.focus_panel::<Self>(window, cx);
895 }
896 RevealStrategy::NoFocus => {
897 workspace.open_panel::<Self>(window, cx);
898 }
899 RevealStrategy::Never => {}
900 }
901
902 pane.update(cx, |pane, cx| {
903 let focus = matches!(reveal_strategy, RevealStrategy::Always);
904 pane.add_item(terminal_view, true, focus, None, window, cx);
905 });
906
907 Ok(terminal.downgrade())
908 })?;
909 terminal_panel.update(cx, |terminal_panel, cx| {
910 terminal_panel.pending_terminals_to_add =
911 terminal_panel.pending_terminals_to_add.saturating_sub(1);
912 terminal_panel.serialize(cx)
913 })?;
914 result
915 }
916 Err(error) => {
917 pane.update_in(cx, |pane, window, cx| {
918 let focus = pane.has_focus(window, cx);
919 let failed_to_spawn = cx.new(|cx| FailedToSpawnTerminal {
920 error: error.to_string(),
921 focus_handle: cx.focus_handle(),
922 });
923 pane.add_item(Box::new(failed_to_spawn), true, focus, None, window, cx);
924 })?;
925 Err(error)
926 }
927 }
928 })
929 }
930
931 fn serialize(&mut self, cx: &mut Context<Self>) {
932 let height = self.height;
933 let width = self.width;
934 let Some(serialization_key) = self
935 .workspace
936 .read_with(cx, |workspace, _| {
937 TerminalPanel::serialization_key(workspace)
938 })
939 .ok()
940 .flatten()
941 else {
942 return;
943 };
944 self.pending_serialization = cx.spawn(async move |terminal_panel, cx| {
945 cx.background_executor()
946 .timer(Duration::from_millis(50))
947 .await;
948 let terminal_panel = terminal_panel.upgrade()?;
949 let items = terminal_panel.update(cx, |terminal_panel, cx| {
950 SerializedItems::WithSplits(serialize_pane_group(
951 &terminal_panel.center,
952 &terminal_panel.active_pane,
953 cx,
954 ))
955 });
956 cx.background_spawn(
957 async move {
958 KEY_VALUE_STORE
959 .write_kvp(
960 serialization_key,
961 serde_json::to_string(&SerializedTerminalPanel {
962 items,
963 active_item_id: None,
964 height,
965 width,
966 })?,
967 )
968 .await?;
969 anyhow::Ok(())
970 }
971 .log_err(),
972 )
973 .await;
974 Some(())
975 });
976 }
977
978 fn replace_terminal(
979 &self,
980 spawn_task: SpawnInTerminal,
981 task_pane: Entity<Pane>,
982 terminal_item_index: usize,
983 terminal_to_replace: Entity<TerminalView>,
984 window: &mut Window,
985 cx: &mut Context<Self>,
986 ) -> Task<Result<WeakEntity<Terminal>>> {
987 let reveal = spawn_task.reveal;
988 let task_workspace = self.workspace.clone();
989 cx.spawn_in(window, async move |terminal_panel, cx| {
990 let project = terminal_panel.update(cx, |this, cx| {
991 this.workspace
992 .update(cx, |workspace, _| workspace.project().clone())
993 })??;
994 let new_terminal = project
995 .update(cx, |project, cx| {
996 project.create_terminal_task(spawn_task, None, cx)
997 })
998 .await?;
999 terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| {
1000 terminal_to_replace.set_terminal(new_terminal.clone(), window, cx);
1001 })?;
1002
1003 let reveal_target = terminal_panel.update(cx, |panel, _| {
1004 if panel.center.panes().iter().any(|p| **p == task_pane) {
1005 RevealTarget::Dock
1006 } else {
1007 RevealTarget::Center
1008 }
1009 })?;
1010
1011 match reveal {
1012 RevealStrategy::Always => match reveal_target {
1013 RevealTarget::Center => {
1014 task_workspace.update_in(cx, |workspace, window, cx| {
1015 let did_activate = workspace.activate_item(
1016 &terminal_to_replace,
1017 true,
1018 true,
1019 window,
1020 cx,
1021 );
1022
1023 anyhow::ensure!(did_activate, "Failed to retrieve terminal pane");
1024
1025 anyhow::Ok(())
1026 })??;
1027 }
1028 RevealTarget::Dock => {
1029 terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1030 terminal_panel.activate_terminal_view(
1031 &task_pane,
1032 terminal_item_index,
1033 true,
1034 window,
1035 cx,
1036 )
1037 })?;
1038
1039 cx.spawn(async move |cx| {
1040 task_workspace
1041 .update_in(cx, |workspace, window, cx| {
1042 workspace.focus_panel::<Self>(window, cx)
1043 })
1044 .ok()
1045 })
1046 .detach();
1047 }
1048 },
1049 RevealStrategy::NoFocus => match reveal_target {
1050 RevealTarget::Center => {
1051 task_workspace.update_in(cx, |workspace, window, cx| {
1052 workspace.active_pane().focus_handle(cx).focus(window, cx);
1053 })?;
1054 }
1055 RevealTarget::Dock => {
1056 terminal_panel.update_in(cx, |terminal_panel, window, cx| {
1057 terminal_panel.activate_terminal_view(
1058 &task_pane,
1059 terminal_item_index,
1060 false,
1061 window,
1062 cx,
1063 )
1064 })?;
1065
1066 cx.spawn(async move |cx| {
1067 task_workspace
1068 .update_in(cx, |workspace, window, cx| {
1069 workspace.open_panel::<Self>(window, cx)
1070 })
1071 .ok()
1072 })
1073 .detach();
1074 }
1075 },
1076 RevealStrategy::Never => {}
1077 }
1078
1079 Ok(new_terminal.downgrade())
1080 })
1081 }
1082
1083 fn has_no_terminals(&self, cx: &App) -> bool {
1084 self.active_pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
1085 }
1086
1087 pub fn assistant_enabled(&self) -> bool {
1088 self.assistant_enabled
1089 }
1090
1091 /// Returns all panes in the terminal panel.
1092 pub fn panes(&self) -> Vec<&Entity<Pane>> {
1093 self.center.panes()
1094 }
1095
1096 /// Returns all non-empty terminal selections from all terminal views in all panes.
1097 pub fn terminal_selections(&self, cx: &App) -> Vec<String> {
1098 self.center
1099 .panes()
1100 .iter()
1101 .flat_map(|pane| {
1102 pane.read(cx).items().filter_map(|item| {
1103 let terminal_view = item.downcast::<crate::TerminalView>()?;
1104 terminal_view
1105 .read(cx)
1106 .terminal()
1107 .read(cx)
1108 .last_content
1109 .selection_text
1110 .clone()
1111 .filter(|text| !text.is_empty())
1112 })
1113 })
1114 .collect()
1115 }
1116
1117 fn is_enabled(&self, cx: &App) -> bool {
1118 self.workspace
1119 .upgrade()
1120 .is_some_and(|workspace| is_enabled_in_workspace(workspace.read(cx), cx))
1121 }
1122
1123 fn activate_pane_in_direction(
1124 &mut self,
1125 direction: SplitDirection,
1126 window: &mut Window,
1127 cx: &mut Context<Self>,
1128 ) {
1129 if let Some(pane) = self
1130 .center
1131 .find_pane_in_direction(&self.active_pane, direction, cx)
1132 {
1133 window.focus(&pane.focus_handle(cx), cx);
1134 } else {
1135 self.workspace
1136 .update(cx, |workspace, cx| {
1137 workspace.activate_pane_in_direction(direction, window, cx)
1138 })
1139 .ok();
1140 }
1141 }
1142
1143 fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1144 if let Some(to) = self
1145 .center
1146 .find_pane_in_direction(&self.active_pane, direction, cx)
1147 .cloned()
1148 {
1149 self.center.swap(&self.active_pane, &to, cx);
1150 cx.notify();
1151 }
1152 }
1153
1154 fn move_pane_to_border(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1155 if self
1156 .center
1157 .move_to_border(&self.active_pane, direction, cx)
1158 .unwrap()
1159 {
1160 cx.notify();
1161 }
1162 }
1163}
1164
1165/// Prepares a `SpawnInTerminal` by computing the command, args, and command_label
1166/// based on the shell configuration. This is a pure function that can be tested
1167/// without spawning actual terminals.
1168pub fn prepare_task_for_spawn(
1169 task: &SpawnInTerminal,
1170 shell: &Shell,
1171 is_windows: bool,
1172) -> SpawnInTerminal {
1173 let builder = ShellBuilder::new(shell, is_windows);
1174 let command_label = builder.command_label(task.command.as_deref().unwrap_or(""));
1175 let (command, args) = builder.build_no_quote(task.command.clone(), &task.args);
1176
1177 SpawnInTerminal {
1178 command_label,
1179 command: Some(command),
1180 args,
1181 ..task.clone()
1182 }
1183}
1184
1185fn is_enabled_in_workspace(workspace: &Workspace, cx: &App) -> bool {
1186 workspace.project().read(cx).supports_terminal(cx)
1187}
1188
1189pub fn new_terminal_pane(
1190 workspace: WeakEntity<Workspace>,
1191 project: Entity<Project>,
1192 zoomed: bool,
1193 window: &mut Window,
1194 cx: &mut Context<TerminalPanel>,
1195) -> Entity<Pane> {
1196 let terminal_panel = cx.entity();
1197 let pane = cx.new(|cx| {
1198 let mut pane = Pane::new(
1199 workspace.clone(),
1200 project.clone(),
1201 Default::default(),
1202 None,
1203 workspace::NewTerminal::default().boxed_clone(),
1204 false,
1205 window,
1206 cx,
1207 );
1208 pane.set_zoomed(zoomed, cx);
1209 pane.set_can_navigate(false, cx);
1210 pane.display_nav_history_buttons(None);
1211 pane.set_should_display_tab_bar(|_, _| true);
1212 pane.set_zoom_out_on_close(false);
1213
1214 let split_closure_terminal_panel = terminal_panel.downgrade();
1215 pane.set_can_split(Some(Arc::new(move |pane, dragged_item, _window, cx| {
1216 if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
1217 let is_current_pane = tab.pane == cx.entity();
1218 let Some(can_drag_away) = split_closure_terminal_panel
1219 .read_with(cx, |terminal_panel, _| {
1220 let current_panes = terminal_panel.center.panes();
1221 !current_panes.contains(&&tab.pane)
1222 || current_panes.len() > 1
1223 || (!is_current_pane || pane.items_len() > 1)
1224 })
1225 .ok()
1226 else {
1227 return false;
1228 };
1229 if can_drag_away {
1230 let item = if is_current_pane {
1231 pane.item_for_index(tab.ix)
1232 } else {
1233 tab.pane.read(cx).item_for_index(tab.ix)
1234 };
1235 if let Some(item) = item {
1236 return item.downcast::<TerminalView>().is_some();
1237 }
1238 }
1239 }
1240 false
1241 })));
1242
1243 let toolbar = pane.toolbar().clone();
1244 if let Some(callbacks) = cx.try_global::<workspace::PaneSearchBarCallbacks>() {
1245 let languages = Some(project.read(cx).languages().clone());
1246 (callbacks.setup_search_bar)(languages, &toolbar, window, cx);
1247 }
1248 let breadcrumbs = cx.new(|_| Breadcrumbs::new());
1249 toolbar.update(cx, |toolbar, cx| {
1250 toolbar.add_item(breadcrumbs, window, cx);
1251 });
1252
1253 pane
1254 });
1255
1256 cx.subscribe_in(&pane, window, TerminalPanel::handle_pane_event)
1257 .detach();
1258 cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1259
1260 pane
1261}
1262
1263async fn wait_for_terminals_tasks(
1264 terminals_for_task: Vec<(usize, Entity<Pane>, Entity<TerminalView>)>,
1265 cx: &mut AsyncApp,
1266) {
1267 let pending_tasks = terminals_for_task.iter().map(|(_, _, terminal)| {
1268 terminal.update(cx, |terminal_view, cx| {
1269 terminal_view
1270 .terminal()
1271 .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1272 })
1273 });
1274 join_all(pending_tasks).await;
1275}
1276
1277struct FailedToSpawnTerminal {
1278 error: String,
1279 focus_handle: FocusHandle,
1280}
1281
1282impl Focusable for FailedToSpawnTerminal {
1283 fn focus_handle(&self, _: &App) -> FocusHandle {
1284 self.focus_handle.clone()
1285 }
1286}
1287
1288impl Render for FailedToSpawnTerminal {
1289 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1290 let popover_menu = PopoverMenu::new("settings-popover")
1291 .trigger(
1292 IconButton::new("icon-button-popover", IconName::ChevronDown)
1293 .icon_size(IconSize::XSmall),
1294 )
1295 .menu(move |window, cx| {
1296 Some(ContextMenu::build(window, cx, |context_menu, _, _| {
1297 context_menu
1298 .action("Open Settings", zed_actions::OpenSettings.boxed_clone())
1299 .action(
1300 "Edit settings.json",
1301 zed_actions::OpenSettingsFile.boxed_clone(),
1302 )
1303 }))
1304 })
1305 .anchor(Corner::TopRight)
1306 .offset(gpui::Point {
1307 x: px(0.0),
1308 y: px(2.0),
1309 });
1310
1311 v_flex()
1312 .track_focus(&self.focus_handle)
1313 .size_full()
1314 .p_4()
1315 .items_center()
1316 .justify_center()
1317 .bg(cx.theme().colors().editor_background)
1318 .child(
1319 v_flex()
1320 .max_w_112()
1321 .items_center()
1322 .justify_center()
1323 .text_center()
1324 .child(Label::new("Failed to spawn terminal"))
1325 .child(
1326 Label::new(self.error.to_string())
1327 .size(LabelSize::Small)
1328 .color(Color::Muted)
1329 .mb_4(),
1330 )
1331 .child(SplitButton::new(
1332 ButtonLike::new("open-settings-ui")
1333 .child(Label::new("Edit Settings").size(LabelSize::Small))
1334 .on_click(|_, window, cx| {
1335 window.dispatch_action(zed_actions::OpenSettings.boxed_clone(), cx);
1336 }),
1337 popover_menu.into_any_element(),
1338 )),
1339 )
1340 }
1341}
1342
1343impl EventEmitter<()> for FailedToSpawnTerminal {}
1344
1345impl workspace::Item for FailedToSpawnTerminal {
1346 type Event = ();
1347
1348 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
1349 SharedString::new_static("Failed to spawn terminal")
1350 }
1351}
1352
1353impl EventEmitter<PanelEvent> for TerminalPanel {}
1354
1355impl Render for TerminalPanel {
1356 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1357 let registrar = cx
1358 .try_global::<workspace::PaneSearchBarCallbacks>()
1359 .map(|callbacks| {
1360 (callbacks.wrap_div_with_search_actions)(div(), self.active_pane.clone())
1361 })
1362 .unwrap_or_else(div);
1363 self.workspace
1364 .update(cx, |workspace, cx| {
1365 registrar.size_full().child(self.center.render(
1366 workspace.zoomed_item(),
1367 &workspace::PaneRenderContext {
1368 follower_states: &HashMap::default(),
1369 active_call: workspace.active_call(),
1370 active_pane: &self.active_pane,
1371 app_state: workspace.app_state(),
1372 project: workspace.project(),
1373 workspace: &workspace.weak_handle(),
1374 },
1375 window,
1376 cx,
1377 ))
1378 })
1379 .ok()
1380 .map(|div| {
1381 div.on_action({
1382 cx.listener(|terminal_panel, _: &ActivatePaneLeft, window, cx| {
1383 terminal_panel.activate_pane_in_direction(SplitDirection::Left, window, cx);
1384 })
1385 })
1386 .on_action({
1387 cx.listener(|terminal_panel, _: &ActivatePaneRight, window, cx| {
1388 terminal_panel.activate_pane_in_direction(
1389 SplitDirection::Right,
1390 window,
1391 cx,
1392 );
1393 })
1394 })
1395 .on_action({
1396 cx.listener(|terminal_panel, _: &ActivatePaneUp, window, cx| {
1397 terminal_panel.activate_pane_in_direction(SplitDirection::Up, window, cx);
1398 })
1399 })
1400 .on_action({
1401 cx.listener(|terminal_panel, _: &ActivatePaneDown, window, cx| {
1402 terminal_panel.activate_pane_in_direction(SplitDirection::Down, window, cx);
1403 })
1404 })
1405 .on_action(
1406 cx.listener(|terminal_panel, _action: &ActivateNextPane, window, cx| {
1407 let panes = terminal_panel.center.panes();
1408 if let Some(ix) = panes
1409 .iter()
1410 .position(|pane| **pane == terminal_panel.active_pane)
1411 {
1412 let next_ix = (ix + 1) % panes.len();
1413 window.focus(&panes[next_ix].focus_handle(cx), cx);
1414 }
1415 }),
1416 )
1417 .on_action(cx.listener(
1418 |terminal_panel, _action: &ActivatePreviousPane, window, cx| {
1419 let panes = terminal_panel.center.panes();
1420 if let Some(ix) = panes
1421 .iter()
1422 .position(|pane| **pane == terminal_panel.active_pane)
1423 {
1424 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1425 window.focus(&panes[prev_ix].focus_handle(cx), cx);
1426 }
1427 },
1428 ))
1429 .on_action(
1430 cx.listener(|terminal_panel, action: &ActivatePane, window, cx| {
1431 let panes = terminal_panel.center.panes();
1432 if let Some(&pane) = panes.get(action.0) {
1433 window.focus(&pane.read(cx).focus_handle(cx), cx);
1434 } else {
1435 let future =
1436 terminal_panel.new_pane_with_active_terminal(true, window, cx);
1437 cx.spawn_in(window, async move |terminal_panel, cx| {
1438 if let Some(new_pane) = future.await {
1439 _ = terminal_panel.update_in(
1440 cx,
1441 |terminal_panel, window, cx| {
1442 terminal_panel.center.split(
1443 &terminal_panel.active_pane,
1444 &new_pane,
1445 SplitDirection::Right,
1446 cx,
1447 );
1448 let new_pane = new_pane.read(cx);
1449 window.focus(&new_pane.focus_handle(cx), cx);
1450 },
1451 );
1452 }
1453 })
1454 .detach();
1455 }
1456 }),
1457 )
1458 .on_action(cx.listener(|terminal_panel, _: &SwapPaneLeft, _, cx| {
1459 terminal_panel.swap_pane_in_direction(SplitDirection::Left, cx);
1460 }))
1461 .on_action(cx.listener(|terminal_panel, _: &SwapPaneRight, _, cx| {
1462 terminal_panel.swap_pane_in_direction(SplitDirection::Right, cx);
1463 }))
1464 .on_action(cx.listener(|terminal_panel, _: &SwapPaneUp, _, cx| {
1465 terminal_panel.swap_pane_in_direction(SplitDirection::Up, cx);
1466 }))
1467 .on_action(cx.listener(|terminal_panel, _: &SwapPaneDown, _, cx| {
1468 terminal_panel.swap_pane_in_direction(SplitDirection::Down, cx);
1469 }))
1470 .on_action(cx.listener(|terminal_panel, _: &MovePaneLeft, _, cx| {
1471 terminal_panel.move_pane_to_border(SplitDirection::Left, cx);
1472 }))
1473 .on_action(cx.listener(|terminal_panel, _: &MovePaneRight, _, cx| {
1474 terminal_panel.move_pane_to_border(SplitDirection::Right, cx);
1475 }))
1476 .on_action(cx.listener(|terminal_panel, _: &MovePaneUp, _, cx| {
1477 terminal_panel.move_pane_to_border(SplitDirection::Up, cx);
1478 }))
1479 .on_action(cx.listener(|terminal_panel, _: &MovePaneDown, _, cx| {
1480 terminal_panel.move_pane_to_border(SplitDirection::Down, cx);
1481 }))
1482 .on_action(
1483 cx.listener(|terminal_panel, action: &MoveItemToPane, window, cx| {
1484 let Some(&target_pane) =
1485 terminal_panel.center.panes().get(action.destination)
1486 else {
1487 return;
1488 };
1489 move_active_item(
1490 &terminal_panel.active_pane,
1491 target_pane,
1492 action.focus,
1493 true,
1494 window,
1495 cx,
1496 );
1497 }),
1498 )
1499 .on_action(cx.listener(
1500 |terminal_panel, action: &MoveItemToPaneInDirection, window, cx| {
1501 let source_pane = &terminal_panel.active_pane;
1502 if let Some(destination_pane) = terminal_panel
1503 .center
1504 .find_pane_in_direction(source_pane, action.direction, cx)
1505 {
1506 move_active_item(
1507 source_pane,
1508 destination_pane,
1509 action.focus,
1510 true,
1511 window,
1512 cx,
1513 );
1514 };
1515 },
1516 ))
1517 })
1518 .unwrap_or_else(|| div())
1519 }
1520}
1521
1522impl Focusable for TerminalPanel {
1523 fn focus_handle(&self, cx: &App) -> FocusHandle {
1524 self.active_pane.focus_handle(cx)
1525 }
1526}
1527
1528impl Panel for TerminalPanel {
1529 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1530 match TerminalSettings::get_global(cx).dock {
1531 TerminalDockPosition::Left => DockPosition::Left,
1532 TerminalDockPosition::Bottom => DockPosition::Bottom,
1533 TerminalDockPosition::Right => DockPosition::Right,
1534 }
1535 }
1536
1537 fn position_is_valid(&self, _: DockPosition) -> bool {
1538 true
1539 }
1540
1541 fn set_position(
1542 &mut self,
1543 position: DockPosition,
1544 _window: &mut Window,
1545 cx: &mut Context<Self>,
1546 ) {
1547 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1548 let dock = match position {
1549 DockPosition::Left => TerminalDockPosition::Left,
1550 DockPosition::Bottom => TerminalDockPosition::Bottom,
1551 DockPosition::Right => TerminalDockPosition::Right,
1552 };
1553 settings.terminal.get_or_insert_default().dock = Some(dock);
1554 });
1555 }
1556
1557 fn size(&self, window: &Window, cx: &App) -> Pixels {
1558 let settings = TerminalSettings::get_global(cx);
1559 match self.position(window, cx) {
1560 DockPosition::Left | DockPosition::Right => {
1561 self.width.unwrap_or(settings.default_width)
1562 }
1563 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1564 }
1565 }
1566
1567 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1568 match self.position(window, cx) {
1569 DockPosition::Left | DockPosition::Right => self.width = size,
1570 DockPosition::Bottom => self.height = size,
1571 }
1572 cx.notify();
1573 cx.defer_in(window, |this, _, cx| {
1574 this.serialize(cx);
1575 })
1576 }
1577
1578 fn is_zoomed(&self, _window: &Window, cx: &App) -> bool {
1579 self.active_pane.read(cx).is_zoomed()
1580 }
1581
1582 fn set_zoomed(&mut self, zoomed: bool, _: &mut Window, cx: &mut Context<Self>) {
1583 for pane in self.center.panes() {
1584 pane.update(cx, |pane, cx| {
1585 pane.set_zoomed(zoomed, cx);
1586 })
1587 }
1588 cx.notify();
1589 }
1590
1591 fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
1592 let old_active = self.active;
1593 self.active = active;
1594 if !active || old_active == active || !self.has_no_terminals(cx) {
1595 return;
1596 }
1597 cx.defer_in(window, |this, window, cx| {
1598 let Ok(kind) = this
1599 .workspace
1600 .update(cx, |workspace, cx| default_working_directory(workspace, cx))
1601 else {
1602 return;
1603 };
1604
1605 this.add_terminal_shell(kind, RevealStrategy::Always, window, cx)
1606 .detach_and_log_err(cx)
1607 })
1608 }
1609
1610 fn icon_label(&self, _window: &Window, cx: &App) -> Option<String> {
1611 let count = self
1612 .center
1613 .panes()
1614 .into_iter()
1615 .map(|pane| pane.read(cx).items_len())
1616 .sum::<usize>();
1617 if count == 0 {
1618 None
1619 } else {
1620 Some(count.to_string())
1621 }
1622 }
1623
1624 fn persistent_name() -> &'static str {
1625 "TerminalPanel"
1626 }
1627
1628 fn panel_key() -> &'static str {
1629 TERMINAL_PANEL_KEY
1630 }
1631
1632 fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1633 if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1634 && TerminalSettings::get_global(cx).button
1635 {
1636 Some(IconName::TerminalAlt)
1637 } else {
1638 None
1639 }
1640 }
1641
1642 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1643 Some("Terminal Panel")
1644 }
1645
1646 fn toggle_action(&self) -> Box<dyn gpui::Action> {
1647 Box::new(ToggleFocus)
1648 }
1649
1650 fn pane(&self) -> Option<Entity<Pane>> {
1651 Some(self.active_pane.clone())
1652 }
1653
1654 fn activation_priority(&self) -> u32 {
1655 1
1656 }
1657}
1658
1659struct TerminalProvider(Entity<TerminalPanel>);
1660
1661impl workspace::TerminalProvider for TerminalProvider {
1662 fn spawn(
1663 &self,
1664 task: SpawnInTerminal,
1665 window: &mut Window,
1666 cx: &mut App,
1667 ) -> Task<Option<Result<ExitStatus>>> {
1668 let terminal_panel = self.0.clone();
1669 window.spawn(cx, async move |cx| {
1670 let terminal = terminal_panel
1671 .update_in(cx, |terminal_panel, window, cx| {
1672 terminal_panel.spawn_task(&task, window, cx)
1673 })
1674 .ok()?
1675 .await;
1676 match terminal {
1677 Ok(terminal) => {
1678 let exit_status = terminal
1679 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1680 .ok()?
1681 .await?;
1682 Some(Ok(exit_status))
1683 }
1684 Err(e) => Some(Err(e)),
1685 }
1686 })
1687 }
1688}
1689
1690struct InlineAssistTabBarButton {
1691 focus_handle: FocusHandle,
1692}
1693
1694impl Render for InlineAssistTabBarButton {
1695 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1696 let focus_handle = self.focus_handle.clone();
1697 IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1698 .icon_size(IconSize::Small)
1699 .on_click(cx.listener(|_, _, window, cx| {
1700 window.dispatch_action(InlineAssist::default().boxed_clone(), cx);
1701 }))
1702 .tooltip(move |_window, cx| {
1703 Tooltip::for_action_in("Inline Assist", &InlineAssist::default(), &focus_handle, cx)
1704 })
1705 }
1706}
1707
1708#[cfg(test)]
1709mod tests {
1710 use std::num::NonZero;
1711
1712 use super::*;
1713 use gpui::{TestAppContext, UpdateGlobal as _};
1714 use pretty_assertions::assert_eq;
1715 use project::FakeFs;
1716 use settings::SettingsStore;
1717 use workspace::MultiWorkspace;
1718
1719 #[test]
1720 fn test_prepare_empty_task() {
1721 let input = SpawnInTerminal::default();
1722 let shell = Shell::System;
1723
1724 let result = prepare_task_for_spawn(&input, &shell, false);
1725
1726 let expected_shell = util::get_system_shell();
1727 assert_eq!(result.env, HashMap::default());
1728 assert_eq!(result.cwd, None);
1729 assert_eq!(result.shell, Shell::System);
1730 assert_eq!(
1731 result.command,
1732 Some(expected_shell.clone()),
1733 "Empty tasks should spawn a -i shell"
1734 );
1735 assert_eq!(result.args, Vec::<String>::new());
1736 assert_eq!(
1737 result.command_label, expected_shell,
1738 "We show the shell launch for empty commands"
1739 );
1740 }
1741
1742 #[gpui::test]
1743 async fn test_bypass_max_tabs_limit(cx: &mut TestAppContext) {
1744 cx.executor().allow_parking();
1745 init_test(cx);
1746
1747 let fs = FakeFs::new(cx.executor());
1748 let project = Project::test(fs, [], cx).await;
1749 let window_handle =
1750 cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
1751
1752 let terminal_panel = window_handle
1753 .update(cx, |multi_workspace, window, cx| {
1754 multi_workspace.workspace().update(cx, |workspace, cx| {
1755 cx.new(|cx| TerminalPanel::new(workspace, window, cx))
1756 })
1757 })
1758 .unwrap();
1759
1760 set_max_tabs(cx, Some(3));
1761
1762 for _ in 0..5 {
1763 let task = window_handle
1764 .update(cx, |_, window, cx| {
1765 terminal_panel.update(cx, |panel, cx| {
1766 panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1767 })
1768 })
1769 .unwrap();
1770 task.await.unwrap();
1771 }
1772
1773 cx.run_until_parked();
1774
1775 let item_count =
1776 terminal_panel.read_with(cx, |panel, cx| panel.active_pane.read(cx).items_len());
1777
1778 assert_eq!(
1779 item_count, 5,
1780 "Terminal panel should bypass max_tabs limit and have all 5 terminals"
1781 );
1782 }
1783
1784 #[cfg(unix)]
1785 #[test]
1786 fn test_prepare_script_like_task() {
1787 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();
1788 let expected_cwd = PathBuf::from("/some/work");
1789
1790 let input = SpawnInTerminal {
1791 command: Some(user_command.clone()),
1792 cwd: Some(expected_cwd.clone()),
1793 ..SpawnInTerminal::default()
1794 };
1795 let shell = Shell::System;
1796
1797 let result = prepare_task_for_spawn(&input, &shell, false);
1798
1799 let system_shell = util::get_system_shell();
1800 assert_eq!(result.env, HashMap::default());
1801 assert_eq!(result.cwd, Some(expected_cwd));
1802 assert_eq!(result.shell, Shell::System);
1803 assert_eq!(result.command, Some(system_shell.clone()));
1804 assert_eq!(
1805 result.args,
1806 vec!["-i".to_string(), "-c".to_string(), user_command.clone()],
1807 "User command should have been moved into the arguments, as we're spawning a new -i shell",
1808 );
1809 assert_eq!(
1810 result.command_label,
1811 format!(
1812 "{system_shell} {interactive}-c '{user_command}'",
1813 interactive = if cfg!(windows) { "" } else { "-i " }
1814 ),
1815 "We want to show to the user the entire command spawned"
1816 );
1817 }
1818
1819 #[gpui::test]
1820 async fn renders_error_if_default_shell_fails(cx: &mut TestAppContext) {
1821 cx.executor().allow_parking();
1822 init_test(cx);
1823
1824 cx.update(|cx| {
1825 SettingsStore::update_global(cx, |store, cx| {
1826 store.update_user_settings(cx, |settings| {
1827 settings.terminal.get_or_insert_default().project.shell =
1828 Some(settings::Shell::Program("__nonexistent_shell__".to_owned()));
1829 });
1830 });
1831 });
1832
1833 let fs = FakeFs::new(cx.executor());
1834 let project = Project::test(fs, [], cx).await;
1835 let window_handle =
1836 cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
1837
1838 let terminal_panel = window_handle
1839 .update(cx, |multi_workspace, window, cx| {
1840 multi_workspace.workspace().update(cx, |workspace, cx| {
1841 cx.new(|cx| TerminalPanel::new(workspace, window, cx))
1842 })
1843 })
1844 .unwrap();
1845
1846 window_handle
1847 .update(cx, |_, window, cx| {
1848 terminal_panel.update(cx, |terminal_panel, cx| {
1849 terminal_panel.add_terminal_shell(None, RevealStrategy::Always, window, cx)
1850 })
1851 })
1852 .unwrap()
1853 .await
1854 .unwrap_err();
1855
1856 window_handle
1857 .update(cx, |_, _, cx| {
1858 terminal_panel.update(cx, |terminal_panel, cx| {
1859 assert!(
1860 terminal_panel
1861 .active_pane
1862 .read(cx)
1863 .items()
1864 .any(|item| item.downcast::<FailedToSpawnTerminal>().is_some()),
1865 "should spawn `FailedToSpawnTerminal` pane"
1866 );
1867 })
1868 })
1869 .unwrap();
1870 }
1871
1872 #[gpui::test]
1873 async fn test_local_terminal_in_local_project(cx: &mut TestAppContext) {
1874 cx.executor().allow_parking();
1875 init_test(cx);
1876
1877 let fs = FakeFs::new(cx.executor());
1878 let project = Project::test(fs, [], cx).await;
1879 let window_handle =
1880 cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
1881
1882 let terminal_panel = window_handle
1883 .update(cx, |multi_workspace, window, cx| {
1884 multi_workspace.workspace().update(cx, |workspace, cx| {
1885 cx.new(|cx| TerminalPanel::new(workspace, window, cx))
1886 })
1887 })
1888 .unwrap();
1889
1890 let result = window_handle
1891 .update(cx, |_, window, cx| {
1892 terminal_panel.update(cx, |terminal_panel, cx| {
1893 terminal_panel.add_local_terminal_shell(RevealStrategy::Always, window, cx)
1894 })
1895 })
1896 .unwrap()
1897 .await;
1898
1899 assert!(
1900 result.is_ok(),
1901 "local terminal should successfully create in local project"
1902 );
1903 }
1904
1905 fn set_max_tabs(cx: &mut TestAppContext, value: Option<usize>) {
1906 cx.update_global(|store: &mut SettingsStore, cx| {
1907 store.update_user_settings(cx, |settings| {
1908 settings.workspace.max_tabs = value.map(|v| NonZero::new(v).unwrap())
1909 });
1910 });
1911 }
1912
1913 pub fn init_test(cx: &mut TestAppContext) {
1914 cx.update(|cx| {
1915 let store = SettingsStore::test(cx);
1916 cx.set_global(store);
1917 theme::init(theme::LoadThemes::JustBase, cx);
1918 editor::init(cx);
1919 crate::init(cx);
1920 });
1921 }
1922}