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