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