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 }
226 }
227
228 fn new_terminal(
229 workspace: &mut Workspace,
230 _: &workspace::NewTerminal,
231 cx: &mut ViewContext<Workspace>,
232 ) {
233 let Some(this) = workspace.focus_panel::<Self>(cx) else {
234 return;
235 };
236
237 this.update(cx, |this, cx| this.add_terminal(cx))
238 }
239
240 fn add_terminal(&mut self, cx: &mut ViewContext<Self>) {
241 let workspace = self.workspace.clone();
242 cx.spawn(|this, mut cx| async move {
243 let pane = this.read_with(&cx, |this, _| this.pane.clone())?;
244 workspace.update(&mut cx, |workspace, cx| {
245 let working_directory_strategy = settings::get::<TerminalSettings>(cx)
246 .working_directory
247 .clone();
248 let working_directory =
249 crate::get_working_directory(workspace, cx, working_directory_strategy);
250 let window_id = cx.window_id();
251 if let Some(terminal) = workspace.project().update(cx, |project, cx| {
252 project
253 .create_terminal(working_directory, window_id, cx)
254 .log_err()
255 }) {
256 let terminal =
257 Box::new(cx.add_view(|cx| {
258 TerminalView::new(terminal, workspace.database_id(), cx)
259 }));
260 pane.update(cx, |pane, cx| {
261 let focus = pane.has_focus();
262 pane.add_item(terminal, true, focus, None, cx);
263 });
264 }
265 })?;
266 this.update(&mut cx, |this, cx| this.serialize(cx))?;
267 anyhow::Ok(())
268 })
269 .detach_and_log_err(cx);
270 }
271
272 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
273 let items = self
274 .pane
275 .read(cx)
276 .items()
277 .map(|item| item.id())
278 .collect::<Vec<_>>();
279 let active_item_id = self.pane.read(cx).active_item().map(|item| item.id());
280 let height = self.height;
281 let width = self.width;
282 self.pending_serialization = cx.background().spawn(
283 async move {
284 KEY_VALUE_STORE
285 .write_kvp(
286 TERMINAL_PANEL_KEY.into(),
287 serde_json::to_string(&SerializedTerminalPanel {
288 items,
289 active_item_id,
290 height,
291 width,
292 })?,
293 )
294 .await?;
295 anyhow::Ok(())
296 }
297 .log_err(),
298 );
299 }
300}
301
302impl Entity for TerminalPanel {
303 type Event = Event;
304}
305
306impl View for TerminalPanel {
307 fn ui_name() -> &'static str {
308 "TerminalPanel"
309 }
310
311 fn render(&mut self, cx: &mut ViewContext<Self>) -> gpui::AnyElement<Self> {
312 ChildView::new(&self.pane, cx).into_any()
313 }
314
315 fn focus_in(&mut self, _: gpui::AnyViewHandle, cx: &mut ViewContext<Self>) {
316 if cx.is_self_focused() {
317 cx.focus(&self.pane);
318 }
319 }
320}
321
322impl Panel for TerminalPanel {
323 fn position(&self, cx: &WindowContext) -> DockPosition {
324 match settings::get::<TerminalSettings>(cx).dock {
325 TerminalDockPosition::Left => DockPosition::Left,
326 TerminalDockPosition::Bottom => DockPosition::Bottom,
327 TerminalDockPosition::Right => DockPosition::Right,
328 }
329 }
330
331 fn position_is_valid(&self, _: DockPosition) -> bool {
332 true
333 }
334
335 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
336 settings::update_settings_file::<TerminalSettings>(self.fs.clone(), cx, move |settings| {
337 let dock = match position {
338 DockPosition::Left => TerminalDockPosition::Left,
339 DockPosition::Bottom => TerminalDockPosition::Bottom,
340 DockPosition::Right => TerminalDockPosition::Right,
341 };
342 settings.dock = Some(dock);
343 });
344 }
345
346 fn size(&self, cx: &WindowContext) -> f32 {
347 let settings = settings::get::<TerminalSettings>(cx);
348 match self.position(cx) {
349 DockPosition::Left | DockPosition::Right => {
350 self.width.unwrap_or_else(|| settings.default_width)
351 }
352 DockPosition::Bottom => self.height.unwrap_or_else(|| settings.default_height),
353 }
354 }
355
356 fn set_size(&mut self, size: f32, cx: &mut ViewContext<Self>) {
357 match self.position(cx) {
358 DockPosition::Left | DockPosition::Right => self.width = Some(size),
359 DockPosition::Bottom => self.height = Some(size),
360 }
361 self.serialize(cx);
362 cx.notify();
363 }
364
365 fn should_zoom_in_on_event(event: &Event) -> bool {
366 matches!(event, Event::ZoomIn)
367 }
368
369 fn should_zoom_out_on_event(event: &Event) -> bool {
370 matches!(event, Event::ZoomOut)
371 }
372
373 fn is_zoomed(&self, cx: &WindowContext) -> bool {
374 self.pane.read(cx).is_zoomed()
375 }
376
377 fn set_zoomed(&mut self, zoomed: bool, cx: &mut ViewContext<Self>) {
378 self.pane.update(cx, |pane, cx| pane.set_zoomed(zoomed, cx));
379 }
380
381 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
382 if active && self.pane.read(cx).items_len() == 0 {
383 self.add_terminal(cx)
384 }
385 }
386
387 fn icon_path(&self) -> &'static str {
388 "icons/terminal_12.svg"
389 }
390
391 fn icon_tooltip(&self) -> (String, Option<Box<dyn Action>>) {
392 ("Terminal Panel".into(), Some(Box::new(ToggleFocus)))
393 }
394
395 fn icon_label(&self, cx: &WindowContext) -> Option<String> {
396 let count = self.pane.read(cx).items_len();
397 if count == 0 {
398 None
399 } else {
400 Some(count.to_string())
401 }
402 }
403
404 fn should_change_position_on_event(event: &Self::Event) -> bool {
405 matches!(event, Event::DockPositionChanged)
406 }
407
408 fn should_activate_on_event(_: &Self::Event) -> bool {
409 false
410 }
411
412 fn should_close_on_event(event: &Event) -> bool {
413 matches!(event, Event::Close)
414 }
415
416 fn has_focus(&self, cx: &WindowContext) -> bool {
417 self.pane.read(cx).has_focus()
418 }
419
420 fn is_focus_event(event: &Self::Event) -> bool {
421 matches!(event, Event::Focus)
422 }
423}
424
425#[derive(Serialize, Deserialize)]
426struct SerializedTerminalPanel {
427 items: Vec<usize>,
428 active_item_id: Option<usize>,
429 width: Option<f32>,
430 height: Option<f32>,
431}