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