1#![allow(dead_code)]
2
3pub mod model;
4
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use anyhow::{anyhow, bail, Result, Context};
9use db::connection;
10use gpui::Axis;
11use indoc::indoc;
12
13
14use db::sqlez::domain::Domain;
15use util::{iife, unzip_option, ResultExt};
16
17use crate::dock::DockPosition;
18
19use super::Workspace;
20
21use model::{
22 GroupId, PaneId, SerializedItem, SerializedPane, SerializedPaneGroup,
23 SerializedWorkspace, WorkspaceId,
24};
25
26connection!(DB: WorkspaceDb<Workspace>);
27
28
29impl Domain for Workspace {
30 fn name() -> &'static str {
31 "workspace"
32 }
33
34 fn migrations() -> &'static [&'static str] {
35 &[indoc! {"
36 CREATE TABLE workspaces(
37 workspace_id BLOB PRIMARY KEY,
38 dock_visible INTEGER, -- Boolean
39 dock_anchor TEXT, -- Enum: 'Bottom' / 'Right' / 'Expanded'
40 dock_pane INTEGER, -- NULL indicates that we don't have a dock pane yet
41 timestamp TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,
42 FOREIGN KEY(dock_pane) REFERENCES panes(pane_id)
43 ) STRICT;
44
45 CREATE TABLE pane_groups(
46 group_id INTEGER PRIMARY KEY,
47 workspace_id BLOB NOT NULL,
48 parent_group_id INTEGER, -- NULL indicates that this is a root node
49 position INTEGER, -- NULL indicates that this is a root node
50 axis TEXT NOT NULL, -- Enum: 'Vertical' / 'Horizontal'
51 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
52 ON DELETE CASCADE
53 ON UPDATE CASCADE,
54 FOREIGN KEY(parent_group_id) REFERENCES pane_groups(group_id) ON DELETE CASCADE
55 ) STRICT;
56
57 CREATE TABLE panes(
58 pane_id INTEGER PRIMARY KEY,
59 workspace_id BLOB NOT NULL,
60 active INTEGER NOT NULL, -- Boolean
61 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
62 ON DELETE CASCADE
63 ON UPDATE CASCADE
64 ) STRICT;
65
66 CREATE TABLE center_panes(
67 pane_id INTEGER PRIMARY KEY,
68 parent_group_id INTEGER, -- NULL means that this is a root pane
69 position INTEGER, -- NULL means that this is a root pane
70 FOREIGN KEY(pane_id) REFERENCES panes(pane_id)
71 ON DELETE CASCADE,
72 FOREIGN KEY(parent_group_id) REFERENCES pane_groups(group_id) ON DELETE CASCADE
73 ) STRICT;
74
75 CREATE TABLE items(
76 item_id INTEGER NOT NULL, -- This is the item's view id, so this is not unique
77 workspace_id BLOB NOT NULL,
78 pane_id INTEGER NOT NULL,
79 kind TEXT NOT NULL,
80 position INTEGER NOT NULL,
81 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
82 ON DELETE CASCADE
83 ON UPDATE CASCADE,
84 FOREIGN KEY(pane_id) REFERENCES panes(pane_id)
85 ON DELETE CASCADE,
86 PRIMARY KEY(item_id, workspace_id)
87 ) STRICT;
88 "}]
89 }
90}
91
92impl WorkspaceDb {
93 /// Returns a serialized workspace for the given worktree_roots. If the passed array
94 /// is empty, the most recent workspace is returned instead. If no workspace for the
95 /// passed roots is stored, returns none.
96 pub fn workspace_for_roots<P: AsRef<Path>>(
97 &self,
98 worktree_roots: &[P],
99 ) -> Option<SerializedWorkspace> {
100 let workspace_id: WorkspaceId = worktree_roots.into();
101
102 // Note that we re-assign the workspace_id here in case it's empty
103 // and we've grabbed the most recent workspace
104 let (workspace_id, dock_position): (WorkspaceId, DockPosition) = iife!({
105 if worktree_roots.len() == 0 {
106 self.select_row(indoc! {"
107 SELECT workspace_id, dock_visible, dock_anchor
108 FROM workspaces
109 ORDER BY timestamp DESC LIMIT 1"})?()?
110 } else {
111 self.select_row_bound(indoc! {"
112 SELECT workspace_id, dock_visible, dock_anchor
113 FROM workspaces
114 WHERE workspace_id = ?"})?(&workspace_id)?
115 }
116 .context("No workspaces found")
117 })
118 .warn_on_err()
119 .flatten()?;
120
121 Some(SerializedWorkspace {
122 workspace_id: workspace_id.clone(),
123 dock_pane: self
124 .get_dock_pane(&workspace_id)
125 .context("Getting dock pane")
126 .log_err()?,
127 center_group: self
128 .get_center_pane_group(&workspace_id)
129 .context("Getting center group")
130 .log_err()?,
131 dock_position,
132 })
133 }
134
135 /// Saves a workspace using the worktree roots. Will garbage collect any workspaces
136 /// that used this workspace previously
137 pub fn save_workspace(
138 &self,
139 old_id: Option<WorkspaceId>,
140 workspace: &SerializedWorkspace,
141 ) {
142 self.with_savepoint("update_worktrees", || {
143 self.exec_bound(indoc! {"
144 UPDATE workspaces SET dock_pane = NULL WHERE workspace_id = ?1;
145 DELETE FROM pane_groups WHERE workspace_id = ?1;
146 DELETE FROM panes WHERE workspace_id = ?1;"})?
147 (old_id.as_ref().unwrap_or(&workspace.workspace_id)).context("Clearing old panes")?;
148
149 if let Some(old_id) = old_id {
150 self.exec_bound(indoc! {"
151 UPDATE OR REPLACE workspaces
152 SET workspace_id = ?,
153 dock_visible = ?,
154 dock_anchor = ?,
155 timestamp = CURRENT_TIMESTAMP
156 WHERE workspace_id = ?"})?((
157 &workspace.workspace_id,
158 workspace.dock_position,
159 &old_id,
160 )).context("Updating workspace with new worktree roots")?;
161 } else {
162 self.exec_bound(
163 "INSERT OR REPLACE INTO workspaces(workspace_id, dock_visible, dock_anchor) VALUES (?, ?, ?)",
164 )?((&workspace.workspace_id, workspace.dock_position)).context("Uodating workspace")?;
165 }
166
167 // Save center pane group and dock pane
168 self.save_pane_group(&workspace.workspace_id, &workspace.center_group, None).context("save pane group in save workspace")?;
169
170 let dock_id = self.save_pane(&workspace.workspace_id, &workspace.dock_pane, None, true).context("save pane in save workspace")?;
171
172 // Complete workspace initialization
173 self.exec_bound(indoc! {"
174 UPDATE workspaces
175 SET dock_pane = ?
176 WHERE workspace_id = ?"})?((
177 dock_id,
178 &workspace.workspace_id,
179 )).context("Finishing initialization with dock pane")?;
180
181 Ok(())
182 })
183 .with_context(|| {
184 format!(
185 "Update workspace with roots {:?} failed.",
186 workspace.workspace_id.paths()
187 )
188 })
189 .log_err();
190 }
191
192 /// Returns the previous workspace ids sorted by last modified along with their opened worktree roots
193 pub fn recent_workspaces(&self, limit: usize) -> Vec<Arc<Vec<PathBuf>>> {
194 iife!({
195 // TODO, upgrade anyhow: https://docs.rs/anyhow/1.0.66/anyhow/fn.Ok.html
196 Ok::<_, anyhow::Error>(
197 self.select_bound::<usize, WorkspaceId>(
198 "SELECT workspace_id FROM workspaces ORDER BY timestamp DESC LIMIT ?",
199 )?(limit)?
200 .into_iter()
201 .map(|id| id.paths())
202 .collect::<Vec<Arc<Vec<PathBuf>>>>(),
203 )
204 })
205 .log_err()
206 .unwrap_or_default()
207 }
208
209 pub(crate) fn get_center_pane_group(
210 &self,
211 workspace_id: &WorkspaceId,
212 ) -> Result<SerializedPaneGroup> {
213 self.get_pane_group(workspace_id, None)?
214 .into_iter()
215 .next()
216 .context("No center pane group")
217 }
218
219 fn get_pane_group(
220 &self,
221 workspace_id: &WorkspaceId,
222 group_id: Option<GroupId>,
223 ) -> Result<Vec<SerializedPaneGroup>> {
224 type GroupKey<'a> = (Option<GroupId>, &'a WorkspaceId);
225 type GroupOrPane = (Option<GroupId>, Option<Axis>, Option<PaneId>, Option<bool>);
226 self.select_bound::<GroupKey, GroupOrPane>(indoc! {"
227 SELECT group_id, axis, pane_id, active
228 FROM (SELECT
229 group_id,
230 axis,
231 NULL as pane_id,
232 NULL as active,
233 position,
234 parent_group_id,
235 workspace_id
236 FROM pane_groups
237 UNION
238 SELECT
239 NULL,
240 NULL,
241 center_panes.pane_id,
242 panes.active as active,
243 position,
244 parent_group_id,
245 panes.workspace_id as workspace_id
246 FROM center_panes
247 JOIN panes ON center_panes.pane_id = panes.pane_id)
248 WHERE parent_group_id IS ? AND workspace_id = ?
249 ORDER BY position
250 "})?((group_id, workspace_id))?
251 .into_iter()
252 .map(|(group_id, axis, pane_id, active)| {
253 if let Some((group_id, axis)) = group_id.zip(axis) {
254 Ok(SerializedPaneGroup::Group {
255 axis,
256 children: self.get_pane_group(
257 workspace_id,
258 Some(group_id),
259 )?,
260 })
261 } else if let Some((pane_id, active)) = pane_id.zip(active) {
262 Ok(SerializedPaneGroup::Pane(SerializedPane::new(self.get_items( pane_id)?, active)))
263 } else {
264 bail!("Pane Group Child was neither a pane group or a pane");
265 }
266 })
267 // Filter out panes and pane groups which don't have any children or items
268 .filter(|pane_group| {
269 match pane_group {
270 Ok(SerializedPaneGroup::Group { children, .. }) => !children.is_empty(),
271 Ok(SerializedPaneGroup::Pane(pane)) => !pane.children.is_empty(),
272 _ => true,
273 }
274 })
275 .collect::<Result<_>>()
276 }
277
278 pub(crate) fn save_pane_group(
279 &self,
280 workspace_id: &WorkspaceId,
281 pane_group: &SerializedPaneGroup,
282 parent: Option<(GroupId, usize)>,
283 ) -> Result<()> {
284 match pane_group {
285 SerializedPaneGroup::Group { axis, children } => {
286 let (parent_id, position) = unzip_option(parent);
287
288 let group_id = self.select_row_bound::<_, i64>(indoc!{"
289 INSERT INTO pane_groups(workspace_id, parent_group_id, position, axis)
290 VALUES (?, ?, ?, ?)
291 RETURNING group_id"})?
292 ((workspace_id, parent_id, position, *axis))?
293 .ok_or_else(|| anyhow!("Couldn't retrieve group_id from inserted pane_group"))?;
294
295 for (position, group) in children.iter().enumerate() {
296 self.save_pane_group(workspace_id, group, Some((group_id, position)))?
297 }
298 Ok(())
299 }
300 SerializedPaneGroup::Pane(pane) => {
301 self.save_pane(workspace_id, &pane, parent, false)?;
302 Ok(())
303 },
304 }
305 }
306
307 pub(crate) fn get_dock_pane(&self, workspace_id: &WorkspaceId) -> Result<SerializedPane> {
308 let (pane_id, active) = self.select_row_bound(indoc! {"
309 SELECT pane_id, active
310 FROM panes
311 WHERE pane_id = (SELECT dock_pane FROM workspaces WHERE workspace_id = ?)"})?(
312 workspace_id,
313 )?
314 .context("No dock pane for workspace")?;
315
316 Ok(SerializedPane::new(
317 self.get_items(pane_id).context("Reading items")?,
318 active
319 ))
320 }
321
322 pub(crate) fn save_pane(
323 &self,
324 workspace_id: &WorkspaceId,
325 pane: &SerializedPane,
326 parent: Option<(GroupId, usize)>, // None indicates BOTH dock pane AND center_pane
327 dock: bool,
328 ) -> Result<PaneId> {
329 let pane_id = self.select_row_bound::<_, i64>(indoc!{"
330 INSERT INTO panes(workspace_id, active)
331 VALUES (?, ?)
332 RETURNING pane_id"},
333 )?((workspace_id, pane.active))?
334 .ok_or_else(|| anyhow!("Could not retrieve inserted pane_id"))?;
335
336 if !dock {
337 let (parent_id, order) = unzip_option(parent);
338 self.exec_bound(indoc! {"
339 INSERT INTO center_panes(pane_id, parent_group_id, position)
340 VALUES (?, ?, ?)"})?((
341 pane_id, parent_id, order
342 ))?;
343 }
344
345 self.save_items(workspace_id, pane_id, &pane.children)
346 .context("Saving items")?;
347
348 Ok(pane_id)
349 }
350
351
352
353 pub(crate) fn get_items(&self, pane_id: PaneId) -> Result<Vec<SerializedItem>> {
354 Ok(self.select_bound(indoc! {"
355 SELECT kind, item_id FROM items
356 WHERE pane_id = ?
357 ORDER BY position"})?(pane_id)?)
358 }
359
360 pub(crate) fn save_items(
361 &self,
362 workspace_id: &WorkspaceId,
363 pane_id: PaneId,
364 items: &[SerializedItem],
365 ) -> Result<()> {
366 let mut insert = self.exec_bound(
367 "INSERT INTO items(workspace_id, pane_id, position, kind, item_id) VALUES (?, ?, ?, ?, ?)",
368 ).context("Preparing insertion")?;
369 for (position, item) in items.iter().enumerate() {
370 insert((workspace_id, pane_id, position, item))?;
371 }
372
373 Ok(())
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 use db::{open_memory_db};
380 use settings::DockAnchor;
381
382 use super::*;
383
384 #[test]
385 fn test_full_workspace_serialization() {
386 env_logger::try_init().ok();
387
388 let db = WorkspaceDb(open_memory_db(Some("test_full_workspace_serialization")));
389
390 let dock_pane = crate::persistence::model::SerializedPane {
391
392 children: vec![
393 SerializedItem::new("Terminal", 1),
394 SerializedItem::new("Terminal", 2),
395 SerializedItem::new("Terminal", 3),
396 SerializedItem::new("Terminal", 4),
397
398 ],
399 active: false
400 };
401
402 // -----------------
403 // | 1,2 | 5,6 |
404 // | - - - | |
405 // | 3,4 | |
406 // -----------------
407 let center_group = SerializedPaneGroup::Group {
408 axis: gpui::Axis::Horizontal,
409 children: vec![
410 SerializedPaneGroup::Group {
411 axis: gpui::Axis::Vertical,
412 children: vec![
413 SerializedPaneGroup::Pane(SerializedPane::new(
414 vec![
415 SerializedItem::new("Terminal", 5),
416 SerializedItem::new("Terminal", 6),
417 ],
418 false)
419 ),
420 SerializedPaneGroup::Pane(SerializedPane::new(
421 vec![
422 SerializedItem::new("Terminal", 7),
423 SerializedItem::new("Terminal", 8),
424 ],
425 false,
426 )),
427 ],
428 },
429 SerializedPaneGroup::Pane(SerializedPane::new(
430 vec![
431 SerializedItem::new("Terminal", 9),
432 SerializedItem::new("Terminal", 10),
433
434 ],
435 false,
436 )),
437 ],
438 };
439
440 let workspace = SerializedWorkspace {
441 workspace_id: (["/tmp", "/tmp2"]).into(),
442 dock_position: DockPosition::Shown(DockAnchor::Bottom),
443 center_group,
444 dock_pane,
445 };
446
447 db.save_workspace(None, &workspace);
448 let round_trip_workspace = db.workspace_for_roots(&["/tmp2", "/tmp"]);
449
450 assert_eq!(workspace, round_trip_workspace.unwrap());
451
452 // Test guaranteed duplicate IDs
453 db.save_workspace(None, &workspace);
454 db.save_workspace(None, &workspace);
455
456 let round_trip_workspace = db.workspace_for_roots(&["/tmp", "/tmp2"]);
457 assert_eq!(workspace, round_trip_workspace.unwrap());
458
459
460 }
461
462 #[test]
463 fn test_workspace_assignment() {
464 env_logger::try_init().ok();
465
466 let db = WorkspaceDb(open_memory_db(Some("test_basic_functionality")));
467
468 let workspace_1 = SerializedWorkspace {
469 workspace_id: (["/tmp", "/tmp2"]).into(),
470 dock_position: crate::dock::DockPosition::Shown(DockAnchor::Bottom),
471 center_group: Default::default(),
472 dock_pane: Default::default(),
473 };
474
475 let mut workspace_2 = SerializedWorkspace {
476 workspace_id: (["/tmp"]).into(),
477 dock_position: crate::dock::DockPosition::Hidden(DockAnchor::Expanded),
478 center_group: Default::default(),
479 dock_pane: Default::default(),
480 };
481
482 db.save_workspace(None, &workspace_1);
483 db.save_workspace(None, &workspace_2);
484
485 // Test that paths are treated as a set
486 assert_eq!(
487 db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(),
488 workspace_1
489 );
490 assert_eq!(
491 db.workspace_for_roots(&["/tmp2", "/tmp"]).unwrap(),
492 workspace_1
493 );
494
495 // Make sure that other keys work
496 assert_eq!(db.workspace_for_roots(&["/tmp"]).unwrap(), workspace_2);
497 assert_eq!(db.workspace_for_roots(&["/tmp3", "/tmp2", "/tmp4"]), None);
498
499 // Test 'mutate' case of updating a pre-existing id
500 workspace_2.workspace_id = (["/tmp", "/tmp2"]).into();
501 db.save_workspace(Some((&["/tmp"]).into()), &workspace_2);
502 assert_eq!(
503 db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(),
504 workspace_2
505 );
506
507 // Test other mechanism for mutating
508 let mut workspace_3 = SerializedWorkspace {
509 workspace_id: (&["/tmp", "/tmp2"]).into(),
510 dock_position: DockPosition::Shown(DockAnchor::Right),
511 center_group: Default::default(),
512 dock_pane: Default::default(),
513 };
514
515
516 db.save_workspace(None, &workspace_3);
517 assert_eq!(
518 db.workspace_for_roots(&["/tmp", "/tmp2"]).unwrap(),
519 workspace_3
520 );
521
522 // Make sure that updating paths differently also works
523 workspace_3.workspace_id = (["/tmp3", "/tmp4", "/tmp2"]).into();
524 db.save_workspace(
525 Some((&["/tmp", "/tmp2"]).into()),
526 &workspace_3,
527 );
528 assert_eq!(db.workspace_for_roots(&["/tmp2", "tmp"]), None);
529 assert_eq!(
530 db.workspace_for_roots(&["/tmp2", "/tmp3", "/tmp4"])
531 .unwrap(),
532 workspace_3
533 );
534
535
536 }
537
538 use crate::dock::DockPosition;
539 use crate::persistence::model::SerializedWorkspace;
540 use crate::persistence::model::{SerializedItem, SerializedPane, SerializedPaneGroup};
541
542 fn default_workspace<P: AsRef<Path>>(
543 workspace_id: &[P],
544 dock_pane: SerializedPane,
545 center_group: &SerializedPaneGroup,
546 ) -> SerializedWorkspace {
547 SerializedWorkspace {
548 workspace_id: workspace_id.into(),
549 dock_position: crate::dock::DockPosition::Hidden(DockAnchor::Right),
550 center_group: center_group.clone(),
551 dock_pane,
552 }
553 }
554
555 #[test]
556 fn test_basic_dock_pane() {
557 env_logger::try_init().ok();
558
559 let db = WorkspaceDb(open_memory_db(Some("basic_dock_pane")));
560
561 let dock_pane = crate::persistence::model::SerializedPane::new(
562 vec![
563 SerializedItem::new("Terminal", 1),
564 SerializedItem::new("Terminal", 4),
565 SerializedItem::new("Terminal", 2),
566 SerializedItem::new("Terminal", 3),
567 ], false
568 );
569
570 let workspace = default_workspace(&["/tmp"], dock_pane, &Default::default());
571
572 db.save_workspace(None, &workspace);
573
574 let new_workspace = db.workspace_for_roots(&["/tmp"]).unwrap();
575
576 assert_eq!(workspace.dock_pane, new_workspace.dock_pane);
577 }
578
579 #[test]
580 fn test_simple_split() {
581 env_logger::try_init().ok();
582
583 let db = WorkspaceDb(open_memory_db(Some("simple_split")));
584
585 // -----------------
586 // | 1,2 | 5,6 |
587 // | - - - | |
588 // | 3,4 | |
589 // -----------------
590 let center_pane = SerializedPaneGroup::Group {
591 axis: gpui::Axis::Horizontal,
592 children: vec![
593 SerializedPaneGroup::Group {
594 axis: gpui::Axis::Vertical,
595 children: vec![
596 SerializedPaneGroup::Pane(SerializedPane::new(
597 vec![
598 SerializedItem::new("Terminal", 1),
599 SerializedItem::new("Terminal", 2),
600 ],
601 false)),
602 SerializedPaneGroup::Pane(SerializedPane::new(vec![
603 SerializedItem::new("Terminal", 4),
604 SerializedItem::new("Terminal", 3),
605 ], true)),
606 ],
607 },
608 SerializedPaneGroup::Pane(SerializedPane::new(
609 vec![
610 SerializedItem::new("Terminal", 5),
611 SerializedItem::new("Terminal", 6),
612 ],
613 false)),
614 ],
615 };
616
617 let workspace = default_workspace(&["/tmp"], Default::default(), ¢er_pane);
618
619 db.save_workspace(None, &workspace);
620
621 let new_workspace = db.workspace_for_roots(&["/tmp"]).unwrap();
622
623 assert_eq!(workspace.center_group, new_workspace.center_group);
624 }
625
626 #[test]
627 fn test_cleanup_panes() {
628 env_logger::try_init().ok();
629
630 let db = WorkspaceDb(open_memory_db(Some("test_cleanup_panes")));
631
632 let center_pane = SerializedPaneGroup::Group {
633 axis: gpui::Axis::Horizontal,
634 children: vec![
635 SerializedPaneGroup::Group {
636 axis: gpui::Axis::Vertical,
637 children: vec![
638 SerializedPaneGroup::Pane(SerializedPane::new(
639 vec![
640 SerializedItem::new("Terminal", 1),
641 SerializedItem::new("Terminal", 2),
642 ],
643 false)),
644 SerializedPaneGroup::Pane(SerializedPane::new(vec![
645 SerializedItem::new("Terminal", 4),
646 SerializedItem::new("Terminal", 3),
647 ], true)),
648 ],
649 },
650 SerializedPaneGroup::Pane(SerializedPane::new(
651 vec![
652 SerializedItem::new("Terminal", 5),
653 SerializedItem::new("Terminal", 6),
654 ],
655 false)),
656 ],
657 };
658
659 let id = &["/tmp"];
660
661 let mut workspace = default_workspace(id, Default::default(), ¢er_pane);
662
663 db.save_workspace(None, &workspace);
664
665 workspace.center_group = SerializedPaneGroup::Group {
666 axis: gpui::Axis::Vertical,
667 children: vec![
668 SerializedPaneGroup::Pane(SerializedPane::new(
669 vec![
670 SerializedItem::new("Terminal", 1),
671 SerializedItem::new("Terminal", 2),
672 ],
673 false)),
674 SerializedPaneGroup::Pane(SerializedPane::new(vec![
675 SerializedItem::new("Terminal", 4),
676 SerializedItem::new("Terminal", 3),
677 ], true)),
678 ],
679 };
680
681 db.save_workspace(None, &workspace);
682
683 let new_workspace = db.workspace_for_roots(id).unwrap();
684
685 assert_eq!(workspace.center_group, new_workspace.center_group);
686
687 }
688}