1use std::{ops::ControlFlow, path::PathBuf, sync::Arc};
2
3use crate::TerminalView;
4use db::kvp::KEY_VALUE_STORE;
5use gpui::{
6 actions, AppContext, AsyncWindowContext, Entity, EventEmitter, ExternalPaths, FocusHandle,
7 FocusableView, IntoElement, ParentElement, Pixels, Render, Styled, Subscription, Task, View,
8 ViewContext, VisualContext, WeakView, WindowContext,
9};
10use itertools::Itertools;
11use project::{Fs, ProjectEntryId};
12use search::{buffer_search::DivRegistrar, BufferSearchBar};
13use serde::{Deserialize, Serialize};
14use settings::{Settings, SettingsStore};
15use terminal::terminal_settings::{TerminalDockPosition, TerminalSettings};
16use ui::{h_stack, ButtonCommon, Clickable, IconButton, IconSize, Selectable, Tooltip};
17use util::{ResultExt, TryFutureExt};
18use workspace::{
19 dock::{DockPosition, Panel, PanelEvent},
20 item::Item,
21 pane,
22 ui::Icon,
23 DraggedTab, Pane, Workspace,
24};
25
26use anyhow::Result;
27
28const TERMINAL_PANEL_KEY: &'static str = "TerminalPanel";
29
30actions!(terminal_panel, [ToggleFocus]);
31
32pub fn init(cx: &mut AppContext) {
33 cx.observe_new_views(
34 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
35 workspace.register_action(TerminalPanel::new_terminal);
36 workspace.register_action(TerminalPanel::open_terminal);
37 workspace.register_action(|workspace, _: &ToggleFocus, cx| {
38 workspace.toggle_panel_focus::<TerminalPanel>(cx);
39 });
40 },
41 )
42 .detach();
43}
44
45pub struct TerminalPanel {
46 pane: View<Pane>,
47 fs: Arc<dyn Fs>,
48 workspace: WeakView<Workspace>,
49 width: Option<Pixels>,
50 height: Option<Pixels>,
51 pending_serialization: Task<Option<()>>,
52 _subscriptions: Vec<Subscription>,
53}
54
55impl TerminalPanel {
56 fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
57 let terminal_panel = cx.view().downgrade();
58 let pane = cx.new_view(|cx| {
59 let mut pane = Pane::new(
60 workspace.weak_handle(),
61 workspace.project().clone(),
62 Default::default(),
63 None,
64 cx,
65 );
66 pane.set_can_split(false, cx);
67 pane.set_can_navigate(false, cx);
68 pane.display_nav_history_buttons(false);
69 pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
70 let terminal_panel = terminal_panel.clone();
71 h_stack()
72 .gap_2()
73 .child(
74 IconButton::new("plus", Icon::Plus)
75 .icon_size(IconSize::Small)
76 .on_click(move |_, cx| {
77 terminal_panel
78 .update(cx, |panel, cx| panel.add_terminal(None, cx))
79 .log_err();
80 })
81 .tooltip(|cx| Tooltip::text("New Terminal", cx)),
82 )
83 .child({
84 let zoomed = pane.is_zoomed();
85 IconButton::new("toggle_zoom", Icon::Maximize)
86 .icon_size(IconSize::Small)
87 .selected(zoomed)
88 .selected_icon(Icon::Minimize)
89 .on_click(cx.listener(|pane, _, cx| {
90 pane.toggle_zoom(&workspace::ToggleZoom, cx);
91 }))
92 .tooltip(move |cx| {
93 Tooltip::text(if zoomed { "Zoom Out" } else { "Zoom In" }, cx)
94 })
95 })
96 .into_any_element()
97 });
98
99 let workspace = workspace.weak_handle();
100 pane.set_custom_drop_handle(cx, move |pane, dropped_item, cx| {
101 if let Some(tab) = dropped_item.downcast_ref::<DraggedTab>() {
102 let item = if &tab.pane == cx.view() {
103 pane.item_for_index(tab.ix)
104 } else {
105 tab.pane.read(cx).item_for_index(tab.ix)
106 };
107 if let Some(item) = item {
108 if item.downcast::<TerminalView>().is_some() {
109 return ControlFlow::Continue(());
110 } else if let Some(project_path) = item.project_path(cx) {
111 if let Some(entry_path) = workspace
112 .update(cx, |workspace, cx| {
113 workspace
114 .project()
115 .read(cx)
116 .absolute_path(&project_path, cx)
117 })
118 .log_err()
119 .flatten()
120 {
121 add_paths_to_terminal(pane, &[entry_path], cx);
122 }
123 }
124 }
125 } else if let Some(&entry_id) = dropped_item.downcast_ref::<ProjectEntryId>() {
126 if let Some(entry_path) = workspace
127 .update(cx, |workspace, cx| {
128 let project = workspace.project().read(cx);
129 project
130 .path_for_entry(entry_id, cx)
131 .and_then(|project_path| project.absolute_path(&project_path, cx))
132 })
133 .log_err()
134 .flatten()
135 {
136 add_paths_to_terminal(pane, &[entry_path], cx);
137 }
138 } else if let Some(paths) = dropped_item.downcast_ref::<ExternalPaths>() {
139 add_paths_to_terminal(pane, paths.paths(), cx);
140 }
141
142 ControlFlow::Break(())
143 });
144 let buffer_search_bar = cx.new_view(search::BufferSearchBar::new);
145 pane.toolbar()
146 .update(cx, |toolbar, cx| toolbar.add_item(buffer_search_bar, cx));
147 pane
148 });
149 let subscriptions = vec![
150 cx.observe(&pane, |_, _, cx| cx.notify()),
151 cx.subscribe(&pane, Self::handle_pane_event),
152 ];
153 let this = Self {
154 pane,
155 fs: workspace.app_state().fs.clone(),
156 workspace: workspace.weak_handle(),
157 pending_serialization: Task::ready(None),
158 width: None,
159 height: None,
160 _subscriptions: subscriptions,
161 };
162 let mut old_dock_position = this.position(cx);
163 cx.observe_global::<SettingsStore>(move |this, cx| {
164 let new_dock_position = this.position(cx);
165 if new_dock_position != old_dock_position {
166 old_dock_position = new_dock_position;
167 cx.emit(PanelEvent::ChangePosition);
168 }
169 })
170 .detach();
171 this
172 }
173
174 pub async fn load(
175 workspace: WeakView<Workspace>,
176 mut cx: AsyncWindowContext,
177 ) -> Result<View<Self>> {
178 let serialized_panel = cx
179 .background_executor()
180 .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })
181 .await
182 .log_err()
183 .flatten()
184 .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
185 .transpose()
186 .log_err()
187 .flatten();
188
189 let (panel, pane, items) = workspace.update(&mut cx, |workspace, cx| {
190 let panel = cx.new_view(|cx| TerminalPanel::new(workspace, cx));
191 let items = if let Some(serialized_panel) = serialized_panel.as_ref() {
192 panel.update(cx, |panel, cx| {
193 cx.notify();
194 panel.height = serialized_panel.height;
195 panel.width = serialized_panel.width;
196 panel.pane.update(cx, |_, cx| {
197 serialized_panel
198 .items
199 .iter()
200 .map(|item_id| {
201 TerminalView::deserialize(
202 workspace.project().clone(),
203 workspace.weak_handle(),
204 workspace.database_id(),
205 *item_id,
206 cx,
207 )
208 })
209 .collect::<Vec<_>>()
210 })
211 })
212 } else {
213 Default::default()
214 };
215 let pane = panel.read(cx).pane.clone();
216 (panel, pane, items)
217 })?;
218
219 let pane = pane.downgrade();
220 let items = futures::future::join_all(items).await;
221 pane.update(&mut cx, |pane, cx| {
222 let active_item_id = serialized_panel
223 .as_ref()
224 .and_then(|panel| panel.active_item_id);
225 let mut active_ix = None;
226 for item in items {
227 if let Some(item) = item.log_err() {
228 let item_id = item.entity_id().as_u64();
229 pane.add_item(Box::new(item), false, false, None, cx);
230 if Some(item_id) == active_item_id {
231 active_ix = Some(pane.items_len() - 1);
232 }
233 }
234 }
235
236 if let Some(active_ix) = active_ix {
237 pane.activate_item(active_ix, false, false, cx)
238 }
239 })?;
240
241 Ok(panel)
242 }
243
244 fn handle_pane_event(
245 &mut self,
246 _pane: View<Pane>,
247 event: &pane::Event,
248 cx: &mut ViewContext<Self>,
249 ) {
250 match event {
251 pane::Event::ActivateItem { .. } => self.serialize(cx),
252 pane::Event::RemoveItem { .. } => self.serialize(cx),
253 pane::Event::Remove => cx.emit(PanelEvent::Close),
254 pane::Event::ZoomIn => cx.emit(PanelEvent::ZoomIn),
255 pane::Event::ZoomOut => cx.emit(PanelEvent::ZoomOut),
256
257 pane::Event::AddItem { item } => {
258 if let Some(workspace) = self.workspace.upgrade() {
259 let pane = self.pane.clone();
260 workspace.update(cx, |workspace, cx| item.added_to_pane(workspace, pane, cx))
261 }
262 }
263
264 _ => {}
265 }
266 }
267
268 pub fn open_terminal(
269 workspace: &mut Workspace,
270 action: &workspace::OpenTerminal,
271 cx: &mut ViewContext<Workspace>,
272 ) {
273 let Some(this) = workspace.focus_panel::<Self>(cx) else {
274 return;
275 };
276
277 this.update(cx, |this, cx| {
278 this.add_terminal(Some(action.working_directory.clone()), cx)
279 })
280 }
281
282 ///Create a new Terminal in the current working directory or the user's home directory
283 fn new_terminal(
284 workspace: &mut Workspace,
285 _: &workspace::NewTerminal,
286 cx: &mut ViewContext<Workspace>,
287 ) {
288 let Some(this) = workspace.focus_panel::<Self>(cx) else {
289 return;
290 };
291
292 this.update(cx, |this, cx| this.add_terminal(None, cx))
293 }
294
295 fn add_terminal(&mut self, working_directory: Option<PathBuf>, cx: &mut ViewContext<Self>) {
296 let workspace = self.workspace.clone();
297 cx.spawn(|this, mut cx| async move {
298 let pane = this.update(&mut cx, |this, _| this.pane.clone())?;
299 workspace.update(&mut cx, |workspace, cx| {
300 let working_directory = if let Some(working_directory) = working_directory {
301 Some(working_directory)
302 } else {
303 let working_directory_strategy =
304 TerminalSettings::get_global(cx).working_directory.clone();
305 crate::get_working_directory(workspace, cx, working_directory_strategy)
306 };
307
308 let window = cx.window_handle();
309 if let Some(terminal) = workspace.project().update(cx, |project, cx| {
310 project
311 .create_terminal(working_directory, window, cx)
312 .log_err()
313 }) {
314 let terminal = Box::new(cx.new_view(|cx| {
315 TerminalView::new(
316 terminal,
317 workspace.weak_handle(),
318 workspace.database_id(),
319 cx,
320 )
321 }));
322 pane.update(cx, |pane, cx| {
323 let focus = pane.has_focus(cx);
324 pane.add_item(terminal, true, focus, None, cx);
325 });
326 }
327 })?;
328 this.update(&mut cx, |this, cx| this.serialize(cx))?;
329 anyhow::Ok(())
330 })
331 .detach_and_log_err(cx);
332 }
333
334 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
335 let items = self
336 .pane
337 .read(cx)
338 .items()
339 .map(|item| item.item_id().as_u64())
340 .collect::<Vec<_>>();
341 let active_item_id = self
342 .pane
343 .read(cx)
344 .active_item()
345 .map(|item| item.item_id().as_u64());
346 let height = self.height;
347 let width = self.width;
348 self.pending_serialization = cx.background_executor().spawn(
349 async move {
350 KEY_VALUE_STORE
351 .write_kvp(
352 TERMINAL_PANEL_KEY.into(),
353 serde_json::to_string(&SerializedTerminalPanel {
354 items,
355 active_item_id,
356 height,
357 width,
358 })?,
359 )
360 .await?;
361 anyhow::Ok(())
362 }
363 .log_err(),
364 );
365 }
366}
367
368fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
369 if let Some(terminal_view) = pane
370 .active_item()
371 .and_then(|item| item.downcast::<TerminalView>())
372 {
373 cx.focus_view(&terminal_view);
374 let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
375 new_text.push(' ');
376 terminal_view.update(cx, |terminal_view, cx| {
377 terminal_view.terminal().update(cx, |terminal, _| {
378 terminal.paste(&new_text);
379 });
380 });
381 }
382}
383
384impl EventEmitter<PanelEvent> for TerminalPanel {}
385
386impl Render for TerminalPanel {
387 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
388 let mut registrar = DivRegistrar::new(
389 |panel, cx| {
390 panel
391 .pane
392 .read(cx)
393 .toolbar()
394 .read(cx)
395 .item_of_type::<BufferSearchBar>()
396 },
397 cx,
398 );
399 BufferSearchBar::register_inner(&mut registrar);
400 registrar.into_div().size_full().child(self.pane.clone())
401 }
402}
403
404impl FocusableView for TerminalPanel {
405 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
406 self.pane.focus_handle(cx)
407 }
408}
409
410impl Panel for TerminalPanel {
411 fn position(&self, cx: &WindowContext) -> DockPosition {
412 match TerminalSettings::get_global(cx).dock {
413 TerminalDockPosition::Left => DockPosition::Left,
414 TerminalDockPosition::Bottom => DockPosition::Bottom,
415 TerminalDockPosition::Right => DockPosition::Right,
416 }
417 }
418
419 fn position_is_valid(&self, _: DockPosition) -> bool {
420 true
421 }
422
423 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
424 settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {
425 let dock = match position {
426 DockPosition::Left => TerminalDockPosition::Left,
427 DockPosition::Bottom => TerminalDockPosition::Bottom,
428 DockPosition::Right => TerminalDockPosition::Right,
429 };
430 settings.dock = Some(dock);
431 });
432 }
433
434 fn size(&self, cx: &WindowContext) -> Pixels {
435 let settings = TerminalSettings::get_global(cx);
436 match self.position(cx) {
437 DockPosition::Left | DockPosition::Right => {
438 self.width.unwrap_or_else(|| settings.default_width)
439 }
440 DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
441 }
442 }
443
444 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
445 match self.position(cx) {
446 DockPosition::Left | DockPosition::Right => self.width = size,
447 DockPosition::Bottom => self.height = size,
448 }
449 self.serialize(cx);
450 cx.notify();
451 }
452
453 fn is_zoomed(&self, cx: &WindowContext) -> bool {
454 self.pane.read(cx).is_zoomed()
455 }
456
457 fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
458 self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
459 }
460
461 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
462 if active && self.pane.read(cx).items_len() == 0 {
463 self.add_terminal(None, cx)
464 }
465 }
466
467 fn icon_label(&self, cx: &WindowContext) -> Option<String> {
468 let count = self.pane.read(cx).items_len();
469 if count == 0 {
470 None
471 } else {
472 Some(count.to_string())
473 }
474 }
475
476 fn persistent_name() -> &'static str {
477 "TerminalPanel"
478 }
479
480 fn icon(&self, _cx: &WindowContext) -> Option<Icon> {
481 Some(Icon::Terminal)
482 }
483
484 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
485 Some("Terminal Panel")
486 }
487
488 fn toggle_action(&self) -> Box<dyn gpui::Action> {
489 Box::new(ToggleFocus)
490 }
491}
492
493#[derive(Serialize, Deserialize)]
494struct SerializedTerminalPanel {
495 items: Vec<u64>,
496 active_item_id: Option<u64>,
497 width: Option<Pixels>,
498 height: Option<Pixels>,
499}