1use std::sync::Arc;
2
3use crate::TerminalView;
4use db::kvp::KEY_VALUE_STORE;
5use gpui::{
6 actions, anyhow::Result, elements::*, serde_json, Action, AppContext, AsyncAppContext, Entity,
7 Subscription, Task, View, ViewContext, ViewHandle, WeakViewHandle, WindowContext,
8};
9use project::Fs;
10use serde::{Deserialize, Serialize};
11use settings::SettingsStore;
12use terminal::{TerminalDockPosition, TerminalSettings};
13use util::{ResultExt, TryFutureExt};
14use workspace::{
15 dock::{DockPosition, Panel},
16 item::Item,
17 pane, DraggedItem, Pane, Workspace,
18};
19
20const TERMINAL_PANEL_KEY: &'static str = "TerminalPanel";
21
22actions!(terminal_panel, [ToggleFocus]);
23
24pub fn init(cx: &mut AppContext) {
25 cx.add_action(TerminalPanel::new_terminal);
26}
27
28pub enum Event {
29 Close,
30 DockPositionChanged,
31 ZoomIn,
32 ZoomOut,
33 Focus,
34}
35
36pub struct TerminalPanel {
37 pane: ViewHandle<Pane>,
38 fs: Arc<dyn Fs>,
39 workspace: WeakViewHandle<Workspace>,
40 width: Option<f32>,
41 height: Option<f32>,
42 pending_serialization: Task<Option<()>>,
43 _subscriptions: Vec<Subscription>,
44}
45
46impl TerminalPanel {
47 fn new(workspace: &Workspace, cx: &mut ViewContext<Self>) -> Self {
48 let weak_self = cx.weak_handle();
49 let pane = cx.add_view(|cx| {
50 let window_id = cx.window_id();
51 let mut pane = Pane::new(
52 workspace.weak_handle(),
53 workspace.app_state().background_actions,
54 Default::default(),
55 cx,
56 );
57 pane.set_can_split(false, cx);
58 pane.set_can_navigate(false, cx);
59 pane.on_can_drop(move |drag_and_drop, cx| {
60 drag_and_drop
61 .currently_dragged::<DraggedItem>(window_id)
62 .map_or(false, |(_, item)| {
63 item.handle.act_as::<TerminalView>(cx).is_some()
64 })
65 });
66 pane.set_render_tab_bar_buttons(cx, move |pane, cx| {
67 let this = weak_self.clone();
68 Flex::row()
69 .with_child(Pane::render_tab_bar_button(
70 0,
71 "icons/plus_12.svg",
72 false,
73 Some((
74 "New Terminal".into(),
75 Some(Box::new(workspace::NewTerminal)),
76 )),
77 cx,
78 move |_, cx| {
79 let this = this.clone();
80 cx.window_context().defer(move |cx| {
81 if let Some(this) = this.upgrade(cx) {
82 this.update(cx, |this, cx| {
83 this.add_terminal(cx);
84 });
85 }
86 })
87 },
88 None,
89 ))
90 .with_child(Pane::render_tab_bar_button(
91 1,
92 if pane.is_zoomed() {
93 "icons/minimize_8.svg"
94 } else {
95 "icons/maximize_8.svg"
96 },
97 pane.is_zoomed(),
98 Some(("Toggle Zoom".into(), Some(Box::new(workspace::ToggleZoom)))),
99 cx,
100 move |pane, cx| pane.toggle_zoom(&Default::default(), cx),
101 None,
102 ))
103 .into_any()
104 });
105 let buffer_search_bar = cx.add_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(Event::DockPositionChanged);
129 }
130 })
131 .detach();
132 this
133 }
134
135 pub fn load(
136 workspace: WeakViewHandle<Workspace>,
137 cx: AsyncAppContext,
138 ) -> Task<Result<ViewHandle<Self>>> {
139 cx.spawn(|mut cx| async move {
140 let serialized_panel = if let Some(panel) = cx
141 .background()
142 .spawn(async move { KEY_VALUE_STORE.read_kvp(TERMINAL_PANEL_KEY) })
143 .await
144 .log_err()
145 .flatten()
146 {
147 Some(serde_json::from_str::<SerializedTerminalPanel>(&panel)?)
148 } else {
149 None
150 };
151 let (panel, pane, items) = workspace.update(&mut cx, |workspace, cx| {
152 let panel = cx.add_view(|cx| TerminalPanel::new(workspace, cx));
153 let items = if let Some(serialized_panel) = serialized_panel.as_ref() {
154 panel.update(cx, |panel, cx| {
155 cx.notify();
156 panel.height = serialized_panel.height;
157 panel.width = serialized_panel.width;
158 panel.pane.update(cx, |_, cx| {
159 serialized_panel
160 .items
161 .iter()
162 .map(|item_id| {
163 TerminalView::deserialize(
164 workspace.project().clone(),
165 workspace.weak_handle(),
166 workspace.database_id(),
167 *item_id,
168 cx,
169 )
170 })
171 .collect::<Vec<_>>()
172 })
173 })
174 } else {
175 Default::default()
176 };
177 let pane = panel.read(cx).pane.clone();
178 (panel, pane, items)
179 })?;
180
181 let items = futures::future::join_all(items).await;
182 workspace.update(&mut cx, |workspace, 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.id();
190 Pane::add_item(workspace, &pane, Box::new(item), false, false, None, cx);
191 if Some(item_id) == active_item_id {
192 active_ix = Some(pane.read(cx).items_len() - 1);
193 }
194 }
195 }
196
197 if let Some(active_ix) = active_ix {
198 pane.update(cx, |pane, cx| {
199 pane.activate_item(active_ix, false, false, cx)
200 });
201 }
202 })?;
203
204 Ok(panel)
205 })
206 }
207
208 fn handle_pane_event(
209 &mut self,
210 _pane: ViewHandle<Pane>,
211 event: &pane::Event,
212 cx: &mut ViewContext<Self>,
213 ) {
214 match event {
215 pane::Event::ActivateItem { .. } => self.serialize(cx),
216 pane::Event::RemoveItem { .. } => self.serialize(cx),
217 pane::Event::Remove => cx.emit(Event::Close),
218 pane::Event::ZoomIn => cx.emit(Event::ZoomIn),
219 pane::Event::ZoomOut => cx.emit(Event::ZoomOut),
220 pane::Event::Focus => cx.emit(Event::Focus),
221 _ => {}
222 }
223 }
224
225 fn new_terminal(
226 workspace: &mut Workspace,
227 _: &workspace::NewTerminal,
228 cx: &mut ViewContext<Workspace>,
229 ) {
230 let Some(this) = workspace.focus_panel::<Self>(cx) else {
231 return;
232 };
233
234 this.update(cx, |this, cx| this.add_terminal(cx))
235 }
236
237 fn add_terminal(&mut self, cx: &mut ViewContext<Self>) {
238 let workspace = self.workspace.clone();
239 cx.spawn(|this, mut cx| async move {
240 let pane = this.read_with(&cx, |this, _| this.pane.clone())?;
241 workspace.update(&mut cx, |workspace, cx| {
242 let working_directory_strategy = settings::get::<TerminalSettings>(cx)
243 .working_directory
244 .clone();
245 let working_directory =
246 crate::get_working_directory(workspace, cx, working_directory_strategy);
247 let window_id = cx.window_id();
248 if let Some(terminal) = workspace.project().update(cx, |project, cx| {
249 project
250 .create_terminal(working_directory, window_id, cx)
251 .log_err()
252 }) {
253 let terminal =
254 Box::new(cx.add_view(|cx| {
255 TerminalView::new(terminal, workspace.database_id(), cx)
256 }));
257 let focus = pane.read(cx).has_focus();
258 Pane::add_item(workspace, &pane, terminal, true, focus, None, cx);
259 }
260 })?;
261 this.update(&mut cx, |this, cx| this.serialize(cx))?;
262 anyhow::Ok(())
263 })
264 .detach_and_log_err(cx);
265 }
266
267 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
268 let items = self
269 .pane
270 .read(cx)
271 .items()
272 .map(|item| item.id())
273 .collect::<Vec<_>>();
274 let active_item_id = self.pane.read(cx).active_item().map(|item| item.id());
275 let height = self.height;
276 let width = self.width;
277 self.pending_serialization = cx.background().spawn(
278 async move {
279 KEY_VALUE_STORE
280 .write_kvp(
281 TERMINAL_PANEL_KEY.into(),
282 serde_json::to_string(&SerializedTerminalPanel {
283 items,
284 active_item_id,
285 height,
286 width,
287 })?,
288 )
289 .await?;
290 anyhow::Ok(())
291 }
292 .log_err(),
293 );
294 }
295}
296
297impl Entity for TerminalPanel {
298 type Event = Event;
299}
300
301impl View for TerminalPanel {
302 fn ui_name() -> &'static str {
303 "TerminalPanel"
304 }
305
306 fn render(&mut self, cx: &mut ViewContext<Self>) -> gpui::AnyElement<Self> {
307 ChildView::new(&self.pane, cx).into_any()
308 }
309
310 fn focus_in(&mut self, _: gpui::AnyViewHandle, cx: &mut ViewContext<Self>) {
311 if cx.is_self_focused() {
312 cx.focus(&self.pane);
313 }
314 }
315}
316
317impl Panel for TerminalPanel {
318 fn position(&self, cx: &WindowContext) -> DockPosition {
319 match settings::get::<TerminalSettings>(cx).dock {
320 TerminalDockPosition::Left => DockPosition::Left,
321 TerminalDockPosition::Bottom => DockPosition::Bottom,
322 TerminalDockPosition::Right => DockPosition::Right,
323 }
324 }
325
326 fn position_is_valid(&self, _: DockPosition) -> bool {
327 true
328 }
329
330 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
331 settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {
332 let dock = match position {
333 DockPosition::Left => TerminalDockPosition::Left,
334 DockPosition::Bottom => TerminalDockPosition::Bottom,
335 DockPosition::Right => TerminalDockPosition::Right,
336 };
337 settings.dock = Some(dock);
338 });
339 }
340
341 fn size(&self, cx: &WindowContext) -> f32 {
342 let settings = settings::get::<TerminalSettings>(cx);
343 match self.position(cx) {
344 DockPosition::Left | DockPosition::Right => {
345 self.width.unwrap_or_else(|| settings.default_width)
346 }
347 DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
348 }
349 }
350
351 fn set_size(&mut self, size: f32, cx: &mut ViewContext<Self>) {
352 match self.position(cx) {
353 DockPosition::Left | DockPosition::Right => self.width = Some(size),
354 DockPosition::Bottom => self.height = Some(size),
355 }
356 self.serialize(cx);
357 cx.notify();
358 }
359
360 fn should_zoom_in_on_event(event: &Event) -> bool {
361 matches!(event, Event::ZoomIn)
362 }
363
364 fn should_zoom_out_on_event(event: &Event) -> bool {
365 matches!(event, Event::ZoomOut)
366 }
367
368 fn is_zoomed(&self, cx: &WindowContext) -> bool {
369 self.pane.read(cx).is_zoomed()
370 }
371
372 fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
373 self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
374 }
375
376 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
377 if active && self.pane.read(cx).items_len() == 0 {
378 self.add_terminal(cx)
379 }
380 }
381
382 fn icon_path(&self) -> &'static str {
383 "icons/terminal_12.svg"
384 }
385
386 fn icon_tooltip(&self) -> (String, Option<Box<dyn Action>>) {
387 ("Terminal Panel".into(), Some(Box::new(ToggleFocus)))
388 }
389
390 fn icon_label(&self, cx: &WindowContext) -> Option<String> {
391 let count = self.pane.read(cx).items_len();
392 if count == 0 {
393 None
394 } else {
395 Some(count.to_string())
396 }
397 }
398
399 fn should_change_position_on_event(event: &Self::Event) -> bool {
400 matches!(event, Event::DockPositionChanged)
401 }
402
403 fn should_activate_on_event(_: &Self::Event) -> bool {
404 false
405 }
406
407 fn should_close_on_event(event: &Event) -> bool {
408 matches!(event, Event::Close)
409 }
410
411 fn has_focus(&self, cx: &WindowContext) -> bool {
412 self.pane.read(cx).has_focus()
413 }
414
415 fn is_focus_event(event: &Self::Event) -> bool {
416 matches!(event, Event::Focus)
417 }
418}
419
420#[derive(Serialize, Deserialize)]
421struct SerializedTerminalPanel {
422 items: Vec<usize>,
423 active_item_id: Option<usize>,
424 width: Option<f32>,
425 height: Option<f32>,
426}