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