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