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