1use anyhow::Result;
2use async_recursion::async_recursion;
3use collections::HashSet;
4use futures::{stream::FuturesUnordered, StreamExt as _};
5use gpui::{AsyncWindowContext, Axis, Model, Task, View, WeakView};
6use project::{terminals::TerminalKind, Project};
7use serde::{Deserialize, Serialize};
8use std::path::{Path, PathBuf};
9use ui::{Pixels, ViewContext, VisualContext as _, WindowContext};
10use util::ResultExt as _;
11
12use db::{define_connection, query, sqlez::statement::Statement, sqlez_macros::sql};
13use workspace::{
14 ItemHandle, ItemId, Member, Pane, PaneAxis, PaneGroup, SerializableItem as _, Workspace,
15 WorkspaceDb, WorkspaceId,
16};
17
18use crate::{
19 default_working_directory,
20 terminal_panel::{new_terminal_pane, TerminalPanel},
21 TerminalView,
22};
23
24pub(crate) fn serialize_pane_group(
25 pane_group: &PaneGroup,
26 active_pane: &View<Pane>,
27 cx: &WindowContext,
28) -> SerializedPaneGroup {
29 build_serialized_pane_group(&pane_group.root, active_pane, cx)
30}
31
32fn build_serialized_pane_group(
33 pane_group: &Member,
34 active_pane: &View<Pane>,
35 cx: &WindowContext,
36) -> SerializedPaneGroup {
37 match pane_group {
38 Member::Axis(PaneAxis {
39 axis,
40 members,
41 flexes,
42 bounding_boxes: _,
43 }) => SerializedPaneGroup::Group {
44 axis: SerializedAxis(*axis),
45 children: members
46 .iter()
47 .map(|member| build_serialized_pane_group(member, active_pane, cx))
48 .collect::<Vec<_>>(),
49 flexes: Some(flexes.lock().clone()),
50 },
51 Member::Pane(pane_handle) => {
52 SerializedPaneGroup::Pane(serialize_pane(pane_handle, pane_handle == active_pane, cx))
53 }
54 }
55}
56
57fn serialize_pane(pane: &View<Pane>, active: bool, cx: &WindowContext) -> SerializedPane {
58 let mut items_to_serialize = HashSet::default();
59 let pane = pane.read(cx);
60 let children = pane
61 .items()
62 .filter_map(|item| {
63 let terminal_view = item.act_as::<TerminalView>(cx)?;
64 if terminal_view.read(cx).terminal().read(cx).task().is_some() {
65 None
66 } else {
67 let id = item.item_id().as_u64();
68 items_to_serialize.insert(id);
69 Some(id)
70 }
71 })
72 .collect::<Vec<_>>();
73 let active_item = pane
74 .active_item()
75 .map(|item| item.item_id().as_u64())
76 .filter(|active_id| items_to_serialize.contains(active_id));
77
78 SerializedPane {
79 active,
80 children,
81 active_item,
82 }
83}
84
85pub(crate) fn deserialize_terminal_panel(
86 workspace: WeakView<Workspace>,
87 project: Model<Project>,
88 database_id: WorkspaceId,
89 serialized_panel: SerializedTerminalPanel,
90 cx: &mut WindowContext,
91) -> Task<anyhow::Result<View<TerminalPanel>>> {
92 cx.spawn(move |mut cx| async move {
93 let terminal_panel = workspace.update(&mut cx, |workspace, cx| {
94 cx.new_view(|cx| {
95 let mut panel = TerminalPanel::new(workspace, cx);
96 panel.height = serialized_panel.height.map(|h| h.round());
97 panel.width = serialized_panel.width.map(|w| w.round());
98 panel
99 })
100 })?;
101 match &serialized_panel.items {
102 SerializedItems::NoSplits(item_ids) => {
103 let items = deserialize_terminal_views(
104 database_id,
105 project,
106 workspace,
107 item_ids.as_slice(),
108 &mut cx,
109 )
110 .await;
111 let active_item = serialized_panel.active_item_id;
112 terminal_panel.update(&mut cx, |terminal_panel, cx| {
113 terminal_panel.active_pane.update(cx, |pane, cx| {
114 populate_pane_items(pane, items, active_item, cx);
115 });
116 })?;
117 }
118 SerializedItems::WithSplits(serialized_pane_group) => {
119 let center_pane = deserialize_pane_group(
120 workspace,
121 project,
122 terminal_panel.clone(),
123 database_id,
124 serialized_pane_group,
125 &mut cx,
126 )
127 .await;
128 if let Some((center_group, active_pane)) = center_pane {
129 terminal_panel.update(&mut cx, |terminal_panel, _| {
130 terminal_panel.center = PaneGroup::with_root(center_group);
131 terminal_panel.active_pane =
132 active_pane.unwrap_or_else(|| terminal_panel.center.first_pane());
133 })?;
134 }
135 }
136 }
137
138 Ok(terminal_panel)
139 })
140}
141
142fn populate_pane_items(
143 pane: &mut Pane,
144 items: Vec<View<TerminalView>>,
145 active_item: Option<u64>,
146 cx: &mut ViewContext<Pane>,
147) {
148 let mut item_index = pane.items_len();
149 for item in items {
150 let activate_item = Some(item.item_id().as_u64()) == active_item;
151 pane.add_item(Box::new(item), false, false, None, cx);
152 item_index += 1;
153 if activate_item {
154 pane.activate_item(item_index, false, false, cx);
155 }
156 }
157}
158
159#[async_recursion(?Send)]
160async fn deserialize_pane_group(
161 workspace: WeakView<Workspace>,
162 project: Model<Project>,
163 panel: View<TerminalPanel>,
164 workspace_id: WorkspaceId,
165 serialized: &SerializedPaneGroup,
166 cx: &mut AsyncWindowContext,
167) -> Option<(Member, Option<View<Pane>>)> {
168 match serialized {
169 SerializedPaneGroup::Group {
170 axis,
171 flexes,
172 children,
173 } => {
174 let mut current_active_pane = None;
175 let mut members = Vec::new();
176 for child in children {
177 if let Some((new_member, active_pane)) = deserialize_pane_group(
178 workspace.clone(),
179 project.clone(),
180 panel.clone(),
181 workspace_id,
182 child,
183 cx,
184 )
185 .await
186 {
187 members.push(new_member);
188 current_active_pane = current_active_pane.or(active_pane);
189 }
190 }
191
192 if members.is_empty() {
193 return None;
194 }
195
196 if members.len() == 1 {
197 return Some((members.remove(0), current_active_pane));
198 }
199
200 Some((
201 Member::Axis(PaneAxis::load(axis.0, members, flexes.clone())),
202 current_active_pane,
203 ))
204 }
205 SerializedPaneGroup::Pane(serialized_pane) => {
206 let active = serialized_pane.active;
207 let new_items = deserialize_terminal_views(
208 workspace_id,
209 project.clone(),
210 workspace.clone(),
211 serialized_pane.children.as_slice(),
212 cx,
213 )
214 .await;
215
216 let pane = panel
217 .update(cx, |terminal_panel, cx| {
218 new_terminal_pane(
219 workspace.clone(),
220 project.clone(),
221 terminal_panel.active_pane.read(cx).is_zoomed(),
222 cx,
223 )
224 })
225 .log_err()?;
226 let active_item = serialized_pane.active_item;
227
228 let terminal = pane
229 .update(cx, |pane, cx| {
230 populate_pane_items(pane, new_items, active_item, cx);
231 // Avoid blank panes in splits
232 if pane.items_len() == 0 {
233 let working_directory = workspace
234 .update(cx, |workspace, cx| default_working_directory(workspace, cx))
235 .ok()
236 .flatten();
237 let kind = TerminalKind::Shell(
238 working_directory.as_deref().map(Path::to_path_buf),
239 );
240 let window = cx.window_handle();
241 let terminal = project
242 .update(cx, |project, cx| project.create_terminal(kind, window, cx));
243 Some(Some(terminal))
244 } else {
245 Some(None)
246 }
247 })
248 .ok()
249 .flatten()?;
250 if let Some(terminal) = terminal {
251 let terminal = terminal.await.ok()?;
252 pane.update(cx, |pane, cx| {
253 let terminal_view = Box::new(cx.new_view(|cx| {
254 TerminalView::new(
255 terminal,
256 workspace.clone(),
257 Some(workspace_id),
258 project.downgrade(),
259 cx,
260 )
261 }));
262 pane.add_item(terminal_view, true, false, None, cx);
263 })
264 .ok()?;
265 }
266 Some((Member::Pane(pane.clone()), active.then_some(pane)))
267 }
268 }
269}
270
271async fn deserialize_terminal_views(
272 workspace_id: WorkspaceId,
273 project: Model<Project>,
274 workspace: WeakView<Workspace>,
275 item_ids: &[u64],
276 cx: &mut AsyncWindowContext,
277) -> Vec<View<TerminalView>> {
278 let mut items = Vec::with_capacity(item_ids.len());
279 let mut deserialized_items = item_ids
280 .iter()
281 .map(|item_id| {
282 cx.update(|cx| {
283 TerminalView::deserialize(
284 project.clone(),
285 workspace.clone(),
286 workspace_id,
287 *item_id,
288 cx,
289 )
290 })
291 .unwrap_or_else(|e| Task::ready(Err(e.context("no window present"))))
292 })
293 .collect::<FuturesUnordered<_>>();
294 while let Some(item) = deserialized_items.next().await {
295 if let Some(item) = item.log_err() {
296 items.push(item);
297 }
298 }
299 items
300}
301
302#[derive(Debug, Serialize, Deserialize)]
303pub(crate) struct SerializedTerminalPanel {
304 pub items: SerializedItems,
305 // A deprecated field, kept for backwards compatibility for the code before terminal splits were introduced.
306 pub active_item_id: Option<u64>,
307 pub width: Option<Pixels>,
308 pub height: Option<Pixels>,
309}
310
311#[derive(Debug, Serialize, Deserialize)]
312#[serde(untagged)]
313pub(crate) enum SerializedItems {
314 // The data stored before terminal splits were introduced.
315 NoSplits(Vec<u64>),
316 WithSplits(SerializedPaneGroup),
317}
318
319#[derive(Debug, Serialize, Deserialize)]
320pub(crate) enum SerializedPaneGroup {
321 Pane(SerializedPane),
322 Group {
323 axis: SerializedAxis,
324 flexes: Option<Vec<f32>>,
325 children: Vec<SerializedPaneGroup>,
326 },
327}
328
329#[derive(Debug, Serialize, Deserialize)]
330pub(crate) struct SerializedPane {
331 pub active: bool,
332 pub children: Vec<u64>,
333 pub active_item: Option<u64>,
334}
335
336#[derive(Debug)]
337pub(crate) struct SerializedAxis(pub Axis);
338
339impl Serialize for SerializedAxis {
340 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
341 where
342 S: serde::Serializer,
343 {
344 match self.0 {
345 Axis::Horizontal => serializer.serialize_str("horizontal"),
346 Axis::Vertical => serializer.serialize_str("vertical"),
347 }
348 }
349}
350
351impl<'de> Deserialize<'de> for SerializedAxis {
352 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
353 where
354 D: serde::Deserializer<'de>,
355 {
356 let s = String::deserialize(deserializer)?;
357 match s.as_str() {
358 "horizontal" => Ok(SerializedAxis(Axis::Horizontal)),
359 "vertical" => Ok(SerializedAxis(Axis::Vertical)),
360 invalid => Err(serde::de::Error::custom(format!(
361 "Invalid axis value: '{invalid}'"
362 ))),
363 }
364 }
365}
366
367define_connection! {
368 pub static ref TERMINAL_DB: TerminalDb<WorkspaceDb> =
369 &[sql!(
370 CREATE TABLE terminals (
371 workspace_id INTEGER,
372 item_id INTEGER UNIQUE,
373 working_directory BLOB,
374 PRIMARY KEY(workspace_id, item_id),
375 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
376 ON DELETE CASCADE
377 ) STRICT;
378 ),
379 // Remove the unique constraint on the item_id table
380 // SQLite doesn't have a way of doing this automatically, so
381 // we have to do this silly copying.
382 sql!(
383 CREATE TABLE terminals2 (
384 workspace_id INTEGER,
385 item_id INTEGER,
386 working_directory BLOB,
387 PRIMARY KEY(workspace_id, item_id),
388 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
389 ON DELETE CASCADE
390 ) STRICT;
391
392 INSERT INTO terminals2 (workspace_id, item_id, working_directory)
393 SELECT workspace_id, item_id, working_directory FROM terminals;
394
395 DROP TABLE terminals;
396
397 ALTER TABLE terminals2 RENAME TO terminals;
398 )];
399}
400
401impl TerminalDb {
402 query! {
403 pub async fn update_workspace_id(
404 new_id: WorkspaceId,
405 old_id: WorkspaceId,
406 item_id: ItemId
407 ) -> Result<()> {
408 UPDATE terminals
409 SET workspace_id = ?
410 WHERE workspace_id = ? AND item_id = ?
411 }
412 }
413
414 query! {
415 pub async fn save_working_directory(
416 item_id: ItemId,
417 workspace_id: WorkspaceId,
418 working_directory: PathBuf
419 ) -> Result<()> {
420 INSERT OR REPLACE INTO terminals(item_id, workspace_id, working_directory)
421 VALUES (?, ?, ?)
422 }
423 }
424
425 query! {
426 pub fn get_working_directory(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
427 SELECT working_directory
428 FROM terminals
429 WHERE item_id = ? AND workspace_id = ?
430 }
431 }
432
433 pub async fn delete_unloaded_items(
434 &self,
435 workspace: WorkspaceId,
436 alive_items: Vec<ItemId>,
437 ) -> Result<()> {
438 let placeholders = alive_items
439 .iter()
440 .map(|_| "?")
441 .collect::<Vec<&str>>()
442 .join(", ");
443
444 let query = format!(
445 "DELETE FROM terminals WHERE workspace_id = ? AND item_id NOT IN ({placeholders})"
446 );
447
448 self.write(move |conn| {
449 let mut statement = Statement::prepare(conn, query)?;
450 let mut next_index = statement.bind(&workspace, 1)?;
451 for id in alive_items {
452 next_index = statement.bind(&id, next_index)?;
453 }
454 statement.exec()
455 })
456 .await
457 }
458}