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