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