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