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