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