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, |_, cx| {
218 new_terminal_pane(workspace.clone(), project.clone(), cx)
219 })
220 .log_err()?;
221 let active_item = serialized_pane.active_item;
222
223 let terminal = pane
224 .update(cx, |pane, cx| {
225 populate_pane_items(pane, new_items, active_item, cx);
226 // Avoid blank panes in splits
227 if pane.items_len() == 0 {
228 let working_directory = workspace
229 .update(cx, |workspace, cx| default_working_directory(workspace, cx))
230 .ok()
231 .flatten();
232 let kind = TerminalKind::Shell(
233 working_directory.as_deref().map(Path::to_path_buf),
234 );
235 let window = cx.window_handle();
236 let terminal = project
237 .update(cx, |project, cx| project.create_terminal(kind, window, cx));
238 Some(Some(terminal))
239 } else {
240 Some(None)
241 }
242 })
243 .ok()
244 .flatten()?;
245 if let Some(terminal) = terminal {
246 let terminal = terminal.await.ok()?;
247 pane.update(cx, |pane, cx| {
248 let terminal_view = Box::new(cx.new_view(|cx| {
249 TerminalView::new(terminal, workspace.clone(), Some(workspace_id), cx)
250 }));
251 pane.add_item(terminal_view, true, false, None, cx);
252 })
253 .ok()?;
254 }
255 Some((Member::Pane(pane.clone()), active.then_some(pane)))
256 }
257 }
258}
259
260async fn deserialize_terminal_views(
261 workspace_id: WorkspaceId,
262 project: Model<Project>,
263 workspace: WeakView<Workspace>,
264 item_ids: &[u64],
265 cx: &mut AsyncWindowContext,
266) -> Vec<View<TerminalView>> {
267 let mut items = Vec::with_capacity(item_ids.len());
268 let mut deserialized_items = item_ids
269 .iter()
270 .map(|item_id| {
271 cx.update(|cx| {
272 TerminalView::deserialize(
273 project.clone(),
274 workspace.clone(),
275 workspace_id,
276 *item_id,
277 cx,
278 )
279 })
280 .unwrap_or_else(|e| Task::ready(Err(e.context("no window present"))))
281 })
282 .collect::<FuturesUnordered<_>>();
283 while let Some(item) = deserialized_items.next().await {
284 if let Some(item) = item.log_err() {
285 items.push(item);
286 }
287 }
288 items
289}
290
291#[derive(Debug, Serialize, Deserialize)]
292pub(crate) struct SerializedTerminalPanel {
293 pub items: SerializedItems,
294 // A deprecated field, kept for backwards compatibility for the code before terminal splits were introduced.
295 pub active_item_id: Option<u64>,
296 pub width: Option<Pixels>,
297 pub height: Option<Pixels>,
298}
299
300#[derive(Debug, Serialize, Deserialize)]
301#[serde(untagged)]
302pub(crate) enum SerializedItems {
303 // The data stored before terminal splits were introduced.
304 NoSplits(Vec<u64>),
305 WithSplits(SerializedPaneGroup),
306}
307
308#[derive(Debug, Serialize, Deserialize)]
309pub(crate) enum SerializedPaneGroup {
310 Pane(SerializedPane),
311 Group {
312 axis: SerializedAxis,
313 flexes: Option<Vec<f32>>,
314 children: Vec<SerializedPaneGroup>,
315 },
316}
317
318#[derive(Debug, Serialize, Deserialize)]
319pub(crate) struct SerializedPane {
320 pub active: bool,
321 pub children: Vec<u64>,
322 pub active_item: Option<u64>,
323}
324
325#[derive(Debug)]
326pub(crate) struct SerializedAxis(pub Axis);
327
328impl Serialize for SerializedAxis {
329 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
330 where
331 S: serde::Serializer,
332 {
333 match self.0 {
334 Axis::Horizontal => serializer.serialize_str("horizontal"),
335 Axis::Vertical => serializer.serialize_str("vertical"),
336 }
337 }
338}
339
340impl<'de> Deserialize<'de> for SerializedAxis {
341 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
342 where
343 D: serde::Deserializer<'de>,
344 {
345 let s = String::deserialize(deserializer)?;
346 match s.as_str() {
347 "horizontal" => Ok(SerializedAxis(Axis::Horizontal)),
348 "vertical" => Ok(SerializedAxis(Axis::Vertical)),
349 invalid => Err(serde::de::Error::custom(format!(
350 "Invalid axis value: '{invalid}'"
351 ))),
352 }
353 }
354}
355
356define_connection! {
357 pub static ref TERMINAL_DB: TerminalDb<WorkspaceDb> =
358 &[sql!(
359 CREATE TABLE terminals (
360 workspace_id INTEGER,
361 item_id INTEGER UNIQUE,
362 working_directory BLOB,
363 PRIMARY KEY(workspace_id, item_id),
364 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
365 ON DELETE CASCADE
366 ) STRICT;
367 ),
368 // Remove the unique constraint on the item_id table
369 // SQLite doesn't have a way of doing this automatically, so
370 // we have to do this silly copying.
371 sql!(
372 CREATE TABLE terminals2 (
373 workspace_id INTEGER,
374 item_id INTEGER,
375 working_directory BLOB,
376 PRIMARY KEY(workspace_id, item_id),
377 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
378 ON DELETE CASCADE
379 ) STRICT;
380
381 INSERT INTO terminals2 (workspace_id, item_id, working_directory)
382 SELECT workspace_id, item_id, working_directory FROM terminals;
383
384 DROP TABLE terminals;
385
386 ALTER TABLE terminals2 RENAME TO terminals;
387 )];
388}
389
390impl TerminalDb {
391 query! {
392 pub async fn update_workspace_id(
393 new_id: WorkspaceId,
394 old_id: WorkspaceId,
395 item_id: ItemId
396 ) -> Result<()> {
397 UPDATE terminals
398 SET workspace_id = ?
399 WHERE workspace_id = ? AND item_id = ?
400 }
401 }
402
403 query! {
404 pub async fn save_working_directory(
405 item_id: ItemId,
406 workspace_id: WorkspaceId,
407 working_directory: PathBuf
408 ) -> Result<()> {
409 INSERT OR REPLACE INTO terminals(item_id, workspace_id, working_directory)
410 VALUES (?, ?, ?)
411 }
412 }
413
414 query! {
415 pub fn get_working_directory(item_id: ItemId, workspace_id: WorkspaceId) -> Result<Option<PathBuf>> {
416 SELECT working_directory
417 FROM terminals
418 WHERE item_id = ? AND workspace_id = ?
419 }
420 }
421
422 pub async fn delete_unloaded_items(
423 &self,
424 workspace: WorkspaceId,
425 alive_items: Vec<ItemId>,
426 ) -> Result<()> {
427 let placeholders = alive_items
428 .iter()
429 .map(|_| "?")
430 .collect::<Vec<&str>>()
431 .join(", ");
432
433 let query = format!(
434 "DELETE FROM terminals WHERE workspace_id = ? AND item_id NOT IN ({placeholders})"
435 );
436
437 self.write(move |conn| {
438 let mut statement = Statement::prepare(conn, query)?;
439 let mut next_index = statement.bind(&workspace, 1)?;
440 for id in alive_items {
441 next_index = statement.bind(&id, next_index)?;
442 }
443 statement.exec()
444 })
445 .await
446 }
447}