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