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, NewTerminal, Pane, PaneGroup, SplitDirection, SplitDown, SplitLeft,
33 SplitRight, SplitUp, SwapPaneDown, SwapPaneLeft, SwapPaneRight, SwapPaneUp, ToggleZoom,
34 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.as_ref().and_then(|terminal_view| {
453 let terminal = terminal_view.read(cx).terminal().read(cx);
454 terminal
455 .working_directory()
456 .or_else(|| default_working_directory(workspace, cx))
457 });
458 let is_zoomed = active_pane.read(cx).is_zoomed();
459 cx.spawn_in(window, async move |panel, cx| {
460 let terminal = project
461 .update(cx, |project, cx| match terminal_view {
462 Some(view) => Task::ready(project.clone_terminal(
463 &view.read(cx).terminal.clone(),
464 cx,
465 || working_directory,
466 )),
467 None => project.create_terminal_shell(working_directory, cx),
468 })
469 .ok()?
470 .await
471 .log_err()?;
472
473 panel
474 .update_in(cx, move |terminal_panel, window, cx| {
475 let terminal_view = Box::new(cx.new(|cx| {
476 TerminalView::new(
477 terminal.clone(),
478 weak_workspace.clone(),
479 database_id,
480 project.downgrade(),
481 window,
482 cx,
483 )
484 }));
485 let pane = new_terminal_pane(weak_workspace, project, is_zoomed, window, cx);
486 terminal_panel.apply_tab_bar_buttons(&pane, cx);
487 pane.update(cx, |pane, cx| {
488 pane.add_item(terminal_view, true, true, None, window, cx);
489 });
490 Some(pane)
491 })
492 .ok()
493 .flatten()
494 })
495 }
496
497 pub fn open_terminal(
498 workspace: &mut Workspace,
499 action: &workspace::OpenTerminal,
500 window: &mut Window,
501 cx: &mut Context<Workspace>,
502 ) {
503 let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
504 return;
505 };
506
507 terminal_panel
508 .update(cx, |panel, cx| {
509 panel.add_terminal_shell(
510 Some(action.working_directory.clone()),
511 RevealStrategy::Always,
512 window,
513 cx,
514 )
515 })
516 .detach_and_log_err(cx);
517 }
518
519 pub fn spawn_task(
520 &mut self,
521 task: &SpawnInTerminal,
522 window: &mut Window,
523 cx: &mut Context<Self>,
524 ) -> Task<Result<WeakEntity<Terminal>>> {
525 let remote_client = self
526 .workspace
527 .update(cx, |workspace, cx| {
528 let project = workspace.project().read(cx);
529 if project.is_via_collab() {
530 Err(anyhow!("cannot spawn tasks as a guest"))
531 } else {
532 Ok(project.remote_client())
533 }
534 })
535 .flatten();
536
537 let remote_client = match remote_client {
538 Ok(remote_client) => remote_client,
539 Err(e) => return Task::ready(Err(e)),
540 };
541
542 let remote_shell = remote_client
543 .as_ref()
544 .and_then(|remote_client| remote_client.read(cx).shell());
545
546 let shell = if let Some(remote_shell) = remote_shell
547 && task.shell == Shell::System
548 {
549 Shell::Program(remote_shell)
550 } else {
551 task.shell.clone()
552 };
553
554 let builder = ShellBuilder::new(&shell);
555 let command_label = builder.command_label(task.command.as_deref().unwrap_or(""));
556 let (command, args) = builder.build(task.command.clone(), &task.args);
557
558 let task = SpawnInTerminal {
559 command_label,
560 command: Some(command),
561 args,
562 ..task.clone()
563 };
564
565 if task.allow_concurrent_runs && task.use_new_terminal {
566 return self.spawn_in_new_terminal(task, window, cx);
567 }
568
569 let mut terminals_for_task = self.terminals_for_task(&task.full_label, cx);
570 let Some(existing) = terminals_for_task.pop() else {
571 return self.spawn_in_new_terminal(task, window, cx);
572 };
573
574 let (existing_item_index, task_pane, existing_terminal) = existing;
575 if task.allow_concurrent_runs {
576 return self.replace_terminal(
577 task,
578 task_pane,
579 existing_item_index,
580 existing_terminal,
581 window,
582 cx,
583 );
584 }
585
586 let (tx, rx) = oneshot::channel();
587
588 self.deferred_tasks.insert(
589 task.id.clone(),
590 cx.spawn_in(window, async move |terminal_panel, cx| {
591 wait_for_terminals_tasks(terminals_for_task, cx).await;
592 let task = terminal_panel.update_in(cx, |terminal_panel, window, cx| {
593 if task.use_new_terminal {
594 terminal_panel.spawn_in_new_terminal(task, window, cx)
595 } else {
596 terminal_panel.replace_terminal(
597 task,
598 task_pane,
599 existing_item_index,
600 existing_terminal,
601 window,
602 cx,
603 )
604 }
605 });
606 if let Ok(task) = task {
607 tx.send(task.await).ok();
608 }
609 }),
610 );
611
612 cx.spawn(async move |_, _| rx.await?)
613 }
614
615 fn spawn_in_new_terminal(
616 &mut self,
617 spawn_task: SpawnInTerminal,
618 window: &mut Window,
619 cx: &mut Context<Self>,
620 ) -> Task<Result<WeakEntity<Terminal>>> {
621 let reveal = spawn_task.reveal;
622 let reveal_target = spawn_task.reveal_target;
623 match reveal_target {
624 RevealTarget::Center => self
625 .workspace
626 .update(cx, |workspace, cx| {
627 Self::add_center_terminal(workspace, window, cx, |project, cx| {
628 project.create_terminal_task(spawn_task, cx)
629 })
630 })
631 .unwrap_or_else(|e| Task::ready(Err(e))),
632 RevealTarget::Dock => self.add_terminal_task(spawn_task, reveal, window, cx),
633 }
634 }
635
636 /// Create a new Terminal in the current working directory or the user's home directory
637 fn new_terminal(
638 workspace: &mut Workspace,
639 _: &workspace::NewTerminal,
640 window: &mut Window,
641 cx: &mut Context<Workspace>,
642 ) {
643 let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
644 return;
645 };
646
647 terminal_panel
648 .update(cx, |this, cx| {
649 this.add_terminal_shell(
650 default_working_directory(workspace, cx),
651 RevealStrategy::Always,
652 window,
653 cx,
654 )
655 })
656 .detach_and_log_err(cx);
657 }
658
659 fn terminals_for_task(
660 &self,
661 label: &str,
662 cx: &mut App,
663 ) -> Vec<(usize, Entity<Pane>, Entity<TerminalView>)> {
664 let Some(workspace) = self.workspace.upgrade() else {
665 return Vec::new();
666 };
667
668 let pane_terminal_views = |pane: Entity<Pane>| {
669 pane.read(cx)
670 .items()
671 .enumerate()
672 .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
673 .filter_map(|(index, terminal_view)| {
674 let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
675 if &task_state.spawned_task.full_label == label {
676 Some((index, terminal_view))
677 } else {
678 None
679 }
680 })
681 .map(move |(index, terminal_view)| (index, pane.clone(), terminal_view))
682 };
683
684 self.center
685 .panes()
686 .into_iter()
687 .cloned()
688 .flat_map(pane_terminal_views)
689 .chain(
690 workspace
691 .read(cx)
692 .panes()
693 .iter()
694 .cloned()
695 .flat_map(pane_terminal_views),
696 )
697 .sorted_by_key(|(_, _, terminal_view)| terminal_view.entity_id())
698 .collect()
699 }
700
701 fn activate_terminal_view(
702 &self,
703 pane: &Entity<Pane>,
704 item_index: usize,
705 focus: bool,
706 window: &mut Window,
707 cx: &mut App,
708 ) {
709 pane.update(cx, |pane, cx| {
710 pane.activate_item(item_index, true, focus, window, cx)
711 })
712 }
713
714 pub fn add_center_terminal(
715 workspace: &mut Workspace,
716 window: &mut Window,
717 cx: &mut Context<Workspace>,
718 create_terminal: impl FnOnce(
719 &mut Project,
720 &mut Context<Project>,
721 ) -> Task<Result<Entity<Terminal>>>
722 + 'static,
723 ) -> Task<Result<WeakEntity<Terminal>>> {
724 if !is_enabled_in_workspace(workspace, cx) {
725 return Task::ready(Err(anyhow!(
726 "terminal not yet supported for remote projects"
727 )));
728 }
729 let project = workspace.project().downgrade();
730 cx.spawn_in(window, async move |workspace, cx| {
731 let terminal = project.update(cx, create_terminal)?.await?;
732
733 workspace.update_in(cx, |workspace, window, cx| {
734 let terminal_view = cx.new(|cx| {
735 TerminalView::new(
736 terminal.clone(),
737 workspace.weak_handle(),
738 workspace.database_id(),
739 workspace.project().downgrade(),
740 window,
741 cx,
742 )
743 });
744 workspace.add_item_to_active_pane(Box::new(terminal_view), None, true, window, cx);
745 })?;
746 Ok(terminal.downgrade())
747 })
748 }
749
750 pub fn add_terminal_task(
751 &mut self,
752 task: SpawnInTerminal,
753 reveal_strategy: RevealStrategy,
754 window: &mut Window,
755 cx: &mut Context<Self>,
756 ) -> Task<Result<WeakEntity<Terminal>>> {
757 let workspace = self.workspace.clone();
758 cx.spawn_in(window, async move |terminal_panel, cx| {
759 if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
760 anyhow::bail!("terminal not yet supported for remote projects");
761 }
762 let pane = terminal_panel.update(cx, |terminal_panel, _| {
763 terminal_panel.pending_terminals_to_add += 1;
764 terminal_panel.active_pane.clone()
765 })?;
766 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
767 let terminal = project
768 .update(cx, |project, cx| project.create_terminal_task(task, cx))?
769 .await?;
770 let result = workspace.update_in(cx, |workspace, window, cx| {
771 let terminal_view = Box::new(cx.new(|cx| {
772 TerminalView::new(
773 terminal.clone(),
774 workspace.weak_handle(),
775 workspace.database_id(),
776 workspace.project().downgrade(),
777 window,
778 cx,
779 )
780 }));
781
782 match reveal_strategy {
783 RevealStrategy::Always => {
784 workspace.focus_panel::<Self>(window, cx);
785 }
786 RevealStrategy::NoFocus => {
787 workspace.open_panel::<Self>(window, cx);
788 }
789 RevealStrategy::Never => {}
790 }
791
792 pane.update(cx, |pane, cx| {
793 let focus = pane.has_focus(window, cx)
794 || matches!(reveal_strategy, RevealStrategy::Always);
795 pane.add_item(terminal_view, true, focus, None, window, cx);
796 });
797
798 Ok(terminal.downgrade())
799 })?;
800 terminal_panel.update(cx, |terminal_panel, cx| {
801 terminal_panel.pending_terminals_to_add =
802 terminal_panel.pending_terminals_to_add.saturating_sub(1);
803 terminal_panel.serialize(cx)
804 })?;
805 result
806 })
807 }
808
809 fn add_terminal_shell(
810 &mut self,
811 cwd: Option<PathBuf>,
812 reveal_strategy: RevealStrategy,
813 window: &mut Window,
814 cx: &mut Context<Self>,
815 ) -> Task<Result<WeakEntity<Terminal>>> {
816 let workspace = self.workspace.clone();
817 cx.spawn_in(window, async move |terminal_panel, cx| {
818 if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
819 anyhow::bail!("terminal not yet supported for collaborative projects");
820 }
821 let pane = terminal_panel.update(cx, |terminal_panel, _| {
822 terminal_panel.pending_terminals_to_add += 1;
823 terminal_panel.active_pane.clone()
824 })?;
825 let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
826 let terminal = project
827 .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))?
828 .await?;
829 let result = workspace.update_in(cx, |workspace, window, cx| {
830 let terminal_view = Box::new(cx.new(|cx| {
831 TerminalView::new(
832 terminal.clone(),
833 workspace.weak_handle(),
834 workspace.database_id(),
835 workspace.project().downgrade(),
836 window,
837 cx,
838 )
839 }));
840
841 match reveal_strategy {
842 RevealStrategy::Always => {
843 workspace.focus_panel::<Self>(window, cx);
844 }
845 RevealStrategy::NoFocus => {
846 workspace.open_panel::<Self>(window, cx);
847 }
848 RevealStrategy::Never => {}
849 }
850
851 pane.update(cx, |pane, cx| {
852 let focus = pane.has_focus(window, cx)
853 || matches!(reveal_strategy, RevealStrategy::Always);
854 pane.add_item(terminal_view, true, focus, None, window, cx);
855 });
856
857 Ok(terminal.downgrade())
858 })?;
859 terminal_panel.update(cx, |terminal_panel, cx| {
860 terminal_panel.pending_terminals_to_add =
861 terminal_panel.pending_terminals_to_add.saturating_sub(1);
862 terminal_panel.serialize(cx)
863 })?;
864 result
865 })
866 }
867
868 fn serialize(&mut self, cx: &mut Context<Self>) {
869 let height = self.height;
870 let width = self.width;
871 let Some(serialization_key) = self
872 .workspace
873 .read_with(cx, |workspace, _| {
874 TerminalPanel::serialization_key(workspace)
875 })
876 .ok()
877 .flatten()
878 else {
879 return;
880 };
881 self.pending_serialization = cx.spawn(async move |terminal_panel, cx| {
882 cx.background_executor()
883 .timer(Duration::from_millis(50))
884 .await;
885 let terminal_panel = terminal_panel.upgrade()?;
886 let items = terminal_panel
887 .update(cx, |terminal_panel, cx| {
888 SerializedItems::WithSplits(serialize_pane_group(
889 &terminal_panel.center,
890 &terminal_panel.active_pane,
891 cx,
892 ))
893 })
894 .ok()?;
895 cx.background_spawn(
896 async move {
897 KEY_VALUE_STORE
898 .write_kvp(
899 serialization_key,
900 serde_json::to_string(&SerializedTerminalPanel {
901 items,
902 active_item_id: None,
903 height,
904 width,
905 })?,
906 )
907 .await?;
908 anyhow::Ok(())
909 }
910 .log_err(),
911 )
912 .await;
913 Some(())
914 });
915 }
916
917 fn replace_terminal(
918 &self,
919 spawn_task: SpawnInTerminal,
920 task_pane: Entity<Pane>,
921 terminal_item_index: usize,
922 terminal_to_replace: Entity<TerminalView>,
923 window: &mut Window,
924 cx: &mut Context<Self>,
925 ) -> Task<Result<WeakEntity<Terminal>>> {
926 let reveal = spawn_task.reveal;
927 let reveal_target = spawn_task.reveal_target;
928 let task_workspace = self.workspace.clone();
929 cx.spawn_in(window, async move |terminal_panel, cx| {
930 let project = terminal_panel.update(cx, |this, cx| {
931 this.workspace
932 .update(cx, |workspace, _| workspace.project().clone())
933 })??;
934 let new_terminal = project
935 .update(cx, |project, cx| {
936 project.create_terminal_task(spawn_task, cx)
937 })?
938 .await?;
939 terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| {
940 terminal_to_replace.set_terminal(new_terminal.clone(), window, cx);
941 })?;
942
943 match reveal {
944 RevealStrategy::Always => match reveal_target {
945 RevealTarget::Center => {
946 task_workspace.update_in(cx, |workspace, window, cx| {
947 let did_activate = workspace.activate_item(
948 &terminal_to_replace,
949 true,
950 true,
951 window,
952 cx,
953 );
954
955 anyhow::ensure!(did_activate, "Failed to retrieve terminal pane");
956
957 anyhow::Ok(())
958 })??;
959 }
960 RevealTarget::Dock => {
961 terminal_panel.update_in(cx, |terminal_panel, window, cx| {
962 terminal_panel.activate_terminal_view(
963 &task_pane,
964 terminal_item_index,
965 true,
966 window,
967 cx,
968 )
969 })?;
970
971 cx.spawn(async move |cx| {
972 task_workspace
973 .update_in(cx, |workspace, window, cx| {
974 workspace.focus_panel::<Self>(window, cx)
975 })
976 .ok()
977 })
978 .detach();
979 }
980 },
981 RevealStrategy::NoFocus => match reveal_target {
982 RevealTarget::Center => {
983 task_workspace.update_in(cx, |workspace, window, cx| {
984 workspace.active_pane().focus_handle(cx).focus(window);
985 })?;
986 }
987 RevealTarget::Dock => {
988 terminal_panel.update_in(cx, |terminal_panel, window, cx| {
989 terminal_panel.activate_terminal_view(
990 &task_pane,
991 terminal_item_index,
992 false,
993 window,
994 cx,
995 )
996 })?;
997
998 cx.spawn(async move |cx| {
999 task_workspace
1000 .update_in(cx, |workspace, window, cx| {
1001 workspace.open_panel::<Self>(window, cx)
1002 })
1003 .ok()
1004 })
1005 .detach();
1006 }
1007 },
1008 RevealStrategy::Never => {}
1009 }
1010
1011 Ok(new_terminal.downgrade())
1012 })
1013 }
1014
1015 fn has_no_terminals(&self, cx: &App) -> bool {
1016 self.active_pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
1017 }
1018
1019 pub fn assistant_enabled(&self) -> bool {
1020 self.assistant_enabled
1021 }
1022
1023 fn is_enabled(&self, cx: &App) -> bool {
1024 self.workspace
1025 .upgrade()
1026 .is_some_and(|workspace| is_enabled_in_workspace(workspace.read(cx), cx))
1027 }
1028
1029 fn activate_pane_in_direction(
1030 &mut self,
1031 direction: SplitDirection,
1032 window: &mut Window,
1033 cx: &mut Context<Self>,
1034 ) {
1035 if let Some(pane) = self
1036 .center
1037 .find_pane_in_direction(&self.active_pane, direction, cx)
1038 {
1039 window.focus(&pane.focus_handle(cx));
1040 } else {
1041 self.workspace
1042 .update(cx, |workspace, cx| {
1043 workspace.activate_pane_in_direction(direction, window, cx)
1044 })
1045 .ok();
1046 }
1047 }
1048
1049 fn swap_pane_in_direction(&mut self, direction: SplitDirection, cx: &mut Context<Self>) {
1050 if let Some(to) = self
1051 .center
1052 .find_pane_in_direction(&self.active_pane, direction, cx)
1053 .cloned()
1054 {
1055 self.center.swap(&self.active_pane, &to);
1056 cx.notify();
1057 }
1058 }
1059}
1060
1061fn is_enabled_in_workspace(workspace: &Workspace, cx: &App) -> bool {
1062 workspace.project().read(cx).supports_terminal(cx)
1063}
1064
1065pub fn new_terminal_pane(
1066 workspace: WeakEntity<Workspace>,
1067 project: Entity<Project>,
1068 zoomed: bool,
1069 window: &mut Window,
1070 cx: &mut Context<TerminalPanel>,
1071) -> Entity<Pane> {
1072 let is_local = project.read(cx).is_local();
1073 let terminal_panel = cx.entity();
1074 let pane = cx.new(|cx| {
1075 let mut pane = Pane::new(
1076 workspace.clone(),
1077 project.clone(),
1078 Default::default(),
1079 None,
1080 NewTerminal.boxed_clone(),
1081 window,
1082 cx,
1083 );
1084 pane.set_zoomed(zoomed, cx);
1085 pane.set_can_navigate(false, cx);
1086 pane.display_nav_history_buttons(None);
1087 pane.set_should_display_tab_bar(|_, _| true);
1088 pane.set_zoom_out_on_close(false);
1089
1090 let split_closure_terminal_panel = terminal_panel.downgrade();
1091 pane.set_can_split(Some(Arc::new(move |pane, dragged_item, _window, cx| {
1092 if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
1093 let is_current_pane = tab.pane == cx.entity();
1094 let Some(can_drag_away) = split_closure_terminal_panel
1095 .read_with(cx, |terminal_panel, _| {
1096 let current_panes = terminal_panel.center.panes();
1097 !current_panes.contains(&&tab.pane)
1098 || current_panes.len() > 1
1099 || (!is_current_pane || pane.items_len() > 1)
1100 })
1101 .ok()
1102 else {
1103 return false;
1104 };
1105 if can_drag_away {
1106 let item = if is_current_pane {
1107 pane.item_for_index(tab.ix)
1108 } else {
1109 tab.pane.read(cx).item_for_index(tab.ix)
1110 };
1111 if let Some(item) = item {
1112 return item.downcast::<TerminalView>().is_some();
1113 }
1114 }
1115 }
1116 false
1117 })));
1118
1119 let buffer_search_bar = cx.new(|cx| {
1120 search::BufferSearchBar::new(Some(project.read(cx).languages().clone()), window, cx)
1121 });
1122 let breadcrumbs = cx.new(|_| Breadcrumbs::new());
1123 pane.toolbar().update(cx, |toolbar, cx| {
1124 toolbar.add_item(buffer_search_bar, window, cx);
1125 toolbar.add_item(breadcrumbs, window, cx);
1126 });
1127
1128 let drop_closure_project = project.downgrade();
1129 let drop_closure_terminal_panel = terminal_panel.downgrade();
1130 pane.set_custom_drop_handle(cx, move |pane, dropped_item, window, cx| {
1131 let Some(project) = drop_closure_project.upgrade() else {
1132 return ControlFlow::Break(());
1133 };
1134 if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
1135 let this_pane = cx.entity();
1136 let item = if tab.pane == this_pane {
1137 pane.item_for_index(tab.ix)
1138 } else {
1139 tab.pane.read(cx).item_for_index(tab.ix)
1140 };
1141 if let Some(item) = item {
1142 if item.downcast::<TerminalView>().is_some() {
1143 let source = tab.pane.clone();
1144 let item_id_to_move = item.item_id();
1145
1146 let Ok(new_split_pane) = pane
1147 .drag_split_direction()
1148 .map(|split_direction| {
1149 drop_closure_terminal_panel.update(cx, |terminal_panel, cx| {
1150 let is_zoomed = if terminal_panel.active_pane == this_pane {
1151 pane.is_zoomed()
1152 } else {
1153 terminal_panel.active_pane.read(cx).is_zoomed()
1154 };
1155 let new_pane = new_terminal_pane(
1156 workspace.clone(),
1157 project.clone(),
1158 is_zoomed,
1159 window,
1160 cx,
1161 );
1162 terminal_panel.apply_tab_bar_buttons(&new_pane, cx);
1163 terminal_panel.center.split(
1164 &this_pane,
1165 &new_pane,
1166 split_direction,
1167 )?;
1168 anyhow::Ok(new_pane)
1169 })
1170 })
1171 .transpose()
1172 else {
1173 return ControlFlow::Break(());
1174 };
1175
1176 match new_split_pane.transpose() {
1177 // Source pane may be the one currently updated, so defer the move.
1178 Ok(Some(new_pane)) => cx
1179 .spawn_in(window, async move |_, cx| {
1180 cx.update(|window, cx| {
1181 move_item(
1182 &source,
1183 &new_pane,
1184 item_id_to_move,
1185 new_pane.read(cx).active_item_index(),
1186 true,
1187 window,
1188 cx,
1189 );
1190 })
1191 .ok();
1192 })
1193 .detach(),
1194 // If we drop into existing pane or current pane,
1195 // regular pane drop handler will take care of it,
1196 // using the right tab index for the operation.
1197 Ok(None) => return ControlFlow::Continue(()),
1198 err @ Err(_) => {
1199 err.log_err();
1200 return ControlFlow::Break(());
1201 }
1202 };
1203 } else if let Some(project_path) = item.project_path(cx)
1204 && let Some(entry_path) = project.read(cx).absolute_path(&project_path, cx)
1205 {
1206 add_paths_to_terminal(pane, &[entry_path], window, cx);
1207 }
1208 }
1209 } else if let Some(selection) = dropped_item.downcast_ref::<DraggedSelection>() {
1210 let project = project.read(cx);
1211 let paths_to_add = selection
1212 .items()
1213 .map(|selected_entry| selected_entry.entry_id)
1214 .filter_map(|entry_id| project.path_for_entry(entry_id, cx))
1215 .filter_map(|project_path| project.absolute_path(&project_path, cx))
1216 .collect::<Vec<_>>();
1217 if !paths_to_add.is_empty() {
1218 add_paths_to_terminal(pane, &paths_to_add, window, cx);
1219 }
1220 } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
1221 if let Some(entry_path) = project
1222 .read(cx)
1223 .path_for_entry(entry_id, cx)
1224 .and_then(|project_path| project.read(cx).absolute_path(&project_path, cx))
1225 {
1226 add_paths_to_terminal(pane, &[entry_path], window, cx);
1227 }
1228 } else if is_local && let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
1229 add_paths_to_terminal(pane, paths.paths(), window, cx);
1230 }
1231
1232 ControlFlow::Break(())
1233 });
1234
1235 pane
1236 });
1237
1238 cx.subscribe_in(&pane, window, TerminalPanel::handle_pane_event)
1239 .detach();
1240 cx.observe(&pane, |_, _, cx| cx.notify()).detach();
1241
1242 pane
1243}
1244
1245async fn wait_for_terminals_tasks(
1246 terminals_for_task: Vec<(usize, Entity<Pane>, Entity<TerminalView>)>,
1247 cx: &mut AsyncApp,
1248) {
1249 let pending_tasks = terminals_for_task.iter().filter_map(|(_, _, terminal)| {
1250 terminal
1251 .update(cx, |terminal_view, cx| {
1252 terminal_view
1253 .terminal()
1254 .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1255 })
1256 .ok()
1257 });
1258 join_all(pending_tasks).await;
1259}
1260
1261fn add_paths_to_terminal(
1262 pane: &mut Pane,
1263 paths: &[PathBuf],
1264 window: &mut Window,
1265 cx: &mut Context<Pane>,
1266) {
1267 if let Some(terminal_view) = pane
1268 .active_item()
1269 .and_then(|item| item.downcast::<TerminalView>())
1270 {
1271 window.focus(&terminal_view.focus_handle(cx));
1272 let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
1273 new_text.push(' ');
1274 terminal_view.update(cx, |terminal_view, cx| {
1275 terminal_view.terminal().update(cx, |terminal, _| {
1276 terminal.paste(&new_text);
1277 });
1278 });
1279 }
1280}
1281
1282impl EventEmitter<PanelEvent> for TerminalPanel {}
1283
1284impl Render for TerminalPanel {
1285 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1286 let mut registrar = DivRegistrar::new(
1287 |panel, _, cx| {
1288 panel
1289 .active_pane
1290 .read(cx)
1291 .toolbar()
1292 .read(cx)
1293 .item_of_type::<BufferSearchBar>()
1294 },
1295 cx,
1296 );
1297 BufferSearchBar::register(&mut registrar);
1298 let registrar = registrar.into_div();
1299 self.workspace
1300 .update(cx, |workspace, cx| {
1301 registrar.size_full().child(self.center.render(
1302 workspace.zoomed_item(),
1303 &workspace::PaneRenderContext {
1304 follower_states: &HashMap::default(),
1305 active_call: workspace.active_call(),
1306 active_pane: &self.active_pane,
1307 app_state: workspace.app_state(),
1308 project: workspace.project(),
1309 workspace: &workspace.weak_handle(),
1310 },
1311 window,
1312 cx,
1313 ))
1314 })
1315 .ok()
1316 .map(|div| {
1317 div.on_action({
1318 cx.listener(|terminal_panel, _: &ActivatePaneLeft, window, cx| {
1319 terminal_panel.activate_pane_in_direction(SplitDirection::Left, window, cx);
1320 })
1321 })
1322 .on_action({
1323 cx.listener(|terminal_panel, _: &ActivatePaneRight, window, cx| {
1324 terminal_panel.activate_pane_in_direction(
1325 SplitDirection::Right,
1326 window,
1327 cx,
1328 );
1329 })
1330 })
1331 .on_action({
1332 cx.listener(|terminal_panel, _: &ActivatePaneUp, window, cx| {
1333 terminal_panel.activate_pane_in_direction(SplitDirection::Up, window, cx);
1334 })
1335 })
1336 .on_action({
1337 cx.listener(|terminal_panel, _: &ActivatePaneDown, window, cx| {
1338 terminal_panel.activate_pane_in_direction(SplitDirection::Down, window, cx);
1339 })
1340 })
1341 .on_action(
1342 cx.listener(|terminal_panel, _action: &ActivateNextPane, window, cx| {
1343 let panes = terminal_panel.center.panes();
1344 if let Some(ix) = panes
1345 .iter()
1346 .position(|pane| **pane == terminal_panel.active_pane)
1347 {
1348 let next_ix = (ix + 1) % panes.len();
1349 window.focus(&panes[next_ix].focus_handle(cx));
1350 }
1351 }),
1352 )
1353 .on_action(cx.listener(
1354 |terminal_panel, _action: &ActivatePreviousPane, window, cx| {
1355 let panes = terminal_panel.center.panes();
1356 if let Some(ix) = panes
1357 .iter()
1358 .position(|pane| **pane == terminal_panel.active_pane)
1359 {
1360 let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
1361 window.focus(&panes[prev_ix].focus_handle(cx));
1362 }
1363 },
1364 ))
1365 .on_action(
1366 cx.listener(|terminal_panel, action: &ActivatePane, window, cx| {
1367 let panes = terminal_panel.center.panes();
1368 if let Some(&pane) = panes.get(action.0) {
1369 window.focus(&pane.read(cx).focus_handle(cx));
1370 } else {
1371 let future =
1372 terminal_panel.new_pane_with_cloned_active_terminal(window, cx);
1373 cx.spawn_in(window, async move |terminal_panel, cx| {
1374 if let Some(new_pane) = future.await {
1375 _ = terminal_panel.update_in(
1376 cx,
1377 |terminal_panel, window, cx| {
1378 terminal_panel
1379 .center
1380 .split(
1381 &terminal_panel.active_pane,
1382 &new_pane,
1383 SplitDirection::Right,
1384 )
1385 .log_err();
1386 let new_pane = new_pane.read(cx);
1387 window.focus(&new_pane.focus_handle(cx));
1388 },
1389 );
1390 }
1391 })
1392 .detach();
1393 }
1394 }),
1395 )
1396 .on_action(cx.listener(|terminal_panel, _: &SwapPaneLeft, _, cx| {
1397 terminal_panel.swap_pane_in_direction(SplitDirection::Left, cx);
1398 }))
1399 .on_action(cx.listener(|terminal_panel, _: &SwapPaneRight, _, cx| {
1400 terminal_panel.swap_pane_in_direction(SplitDirection::Right, cx);
1401 }))
1402 .on_action(cx.listener(|terminal_panel, _: &SwapPaneUp, _, cx| {
1403 terminal_panel.swap_pane_in_direction(SplitDirection::Up, cx);
1404 }))
1405 .on_action(cx.listener(|terminal_panel, _: &SwapPaneDown, _, cx| {
1406 terminal_panel.swap_pane_in_direction(SplitDirection::Down, cx);
1407 }))
1408 .on_action(
1409 cx.listener(|terminal_panel, action: &MoveItemToPane, window, cx| {
1410 let Some(&target_pane) =
1411 terminal_panel.center.panes().get(action.destination)
1412 else {
1413 return;
1414 };
1415 move_active_item(
1416 &terminal_panel.active_pane,
1417 target_pane,
1418 action.focus,
1419 true,
1420 window,
1421 cx,
1422 );
1423 }),
1424 )
1425 .on_action(cx.listener(
1426 |terminal_panel, action: &MoveItemToPaneInDirection, window, cx| {
1427 let source_pane = &terminal_panel.active_pane;
1428 if let Some(destination_pane) = terminal_panel
1429 .center
1430 .find_pane_in_direction(source_pane, action.direction, cx)
1431 {
1432 move_active_item(
1433 source_pane,
1434 destination_pane,
1435 action.focus,
1436 true,
1437 window,
1438 cx,
1439 );
1440 };
1441 },
1442 ))
1443 })
1444 .unwrap_or_else(|| div())
1445 }
1446}
1447
1448impl Focusable for TerminalPanel {
1449 fn focus_handle(&self, cx: &App) -> FocusHandle {
1450 self.active_pane.focus_handle(cx)
1451 }
1452}
1453
1454impl Panel for TerminalPanel {
1455 fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1456 match TerminalSettings::get_global(cx).dock {
1457 TerminalDockPosition::Left => DockPosition::Left,
1458 TerminalDockPosition::Bottom => DockPosition::Bottom,
1459 TerminalDockPosition::Right => DockPosition::Right,
1460 }
1461 }
1462
1463 fn position_is_valid(&self, _: DockPosition) -> bool {
1464 true
1465 }
1466
1467 fn set_position(
1468 &mut self,
1469 position: DockPosition,
1470 _window: &mut Window,
1471 cx: &mut Context<Self>,
1472 ) {
1473 settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1474 let dock = match position {
1475 DockPosition::Left => TerminalDockPosition::Left,
1476 DockPosition::Bottom => TerminalDockPosition::Bottom,
1477 DockPosition::Right => TerminalDockPosition::Right,
1478 };
1479 settings.terminal.get_or_insert_default().dock = Some(dock);
1480 });
1481 }
1482
1483 fn size(&self, window: &Window, cx: &App) -> Pixels {
1484 let settings = TerminalSettings::get_global(cx);
1485 match self.position(window, cx) {
1486 DockPosition::Left | DockPosition::Right => {
1487 self.width.unwrap_or(settings.default_width)
1488 }
1489 DockPosition::Bottom => self.height.unwrap_or(settings.default_height),
1490 }
1491 }
1492
1493 fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
1494 match self.position(window, cx) {
1495 DockPosition::Left | DockPosition::Right => self.width = size,
1496 DockPosition::Bottom => self.height = size,
1497 }
1498 cx.notify();
1499 cx.defer_in(window, |this, _, cx| {
1500 this.serialize(cx);
1501 })
1502 }
1503
1504 fn is_zoomed(&self, _window: &Window, cx: &App) -> bool {
1505 self.active_pane.read(cx).is_zoomed()
1506 }
1507
1508 fn set_zoomed(&mut self, zoomed: bool, _: &mut Window, cx: &mut Context<Self>) {
1509 for pane in self.center.panes() {
1510 pane.update(cx, |pane, cx| {
1511 pane.set_zoomed(zoomed, cx);
1512 })
1513 }
1514 cx.notify();
1515 }
1516
1517 fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
1518 let old_active = self.active;
1519 self.active = active;
1520 if !active || old_active == active || !self.has_no_terminals(cx) {
1521 return;
1522 }
1523 cx.defer_in(window, |this, window, cx| {
1524 let Ok(kind) = this
1525 .workspace
1526 .update(cx, |workspace, cx| default_working_directory(workspace, cx))
1527 else {
1528 return;
1529 };
1530
1531 this.add_terminal_shell(kind, RevealStrategy::Always, window, cx)
1532 .detach_and_log_err(cx)
1533 })
1534 }
1535
1536 fn icon_label(&self, _window: &Window, cx: &App) -> Option<String> {
1537 let count = self
1538 .center
1539 .panes()
1540 .into_iter()
1541 .map(|pane| pane.read(cx).items_len())
1542 .sum::<usize>();
1543 if count == 0 {
1544 None
1545 } else {
1546 Some(count.to_string())
1547 }
1548 }
1549
1550 fn persistent_name() -> &'static str {
1551 "TerminalPanel"
1552 }
1553
1554 fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1555 if (self.is_enabled(cx) || !self.has_no_terminals(cx))
1556 && TerminalSettings::get_global(cx).button
1557 {
1558 Some(IconName::TerminalAlt)
1559 } else {
1560 None
1561 }
1562 }
1563
1564 fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
1565 Some("Terminal Panel")
1566 }
1567
1568 fn toggle_action(&self) -> Box<dyn gpui::Action> {
1569 Box::new(ToggleFocus)
1570 }
1571
1572 fn pane(&self) -> Option<Entity<Pane>> {
1573 Some(self.active_pane.clone())
1574 }
1575
1576 fn activation_priority(&self) -> u32 {
1577 1
1578 }
1579}
1580
1581struct TerminalProvider(Entity<TerminalPanel>);
1582
1583impl workspace::TerminalProvider for TerminalProvider {
1584 fn spawn(
1585 &self,
1586 task: SpawnInTerminal,
1587 window: &mut Window,
1588 cx: &mut App,
1589 ) -> Task<Option<Result<ExitStatus>>> {
1590 let terminal_panel = self.0.clone();
1591 window.spawn(cx, async move |cx| {
1592 let terminal = terminal_panel
1593 .update_in(cx, |terminal_panel, window, cx| {
1594 terminal_panel.spawn_task(&task, window, cx)
1595 })
1596 .ok()?
1597 .await;
1598 match terminal {
1599 Ok(terminal) => {
1600 let exit_status = terminal
1601 .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
1602 .ok()?
1603 .await?;
1604 Some(Ok(exit_status))
1605 }
1606 Err(e) => Some(Err(e)),
1607 }
1608 })
1609 }
1610}
1611
1612struct InlineAssistTabBarButton {
1613 focus_handle: FocusHandle,
1614}
1615
1616impl Render for InlineAssistTabBarButton {
1617 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1618 let focus_handle = self.focus_handle.clone();
1619 IconButton::new("terminal_inline_assistant", IconName::ZedAssistant)
1620 .icon_size(IconSize::Small)
1621 .on_click(cx.listener(|_, _, window, cx| {
1622 window.dispatch_action(InlineAssist::default().boxed_clone(), cx);
1623 }))
1624 .tooltip(move |window, cx| {
1625 Tooltip::for_action_in(
1626 "Inline Assist",
1627 &InlineAssist::default(),
1628 &focus_handle,
1629 window,
1630 cx,
1631 )
1632 })
1633 }
1634}
1635
1636#[cfg(test)]
1637mod tests {
1638 use super::*;
1639 use gpui::TestAppContext;
1640 use pretty_assertions::assert_eq;
1641 use project::FakeFs;
1642 use settings::SettingsStore;
1643
1644 #[gpui::test]
1645 async fn test_spawn_an_empty_task(cx: &mut TestAppContext) {
1646 init_test(cx);
1647
1648 let fs = FakeFs::new(cx.executor());
1649 let project = Project::test(fs, [], cx).await;
1650 let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1651
1652 let (window_handle, terminal_panel) = workspace
1653 .update(cx, |workspace, window, cx| {
1654 let window_handle = window.window_handle();
1655 let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1656 (window_handle, terminal_panel)
1657 })
1658 .unwrap();
1659
1660 let task = window_handle
1661 .update(cx, |_, window, cx| {
1662 terminal_panel.update(cx, |terminal_panel, cx| {
1663 terminal_panel.spawn_task(&SpawnInTerminal::default(), window, cx)
1664 })
1665 })
1666 .unwrap();
1667
1668 let terminal = task.await.unwrap();
1669 let expected_shell = util::get_system_shell();
1670 terminal
1671 .update(cx, |terminal, _| {
1672 let task_metadata = terminal
1673 .task()
1674 .expect("When spawning a task, should have the task metadata")
1675 .spawned_task
1676 .clone();
1677 assert_eq!(task_metadata.env, HashMap::default());
1678 assert_eq!(task_metadata.cwd, None);
1679 assert_eq!(task_metadata.shell, task::Shell::System);
1680 assert_eq!(
1681 task_metadata.command,
1682 Some(expected_shell.clone()),
1683 "Empty tasks should spawn a -i shell"
1684 );
1685 assert_eq!(task_metadata.args, Vec::<String>::new());
1686 assert_eq!(
1687 task_metadata.command_label, expected_shell,
1688 "We show the shell launch for empty commands"
1689 );
1690 })
1691 .unwrap();
1692 }
1693
1694 // A complex Unix command won't be properly parsed by the Windows terminal hence omit the test there.
1695 #[cfg(unix)]
1696 #[gpui::test]
1697 async fn test_spawn_script_like_task(cx: &mut TestAppContext) {
1698 init_test(cx);
1699
1700 let fs = FakeFs::new(cx.executor());
1701 let project = Project::test(fs, [], cx).await;
1702 let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
1703
1704 let (window_handle, terminal_panel) = workspace
1705 .update(cx, |workspace, window, cx| {
1706 let window_handle = window.window_handle();
1707 let terminal_panel = cx.new(|cx| TerminalPanel::new(workspace, window, cx));
1708 (window_handle, terminal_panel)
1709 })
1710 .unwrap();
1711
1712 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();
1713
1714 let expected_cwd = PathBuf::from("/some/work");
1715 let task = window_handle
1716 .update(cx, |_, window, cx| {
1717 terminal_panel.update(cx, |terminal_panel, cx| {
1718 terminal_panel.spawn_task(
1719 &SpawnInTerminal {
1720 command: Some(user_command.clone()),
1721 cwd: Some(expected_cwd.clone()),
1722 ..SpawnInTerminal::default()
1723 },
1724 window,
1725 cx,
1726 )
1727 })
1728 })
1729 .unwrap();
1730
1731 let terminal = task.await.unwrap();
1732 let shell = util::get_system_shell();
1733 terminal
1734 .update(cx, |terminal, _| {
1735 let task_metadata = terminal
1736 .task()
1737 .expect("When spawning a task, should have the task metadata")
1738 .spawned_task
1739 .clone();
1740 assert_eq!(task_metadata.env, HashMap::default());
1741 assert_eq!(task_metadata.cwd, Some(expected_cwd));
1742 assert_eq!(task_metadata.shell, task::Shell::System);
1743 assert_eq!(task_metadata.command, Some(shell.clone()));
1744 assert_eq!(
1745 task_metadata.args,
1746 vec!["-i".to_string(), "-c".to_string(), user_command.clone(),],
1747 "Use command should have been moved into the arguments, as we're spawning a new -i shell",
1748 );
1749 assert_eq!(
1750 task_metadata.command_label,
1751 format!("{shell} {interactive}-c '{user_command}'", interactive = if cfg!(windows) {""} else {"-i "}),
1752 "We want to show to the user the entire command spawned");
1753 })
1754 .unwrap();
1755 }
1756
1757 pub fn init_test(cx: &mut TestAppContext) {
1758 cx.update(|cx| {
1759 let store = SettingsStore::test(cx);
1760 cx.set_global(store);
1761 theme::init(theme::LoadThemes::JustBase, cx);
1762 client::init_settings(cx);
1763 language::init(cx);
1764 Project::init_settings(cx);
1765 workspace::init_settings(cx);
1766 editor::init(cx);
1767 crate::init(cx);
1768 });
1769 }
1770}