1use std::{ops::ControlFlow, path::PathBuf, sync::Arc};
2
3use crate::TerminalView;
4use collections::{HashMap, HashSet};
5use db::kvp::KEY_VALUE_STORE;
6use futures::future::join_all;
7use gpui::{
8 actions, Action, AppContext, AsyncWindowContext, DismissEvent, Entity, EventEmitter,
9 ExternalPaths, FocusHandle, FocusableView, IntoElement, Model, ParentElement, Pixels, Render,
10 Styled, Subscription, Task, View, ViewContext, VisualContext, WeakView, WindowContext,
11};
12use itertools::Itertools;
13use project::{Fs, ProjectEntryId};
14use search::{buffer_search::DivRegistrar, BufferSearchBar};
15use serde::{Deserialize, Serialize};
16use settings::Settings;
17use task::{RevealStrategy, Shell, SpawnInTerminal, TaskId, TerminalWorkDir};
18use terminal::{
19 terminal_settings::{TerminalDockPosition, TerminalSettings},
20 Terminal,
21};
22use ui::{
23 h_flex, ButtonCommon, Clickable, ContextMenu, FluentBuilder, IconButton, IconSize, Selectable,
24 Tooltip,
25};
26use util::{ResultExt, TryFutureExt};
27use workspace::{
28 dock::{DockPosition, Panel, PanelEvent},
29 item::SerializableItem,
30 pane,
31 ui::IconName,
32 DraggedTab, ItemId, NewTerminal, Pane, ToggleZoom, Workspace,
33};
34
35use anyhow::Result;
36
37const TERMINAL_PANEL_KEY: &str = "TerminalPanel";
38
39actions!(terminal_panel, [ToggleFocus]);
40
41pub fn init(cx: &mut AppContext) {
42 cx.observe_new_views(
43 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
44 workspace.register_action(TerminalPanel::new_terminal);
45 workspace.register_action(TerminalPanel::open_terminal);
46 workspace.register_action(|workspace, _: &ToggleFocus, cx| {
47 if workspace
48 .panel::<TerminalPanel>(cx)
49 .as_ref()
50 .is_some_and(|panel| panel.read(cx).enabled)
51 {
52 workspace.toggle_panel_focus::<TerminalPanel>(cx);
53 }
54 });
55 },
56 )
57 .detach();
58}
59
60pub struct TerminalPanel {
61 pane: View<Pane>,
62 fs: Arc<dyn Fs>,
63 workspace: WeakView<Workspace>,
64 width: Option<Pixels>,
65 height: Option<Pixels>,
66 pending_serialization: Task<Option<()>>,
67 pending_terminals_to_add: usize,
68 _subscriptions: Vec<Subscription>,
69 deferred_tasks: HashMap<TaskId, Task<()>>,
70 enabled: bool,
71}
72
73impl TerminalPanel {
74 fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
75 let pane = cx.new_view(|cx| {
76 let mut pane = Pane::new(
77 workspace.weak_handle(),
78 workspace.project().clone(),
79 Default::default(),
80 None,
81 NewTerminal.boxed_clone(),
82 cx,
83 );
84 pane.set_can_split(false, cx);
85 pane.set_can_navigate(false, cx);
86 pane.display_nav_history_buttons(None);
87 pane.set_should_display_tab_bar(|_| true);
88 pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
89 h_flex()
90 .gap_2()
91 .child(
92 IconButton::new("plus", IconName::Plus)
93 .icon_size(IconSize::Small)
94 .on_click(cx.listener(|pane, _, cx| {
95 let focus_handle = pane.focus_handle(cx);
96 let menu = ContextMenu::build(cx, |menu, _| {
97 menu.action(
98 "New Terminal",
99 workspace::NewTerminal.boxed_clone(),
100 )
101 .entry(
102 "Spawn task",
103 Some(tasks_ui::Spawn::modal().boxed_clone()),
104 move |cx| {
105 // We want the focus to go back to terminal panel once task modal is dismissed,
106 // hence we focus that first. Otherwise, we'd end up without a focused element, as
107 // context menu will be gone the moment we spawn the modal.
108 cx.focus(&focus_handle);
109 cx.dispatch_action(
110 tasks_ui::Spawn::modal().boxed_clone(),
111 );
112 },
113 )
114 });
115 cx.subscribe(&menu, |pane, _, _: &DismissEvent, _| {
116 pane.new_item_menu = None;
117 })
118 .detach();
119 pane.new_item_menu = Some(menu);
120 }))
121 .tooltip(|cx| Tooltip::text("New...", cx)),
122 )
123 .when_some(pane.new_item_menu.as_ref(), |el, new_item_menu| {
124 el.child(Pane::render_menu_overlay(new_item_menu))
125 })
126 .child({
127 let zoomed = pane.is_zoomed();
128 IconButton::new("toggle_zoom", IconName::Maximize)
129 .icon_size(IconSize::Small)
130 .selected(zoomed)
131 .selected_icon(IconName::Minimize)
132 .on_click(cx.listener(|pane, _, cx| {
133 pane.toggle_zoom(&workspace::ToggleZoom, cx);
134 }))
135 .tooltip(move |cx| {
136 Tooltip::for_action(
137 if zoomed { "Zoom Out" } else { "Zoom In" },
138 &ToggleZoom,
139 cx,
140 )
141 })
142 })
143 .into_any_element()
144 });
145
146 let workspace = workspace.weak_handle();
147 pane.set_custom_drop_handle(cx, move |pane, dropped_item, cx| {
148 if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
149 let item = if &tab.pane == cx.view() {
150 pane.item_for_index(tab.ix)
151 } else {
152 tab.pane.read(cx).item_for_index(tab.ix)
153 };
154 if let Some(item) = item {
155 if item.downcast::<TerminalView>().is_some() {
156 return ControlFlow::Continue(());
157 } else if let Some(project_path) = item.project_path(cx) {
158 if let Some(entry_path) = workspace
159 .update(cx, |workspace, cx| {
160 workspace
161 .project()
162 .read(cx)
163 .absolute_path(&project_path, cx)
164 })
165 .log_err()
166 .flatten()
167 {
168 add_paths_to_terminal(pane, &[entry_path], cx);
169 }
170 }
171 }
172 } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
173 if let Some(entry_path) = workspace
174 .update(cx, |workspace, cx| {
175 let project = workspace.project().read(cx);
176 project
177 .path_for_entry(entry_id, cx)
178 .and_then(|project_path| project.absolute_path(&project_path, cx))
179 })
180 .log_err()
181 .flatten()
182 {
183 add_paths_to_terminal(pane, &[entry_path], cx);
184 }
185 } else if let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
186 add_paths_to_terminal(pane, paths.paths(), cx);
187 }
188
189 ControlFlow::Break(())
190 });
191 let buffer_search_bar = cx.new_view(search::BufferSearchBar::new);
192 pane.toolbar()
193 .update(cx, |toolbar, cx| toolbar.add_item(buffer_search_bar, cx));
194 pane
195 });
196 let subscriptions = vec![
197 cx.observe(&pane, |_, _, cx| cx.notify()),
198 cx.subscribe(&pane, Self::handle_pane_event),
199 ];
200 let project = workspace.project().read(cx);
201 let enabled = project.is_local() || project.supports_remote_terminal(cx);
202 let this = Self {
203 pane,
204 fs: workspace.app_state().fs.clone(),
205 workspace: workspace.weak_handle(),
206 pending_serialization: Task::ready(None),
207 width: None,
208 height: None,
209 pending_terminals_to_add: 0,
210 deferred_tasks: HashMap::default(),
211 _subscriptions: subscriptions,
212 enabled,
213 };
214 this
215 }
216
217 pub async fn load(
218 workspace: WeakView<Workspace>,
219 mut cx: AsyncWindowContext,
220 ) -> Result<View<Self>> {
221 let serialized_panel = cx
222 .background_executor()
223 .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })
224 .await
225 .log_err()
226 .flatten()
227 .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
228 .transpose()
229 .log_err()
230 .flatten();
231
232 let (panel, pane, items) = workspace.update(&mut cx, |workspace, cx| {
233 let panel = cx.new_view(|cx| TerminalPanel::new(workspace, cx));
234 let items = if let Some((serialized_panel, database_id)) =
235 serialized_panel.as_ref().zip(workspace.database_id())
236 {
237 panel.update(cx, |panel, cx| {
238 cx.notify();
239 panel.height = serialized_panel.height.map(|h| h.round());
240 panel.width = serialized_panel.width.map(|w| w.round());
241 panel.pane.update(cx, |_, cx| {
242 serialized_panel
243 .items
244 .iter()
245 .map(|item_id| {
246 TerminalView::deserialize(
247 workspace.project().clone(),
248 workspace.weak_handle(),
249 database_id,
250 *item_id,
251 cx,
252 )
253 })
254 .collect::<Vec<_>>()
255 })
256 })
257 } else {
258 Vec::new()
259 };
260 let pane = panel.read(cx).pane.clone();
261 (panel, pane, items)
262 })?;
263
264 if let Some(workspace) = workspace.upgrade() {
265 panel
266 .update(&mut cx, |panel, cx| {
267 panel._subscriptions.push(cx.subscribe(
268 &workspace,
269 |terminal_panel, _, e, cx| {
270 if let workspace::Event::SpawnTask(spawn_in_terminal) = e {
271 terminal_panel.spawn_task(spawn_in_terminal, cx);
272 };
273 },
274 ))
275 })
276 .ok();
277 }
278
279 let pane = pane.downgrade();
280 let items = futures::future::join_all(items).await;
281 let mut alive_item_ids = Vec::new();
282 pane.update(&mut cx, |pane, cx| {
283 let active_item_id = serialized_panel
284 .as_ref()
285 .and_then(|panel| panel.active_item_id);
286 let mut active_ix = None;
287 for item in items {
288 if let Some(item) = item.log_err() {
289 let item_id = item.entity_id().as_u64();
290 pane.add_item(Box::new(item), false, false, None, cx);
291 alive_item_ids.push(item_id as ItemId);
292 if Some(item_id) == active_item_id {
293 active_ix = Some(pane.items_len() - 1);
294 }
295 }
296 }
297
298 if let Some(active_ix) = active_ix {
299 pane.activate_item(active_ix, false, false, cx)
300 }
301 })?;
302
303 // Since panels/docks are loaded outside from the workspace, we cleanup here, instead of through the workspace.
304 if let Some(workspace) = workspace.upgrade() {
305 let cleanup_task = workspace.update(&mut cx, |workspace, cx| {
306 workspace
307 .database_id()
308 .map(|workspace_id| TerminalView::cleanup(workspace_id, alive_item_ids, cx))
309 })?;
310 if let Some(task) = cleanup_task {
311 task.await.log_err();
312 }
313 }
314
315 Ok(panel)
316 }
317
318 fn handle_pane_event(
319 &mut self,
320 _pane: View<Pane>,
321 event: &pane::Event,
322 cx: &mut ViewContext<Self>,
323 ) {
324 match event {
325 pane::Event::ActivateItem { .. } => self.serialize(cx),
326 pane::Event::RemoveItem { .. } => self.serialize(cx),
327 pane::Event::Remove => cx.emit(PanelEvent::Close),
328 pane::Event::ZoomIn => cx.emit(PanelEvent::ZoomIn),
329 pane::Event::ZoomOut => cx.emit(PanelEvent::ZoomOut),
330
331 pane::Event::AddItem { item } => {
332 if let Some(workspace) = self.workspace.upgrade() {
333 let pane = self.pane.clone();
334 workspace.update(cx, |workspace, cx| item.added_to_pane(workspace, pane, cx))
335 }
336 }
337
338 _ => {}
339 }
340 }
341
342 pub fn open_terminal(
343 workspace: &mut Workspace,
344 action: &workspace::OpenTerminal,
345 cx: &mut ViewContext<Workspace>,
346 ) {
347 let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
348 return;
349 };
350
351 let terminal_work_dir = workspace
352 .project()
353 .read(cx)
354 .terminal_work_dir_for(Some(&action.working_directory), cx);
355
356 terminal_panel
357 .update(cx, |panel, cx| {
358 panel.add_terminal(terminal_work_dir, None, RevealStrategy::Always, cx)
359 })
360 .detach_and_log_err(cx);
361 }
362
363 fn spawn_task(&mut self, spawn_in_terminal: &SpawnInTerminal, cx: &mut ViewContext<Self>) {
364 let mut spawn_task = spawn_in_terminal.clone();
365 // Set up shell args unconditionally, as tasks are always spawned inside of a shell.
366 let Some((shell, mut user_args)) = (match spawn_in_terminal.shell.clone() {
367 Shell::System => retrieve_system_shell().map(|shell| (shell, Vec::new())),
368 Shell::Program(shell) => Some((shell, Vec::new())),
369 Shell::WithArguments { program, args } => Some((program, args)),
370 }) else {
371 return;
372 };
373 #[cfg(target_os = "windows")]
374 let windows_shell_type = to_windows_shell_type(&shell);
375
376 #[cfg(not(target_os = "windows"))]
377 {
378 spawn_task.command_label = format!("{shell} -i -c `{}`", spawn_task.command_label);
379 }
380 #[cfg(target_os = "windows")]
381 {
382 use crate::terminal_panel::WindowsShellType;
383
384 match windows_shell_type {
385 WindowsShellType::Powershell => {
386 spawn_task.command_label = format!("{shell} -C `{}`", spawn_task.command_label)
387 }
388 WindowsShellType::Cmd => {
389 spawn_task.command_label = format!("{shell} /C `{}`", spawn_task.command_label)
390 }
391 WindowsShellType::Other => {
392 spawn_task.command_label =
393 format!("{shell} -i -c `{}`", spawn_task.command_label)
394 }
395 }
396 }
397
398 let task_command = std::mem::replace(&mut spawn_task.command, shell);
399 let task_args = std::mem::take(&mut spawn_task.args);
400 let combined_command = task_args
401 .into_iter()
402 .fold(task_command, |mut command, arg| {
403 command.push(' ');
404 #[cfg(not(target_os = "windows"))]
405 command.push_str(&arg);
406 #[cfg(target_os = "windows")]
407 command.push_str(&to_windows_shell_variable(windows_shell_type, arg));
408 command
409 });
410
411 #[cfg(not(target_os = "windows"))]
412 user_args.extend(["-i".to_owned(), "-c".to_owned(), combined_command]);
413 #[cfg(target_os = "windows")]
414 {
415 use crate::terminal_panel::WindowsShellType;
416
417 match windows_shell_type {
418 WindowsShellType::Powershell => {
419 user_args.extend(["-C".to_owned(), combined_command])
420 }
421 WindowsShellType::Cmd => user_args.extend(["/C".to_owned(), combined_command]),
422 WindowsShellType::Other => {
423 user_args.extend(["-i".to_owned(), "-c".to_owned(), combined_command])
424 }
425 }
426 }
427 spawn_task.args = user_args;
428 let spawn_task = spawn_task;
429
430 let allow_concurrent_runs = spawn_in_terminal.allow_concurrent_runs;
431 let use_new_terminal = spawn_in_terminal.use_new_terminal;
432
433 if allow_concurrent_runs && use_new_terminal {
434 self.spawn_in_new_terminal(spawn_task, cx)
435 .detach_and_log_err(cx);
436 return;
437 }
438
439 let terminals_for_task = self.terminals_for_task(&spawn_in_terminal.full_label, cx);
440 if terminals_for_task.is_empty() {
441 self.spawn_in_new_terminal(spawn_task, cx)
442 .detach_and_log_err(cx);
443 return;
444 }
445 let (existing_item_index, existing_terminal) = terminals_for_task
446 .last()
447 .expect("covered no terminals case above")
448 .clone();
449 if allow_concurrent_runs {
450 debug_assert!(
451 !use_new_terminal,
452 "Should have handled 'allow_concurrent_runs && use_new_terminal' case above"
453 );
454 self.replace_terminal(spawn_task, existing_item_index, existing_terminal, cx);
455 } else {
456 self.deferred_tasks.insert(
457 spawn_in_terminal.id.clone(),
458 cx.spawn(|terminal_panel, mut cx| async move {
459 wait_for_terminals_tasks(terminals_for_task, &mut cx).await;
460 terminal_panel
461 .update(&mut cx, |terminal_panel, cx| {
462 if use_new_terminal {
463 terminal_panel
464 .spawn_in_new_terminal(spawn_task, cx)
465 .detach_and_log_err(cx);
466 } else {
467 terminal_panel.replace_terminal(
468 spawn_task,
469 existing_item_index,
470 existing_terminal,
471 cx,
472 );
473 }
474 })
475 .ok();
476 }),
477 );
478 }
479 }
480
481 pub fn spawn_in_new_terminal(
482 &mut self,
483 spawn_task: SpawnInTerminal,
484 cx: &mut ViewContext<Self>,
485 ) -> Task<Result<Model<Terminal>>> {
486 let reveal = spawn_task.reveal;
487 self.add_terminal(spawn_task.cwd.clone(), Some(spawn_task), reveal, cx)
488 }
489
490 /// Create a new Terminal in the current working directory or the user's home directory
491 fn new_terminal(
492 workspace: &mut Workspace,
493 _: &workspace::NewTerminal,
494 cx: &mut ViewContext<Workspace>,
495 ) {
496 let Some(terminal_panel) = workspace.panel::<Self>(cx) else {
497 return;
498 };
499
500 terminal_panel
501 .update(cx, |this, cx| {
502 this.add_terminal(None, None, RevealStrategy::Always, cx)
503 })
504 .detach_and_log_err(cx);
505 }
506
507 fn terminals_for_task(
508 &self,
509 label: &str,
510 cx: &mut AppContext,
511 ) -> Vec<(usize, View<TerminalView>)> {
512 self.pane
513 .read(cx)
514 .items()
515 .enumerate()
516 .filter_map(|(index, item)| Some((index, item.act_as::<TerminalView>(cx)?)))
517 .filter_map(|(index, terminal_view)| {
518 let task_state = terminal_view.read(cx).terminal().read(cx).task()?;
519 if &task_state.full_label == label {
520 Some((index, terminal_view))
521 } else {
522 None
523 }
524 })
525 .collect()
526 }
527
528 fn activate_terminal_view(&self, item_index: usize, cx: &mut WindowContext) {
529 self.pane.update(cx, |pane, cx| {
530 pane.activate_item(item_index, true, true, cx)
531 })
532 }
533
534 fn add_terminal(
535 &mut self,
536 working_directory: Option<TerminalWorkDir>,
537 spawn_task: Option<SpawnInTerminal>,
538 reveal_strategy: RevealStrategy,
539 cx: &mut ViewContext<Self>,
540 ) -> Task<Result<Model<Terminal>>> {
541 if !self.enabled {
542 if spawn_task.is_none()
543 || !matches!(
544 spawn_task.as_ref().unwrap().cwd,
545 Some(TerminalWorkDir::Ssh { .. })
546 )
547 {
548 return Task::ready(Err(anyhow::anyhow!(
549 "terminal not yet supported for remote projects"
550 )));
551 }
552 }
553
554 let workspace = self.workspace.clone();
555 self.pending_terminals_to_add += 1;
556
557 cx.spawn(|terminal_panel, mut cx| async move {
558 let pane = terminal_panel.update(&mut cx, |this, _| this.pane.clone())?;
559 let result = workspace.update(&mut cx, |workspace, cx| {
560 let working_directory = if let Some(working_directory) = working_directory {
561 Some(working_directory)
562 } else {
563 let working_directory_strategy =
564 TerminalSettings::get_global(cx).working_directory.clone();
565 crate::get_working_directory(workspace, cx, working_directory_strategy)
566 };
567
568 let window = cx.window_handle();
569 let terminal = workspace.project().update(cx, |project, cx| {
570 project.create_terminal(working_directory, spawn_task, window, cx)
571 })?;
572 let terminal_view = Box::new(cx.new_view(|cx| {
573 TerminalView::new(
574 terminal.clone(),
575 workspace.weak_handle(),
576 workspace.database_id(),
577 cx,
578 )
579 }));
580 pane.update(cx, |pane, cx| {
581 let focus = pane.has_focus(cx);
582 pane.add_item(terminal_view, true, focus, None, cx);
583 });
584
585 if reveal_strategy == RevealStrategy::Always {
586 workspace.focus_panel::<Self>(cx);
587 }
588 Ok(terminal)
589 })?;
590 terminal_panel.update(&mut cx, |this, cx| {
591 this.pending_terminals_to_add = this.pending_terminals_to_add.saturating_sub(1);
592 this.serialize(cx)
593 })?;
594 result
595 })
596 }
597
598 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
599 let mut items_to_serialize = HashSet::default();
600 let items = self
601 .pane
602 .read(cx)
603 .items()
604 .filter_map(|item| {
605 let terminal_view = item.act_as::<TerminalView>(cx)?;
606 if terminal_view.read(cx).terminal().read(cx).task().is_some() {
607 None
608 } else {
609 let id = item.item_id().as_u64();
610 items_to_serialize.insert(id);
611 Some(id)
612 }
613 })
614 .collect::<Vec<_>>();
615 let active_item_id = self
616 .pane
617 .read(cx)
618 .active_item()
619 .map(|item| item.item_id().as_u64())
620 .filter(|active_id| items_to_serialize.contains(active_id));
621 let height = self.height;
622 let width = self.width;
623 self.pending_serialization = cx.background_executor().spawn(
624 async move {
625 KEY_VALUE_STORE
626 .write_kvp(
627 TERMINAL_PANEL_KEY.into(),
628 serde_json::to_string(&SerializedTerminalPanel {
629 items,
630 active_item_id,
631 height,
632 width,
633 })?,
634 )
635 .await?;
636 anyhow::Ok(())
637 }
638 .log_err(),
639 );
640 }
641
642 fn replace_terminal(
643 &self,
644 spawn_task: SpawnInTerminal,
645 terminal_item_index: usize,
646 terminal_to_replace: View<TerminalView>,
647 cx: &mut ViewContext<'_, Self>,
648 ) -> Option<()> {
649 let project = self
650 .workspace
651 .update(cx, |workspace, _| workspace.project().clone())
652 .ok()?;
653
654 let reveal = spawn_task.reveal;
655 let window = cx.window_handle();
656 let new_terminal = project.update(cx, |project, cx| {
657 project
658 .create_terminal(spawn_task.cwd.clone(), Some(spawn_task), window, cx)
659 .log_err()
660 })?;
661 terminal_to_replace.update(cx, |terminal_to_replace, cx| {
662 terminal_to_replace.set_terminal(new_terminal, cx);
663 });
664
665 match reveal {
666 RevealStrategy::Always => {
667 self.activate_terminal_view(terminal_item_index, cx);
668 let task_workspace = self.workspace.clone();
669 cx.spawn(|_, mut cx| async move {
670 task_workspace
671 .update(&mut cx, |workspace, cx| workspace.focus_panel::<Self>(cx))
672 .ok()
673 })
674 .detach();
675 }
676 RevealStrategy::Never => {}
677 }
678
679 Some(())
680 }
681
682 pub fn pane(&self) -> &View<Pane> {
683 &self.pane
684 }
685
686 fn has_no_terminals(&self, cx: &WindowContext) -> bool {
687 self.pane.read(cx).items_len() == 0 && self.pending_terminals_to_add == 0
688 }
689}
690
691async fn wait_for_terminals_tasks(
692 terminals_for_task: Vec<(usize, View<TerminalView>)>,
693 cx: &mut AsyncWindowContext,
694) {
695 let pending_tasks = terminals_for_task.iter().filter_map(|(_, terminal)| {
696 terminal
697 .update(cx, |terminal_view, cx| {
698 terminal_view
699 .terminal()
700 .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))
701 })
702 .ok()
703 });
704 let _: Vec<()> = join_all(pending_tasks).await;
705}
706
707fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
708 if let Some(terminal_view) = pane
709 .active_item()
710 .and_then(|item| item.downcast::<TerminalView>())
711 {
712 cx.focus_view(&terminal_view);
713 let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
714 new_text.push(' ');
715 terminal_view.update(cx, |terminal_view, cx| {
716 terminal_view.terminal().update(cx, |terminal, _| {
717 terminal.paste(&new_text);
718 });
719 });
720 }
721}
722
723impl EventEmitter<PanelEvent> for TerminalPanel {}
724
725impl Render for TerminalPanel {
726 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
727 let mut registrar = DivRegistrar::new(
728 |panel, cx| {
729 panel
730 .pane
731 .read(cx)
732 .toolbar()
733 .read(cx)
734 .item_of_type::<BufferSearchBar>()
735 },
736 cx,
737 );
738 BufferSearchBar::register(&mut registrar);
739 registrar.into_div().size_full().child(self.pane.clone())
740 }
741}
742
743impl FocusableView for TerminalPanel {
744 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
745 self.pane.focus_handle(cx)
746 }
747}
748
749impl Panel for TerminalPanel {
750 fn position(&self, cx: &WindowContext) -> DockPosition {
751 match TerminalSettings::get_global(cx).dock {
752 TerminalDockPosition::Left => DockPosition::Left,
753 TerminalDockPosition::Bottom => DockPosition::Bottom,
754 TerminalDockPosition::Right => DockPosition::Right,
755 }
756 }
757
758 fn position_is_valid(&self, _: DockPosition) -> bool {
759 true
760 }
761
762 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
763 settings::update_settings_file::<TerminalSettings>(
764 self.fs.clone(),
765 cx,
766 move |settings, _| {
767 let dock = match position {
768 DockPosition::Left => TerminalDockPosition::Left,
769 DockPosition::Bottom => TerminalDockPosition::Bottom,
770 DockPosition::Right => TerminalDockPosition::Right,
771 };
772 settings.dock = Some(dock);
773 },
774 );
775 }
776
777 fn size(&self, cx: &WindowContext) -> Pixels {
778 let settings = TerminalSettings::get_global(cx);
779 match self.position(cx) {
780 DockPosition::Left | DockPosition::Right => {
781 self.width.unwrap_or_else(|| settings.default_width)
782 }
783 DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
784 }
785 }
786
787 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
788 match self.position(cx) {
789 DockPosition::Left | DockPosition::Right => self.width = size,
790 DockPosition::Bottom => self.height = size,
791 }
792 self.serialize(cx);
793 cx.notify();
794 }
795
796 fn is_zoomed(&self, cx: &WindowContext) -> bool {
797 self.pane.read(cx).is_zoomed()
798 }
799
800 fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
801 self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
802 }
803
804 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
805 if active && self.has_no_terminals(cx) {
806 self.add_terminal(None, None, RevealStrategy::Never, cx)
807 .detach_and_log_err(cx)
808 }
809 }
810
811 fn icon_label(&self, cx: &WindowContext) -> Option<String> {
812 let count = self.pane.read(cx).items_len();
813 if count == 0 {
814 None
815 } else {
816 Some(count.to_string())
817 }
818 }
819
820 fn persistent_name() -> &'static str {
821 "TerminalPanel"
822 }
823
824 fn icon(&self, cx: &WindowContext) -> Option<IconName> {
825 if (self.enabled || !self.has_no_terminals(cx)) && TerminalSettings::get_global(cx).button {
826 Some(IconName::Terminal)
827 } else {
828 None
829 }
830 }
831
832 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
833 Some("Terminal Panel")
834 }
835
836 fn toggle_action(&self) -> Box<dyn gpui::Action> {
837 Box::new(ToggleFocus)
838 }
839}
840
841#[derive(Serialize, Deserialize)]
842struct SerializedTerminalPanel {
843 items: Vec<u64>,
844 active_item_id: Option<u64>,
845 width: Option<Pixels>,
846 height: Option<Pixels>,
847}
848
849fn retrieve_system_shell() -> Option<String> {
850 #[cfg(not(target_os = "windows"))]
851 {
852 use anyhow::Context;
853 use util::ResultExt;
854
855 return std::env::var("SHELL")
856 .context("Error finding SHELL in env.")
857 .log_err();
858 }
859 // `alacritty_terminal` uses this as default on Windows. See:
860 // https://github.com/alacritty/alacritty/blob/0d4ab7bca43213d96ddfe40048fc0f922543c6f8/alacritty_terminal/src/tty/windows/mod.rs#L130
861 #[cfg(target_os = "windows")]
862 return Some("powershell".to_owned());
863}
864
865#[cfg(target_os = "windows")]
866fn to_windows_shell_variable(shell_type: WindowsShellType, input: String) -> String {
867 match shell_type {
868 WindowsShellType::Powershell => to_powershell_variable(input),
869 WindowsShellType::Cmd => to_cmd_variable(input),
870 WindowsShellType::Other => input,
871 }
872}
873
874#[cfg(target_os = "windows")]
875fn to_windows_shell_type(shell: &str) -> WindowsShellType {
876 if shell == "powershell" || shell.ends_with("powershell.exe") {
877 WindowsShellType::Powershell
878 } else if shell == "cmd" || shell.ends_with("cmd.exe") {
879 WindowsShellType::Cmd
880 } else {
881 // Someother shell detected, the user might install and use a
882 // unix-like shell.
883 WindowsShellType::Other
884 }
885}
886
887/// Convert `${SOME_VAR}`, `$SOME_VAR` to `%SOME_VAR%`.
888#[inline]
889#[cfg(target_os = "windows")]
890fn to_cmd_variable(input: String) -> String {
891 if let Some(var_str) = input.strip_prefix("${") {
892 if var_str.find(':').is_none() {
893 // If the input starts with "${", remove the trailing "}"
894 format!("%{}%", &var_str[..var_str.len() - 1])
895 } else {
896 // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
897 // which will result in the task failing to run in such cases.
898 input
899 }
900 } else if let Some(var_str) = input.strip_prefix('$') {
901 // If the input starts with "$", directly append to "$env:"
902 format!("%{}%", var_str)
903 } else {
904 // If no prefix is found, return the input as is
905 input
906 }
907}
908
909/// Convert `${SOME_VAR}`, `$SOME_VAR` to `$env:SOME_VAR`.
910#[inline]
911#[cfg(target_os = "windows")]
912fn to_powershell_variable(input: String) -> String {
913 if let Some(var_str) = input.strip_prefix("${") {
914 if var_str.find(':').is_none() {
915 // If the input starts with "${", remove the trailing "}"
916 format!("$env:{}", &var_str[..var_str.len() - 1])
917 } else {
918 // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
919 // which will result in the task failing to run in such cases.
920 input
921 }
922 } else if let Some(var_str) = input.strip_prefix('$') {
923 // If the input starts with "$", directly append to "$env:"
924 format!("$env:{}", var_str)
925 } else {
926 // If no prefix is found, return the input as is
927 input
928 }
929}
930
931#[cfg(target_os = "windows")]
932#[derive(Debug, Clone, Copy, PartialEq, Eq)]
933enum WindowsShellType {
934 Powershell,
935 Cmd,
936 Other,
937}