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