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;
15use terminal::terminal_settings::{TerminalDockPosition, TerminalSettings};
16use ui::{h_flex, ButtonCommon, Clickable, IconButton, IconSize, Selectable, Tooltip};
17use util::{ResultExt, TryFutureExt};
18use workspace::{
19 dock::{DockPosition, Panel, PanelEvent},
20 item::Item,
21 pane,
22 ui::IconName,
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_flex()
72 .gap_2()
73 .child(
74 IconButton::new("plus", IconName::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", IconName::Maximize)
86 .icon_size(IconSize::Small)
87 .selected(zoomed)
88 .selected_icon(IconName::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 this
163 }
164
165 pub async fn load(
166 workspace: WeakView<Workspace>,
167 mut cx: AsyncWindowContext,
168 ) -> Result<View<Self>> {
169 let serialized_panel = cx
170 .background_executor()
171 .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })
172 .await
173 .log_err()
174 .flatten()
175 .map(|panel| serde_json::from_str::<SerializedTerminalPanel>(&panel))
176 .transpose()
177 .log_err()
178 .flatten();
179
180 let (panel, pane, items) = workspace.update(&mut cx, |workspace, cx| {
181 let panel = cx.new_view(|cx| TerminalPanel::new(workspace, cx));
182 let items = if let Some(serialized_panel) = serialized_panel.as_ref() {
183 panel.update(cx, |panel, cx| {
184 cx.notify();
185 panel.height = serialized_panel.height;
186 panel.width = serialized_panel.width;
187 panel.pane.update(cx, |_, cx| {
188 serialized_panel
189 .items
190 .iter()
191 .map(|item_id| {
192 TerminalView::deserialize(
193 workspace.project().clone(),
194 workspace.weak_handle(),
195 workspace.database_id(),
196 *item_id,
197 cx,
198 )
199 })
200 .collect::<Vec<_>>()
201 })
202 })
203 } else {
204 Default::default()
205 };
206 let pane = panel.read(cx).pane.clone();
207 (panel, pane, items)
208 })?;
209
210 let pane = pane.downgrade();
211 let items = futures::future::join_all(items).await;
212 pane.update(&mut cx, |pane, cx| {
213 let active_item_id = serialized_panel
214 .as_ref()
215 .and_then(|panel| panel.active_item_id);
216 let mut active_ix = None;
217 for item in items {
218 if let Some(item) = item.log_err() {
219 let item_id = item.entity_id().as_u64();
220 pane.add_item(Box::new(item), false, false, None, cx);
221 if Some(item_id) == active_item_id {
222 active_ix = Some(pane.items_len() - 1);
223 }
224 }
225 }
226
227 if let Some(active_ix) = active_ix {
228 pane.activate_item(active_ix, false, false, cx)
229 }
230 })?;
231
232 Ok(panel)
233 }
234
235 fn handle_pane_event(
236 &mut self,
237 _pane: View<Pane>,
238 event: &pane::Event,
239 cx: &mut ViewContext<Self>,
240 ) {
241 match event {
242 pane::Event::ActivateItem { .. } => self.serialize(cx),
243 pane::Event::RemoveItem { .. } => self.serialize(cx),
244 pane::Event::Remove => cx.emit(PanelEvent::Close),
245 pane::Event::ZoomIn => cx.emit(PanelEvent::ZoomIn),
246 pane::Event::ZoomOut => cx.emit(PanelEvent::ZoomOut),
247
248 pane::Event::AddItem { item } => {
249 if let Some(workspace) = self.workspace.upgrade() {
250 let pane = self.pane.clone();
251 workspace.update(cx, |workspace, cx| item.added_to_pane(workspace, pane, cx))
252 }
253 }
254
255 _ => {}
256 }
257 }
258
259 pub fn open_terminal(
260 workspace: &mut Workspace,
261 action: &workspace::OpenTerminal,
262 cx: &mut ViewContext<Workspace>,
263 ) {
264 let Some(this) = workspace.focus_panel::<Self>(cx) else {
265 return;
266 };
267
268 this.update(cx, |this, cx| {
269 this.add_terminal(Some(action.working_directory.clone()), cx)
270 })
271 }
272
273 ///Create a new Terminal in the current working directory or the user's home directory
274 fn new_terminal(
275 workspace: &mut Workspace,
276 _: &workspace::NewTerminal,
277 cx: &mut ViewContext<Workspace>,
278 ) {
279 let Some(this) = workspace.focus_panel::<Self>(cx) else {
280 return;
281 };
282
283 this.update(cx, |this, cx| this.add_terminal(None, cx))
284 }
285
286 fn add_terminal(&mut self, working_directory: Option<PathBuf>, cx: &mut ViewContext<Self>) {
287 let workspace = self.workspace.clone();
288 cx.spawn(|this, mut cx| async move {
289 let pane = this.update(&mut cx, |this, _| this.pane.clone())?;
290 workspace.update(&mut cx, |workspace, cx| {
291 let working_directory = if let Some(working_directory) = working_directory {
292 Some(working_directory)
293 } else {
294 let working_directory_strategy =
295 TerminalSettings::get_global(cx).working_directory.clone();
296 crate::get_working_directory(workspace, cx, working_directory_strategy)
297 };
298
299 let window = cx.window_handle();
300 if let Some(terminal) = workspace.project().update(cx, |project, cx| {
301 project
302 .create_terminal(working_directory, window, cx)
303 .log_err()
304 }) {
305 let terminal = Box::new(cx.new_view(|cx| {
306 TerminalView::new(
307 terminal,
308 workspace.weak_handle(),
309 workspace.database_id(),
310 cx,
311 )
312 }));
313 pane.update(cx, |pane, cx| {
314 let focus = pane.has_focus(cx);
315 pane.add_item(terminal, true, focus, None, cx);
316 });
317 }
318 })?;
319 this.update(&mut cx, |this, cx| this.serialize(cx))?;
320 anyhow::Ok(())
321 })
322 .detach_and_log_err(cx);
323 }
324
325 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
326 let items = self
327 .pane
328 .read(cx)
329 .items()
330 .map(|item| item.item_id().as_u64())
331 .collect::<Vec<_>>();
332 let active_item_id = self
333 .pane
334 .read(cx)
335 .active_item()
336 .map(|item| item.item_id().as_u64());
337 let height = self.height;
338 let width = self.width;
339 self.pending_serialization = cx.background_executor().spawn(
340 async move {
341 KEY_VALUE_STORE
342 .write_kvp(
343 TERMINAL_PANEL_KEY.into(),
344 serde_json::to_string(&SerializedTerminalPanel {
345 items,
346 active_item_id,
347 height,
348 width,
349 })?,
350 )
351 .await?;
352 anyhow::Ok(())
353 }
354 .log_err(),
355 );
356 }
357}
358
359fn add_paths_to_terminal(pane: &mut Pane, paths: &[PathBuf], cx: &mut ViewContext<'_, Pane>) {
360 if let Some(terminal_view) = pane
361 .active_item()
362 .and_then(|item| item.downcast::<TerminalView>())
363 {
364 cx.focus_view(&terminal_view);
365 let mut new_text = paths.iter().map(|path| format!(" {path:?}")).join("");
366 new_text.push(' ');
367 terminal_view.update(cx, |terminal_view, cx| {
368 terminal_view.terminal().update(cx, |terminal, _| {
369 terminal.paste(&new_text);
370 });
371 });
372 }
373}
374
375impl EventEmitter<PanelEvent> for TerminalPanel {}
376
377impl Render for TerminalPanel {
378 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
379 let mut registrar = DivRegistrar::new(
380 |panel, cx| {
381 panel
382 .pane
383 .read(cx)
384 .toolbar()
385 .read(cx)
386 .item_of_type::<BufferSearchBar>()
387 },
388 cx,
389 );
390 BufferSearchBar::register(&mut registrar);
391 registrar.into_div().size_full().child(self.pane.clone())
392 }
393}
394
395impl FocusableView for TerminalPanel {
396 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
397 self.pane.focus_handle(cx)
398 }
399}
400
401impl Panel for TerminalPanel {
402 fn position(&self, cx: &WindowContext) -> DockPosition {
403 match TerminalSettings::get_global(cx).dock {
404 TerminalDockPosition::Left => DockPosition::Left,
405 TerminalDockPosition::Bottom => DockPosition::Bottom,
406 TerminalDockPosition::Right => DockPosition::Right,
407 }
408 }
409
410 fn position_is_valid(&self, _: DockPosition) -> bool {
411 true
412 }
413
414 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
415 settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {
416 let dock = match position {
417 DockPosition::Left => TerminalDockPosition::Left,
418 DockPosition::Bottom => TerminalDockPosition::Bottom,
419 DockPosition::Right => TerminalDockPosition::Right,
420 };
421 settings.dock = Some(dock);
422 });
423 }
424
425 fn size(&self, cx: &WindowContext) -> Pixels {
426 let settings = TerminalSettings::get_global(cx);
427 match self.position(cx) {
428 DockPosition::Left | DockPosition::Right => {
429 self.width.unwrap_or_else(|| settings.default_width)
430 }
431 DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
432 }
433 }
434
435 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
436 match self.position(cx) {
437 DockPosition::Left | DockPosition::Right => self.width = size,
438 DockPosition::Bottom => self.height = size,
439 }
440 self.serialize(cx);
441 cx.notify();
442 }
443
444 fn is_zoomed(&self, cx: &WindowContext) -> bool {
445 self.pane.read(cx).is_zoomed()
446 }
447
448 fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
449 self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
450 }
451
452 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
453 if active && self.pane.read(cx).items_len() == 0 {
454 self.add_terminal(None, cx)
455 }
456 }
457
458 fn icon_label(&self, cx: &WindowContext) -> Option<String> {
459 let count = self.pane.read(cx).items_len();
460 if count == 0 {
461 None
462 } else {
463 Some(count.to_string())
464 }
465 }
466
467 fn persistent_name() -> &'static str {
468 "TerminalPanel"
469 }
470
471 fn icon(&self, _cx: &WindowContext) -> Option<IconName> {
472 Some(IconName::Terminal)
473 }
474
475 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
476 Some("Terminal Panel")
477 }
478
479 fn toggle_action(&self) -> Box<dyn gpui::Action> {
480 Box::new(ToggleFocus)
481 }
482}
483
484#[derive(Serialize, Deserialize)]
485struct SerializedTerminalPanel {
486 items: Vec<u64>,
487 active_item_id: Option<u64>,
488 width: Option<Pixels>,
489 height: Option<Pixels>,
490}