1use std::{
2 path::{Path, PathBuf},
3 sync::Arc,
4};
5
6use anyhow::{Context, Result};
7
8use async_recursion::async_recursion;
9use gpui::{AsyncAppContext, Axis, ModelHandle, Task, ViewHandle};
10
11use db::sqlez::{
12 bindable::{Bind, Column},
13 statement::Statement,
14};
15use project::Project;
16use settings::DockAnchor;
17use util::ResultExt;
18
19use crate::{
20 dock::DockPosition, ItemDeserializers, Member, Pane, PaneAxis, Workspace, WorkspaceId,
21};
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct WorkspaceLocation(Arc<Vec<PathBuf>>);
25
26impl WorkspaceLocation {
27 pub fn paths(&self) -> Arc<Vec<PathBuf>> {
28 self.0.clone()
29 }
30}
31
32impl<P: AsRef<Path>, T: IntoIterator<Item = P>> From<T> for WorkspaceLocation {
33 fn from(iterator: T) -> Self {
34 let mut roots = iterator
35 .into_iter()
36 .map(|p| p.as_ref().to_path_buf())
37 .collect::<Vec<_>>();
38 roots.sort();
39 Self(Arc::new(roots))
40 }
41}
42
43impl Bind for &WorkspaceLocation {
44 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
45 bincode::serialize(&self.0)
46 .expect("Bincode serialization of paths should not fail")
47 .bind(statement, start_index)
48 }
49}
50
51impl Column for WorkspaceLocation {
52 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
53 let blob = statement.column_blob(start_index)?;
54 Ok((
55 WorkspaceLocation(bincode::deserialize(blob).context("Bincode failed")?),
56 start_index + 1,
57 ))
58 }
59}
60
61#[derive(Debug, PartialEq, Eq, Clone)]
62pub struct SerializedWorkspace {
63 pub id: WorkspaceId,
64 pub location: WorkspaceLocation,
65 pub dock_position: DockPosition,
66 pub center_group: SerializedPaneGroup,
67 pub dock_pane: SerializedPane,
68}
69
70#[derive(Debug, PartialEq, Eq, Clone)]
71pub enum SerializedPaneGroup {
72 Group {
73 axis: Axis,
74 children: Vec<SerializedPaneGroup>,
75 },
76 Pane(SerializedPane),
77}
78
79#[cfg(test)]
80impl Default for SerializedPaneGroup {
81 fn default() -> Self {
82 Self::Pane(SerializedPane {
83 children: vec![SerializedItem::default()],
84 active: false,
85 })
86 }
87}
88
89impl SerializedPaneGroup {
90 #[async_recursion(?Send)]
91 pub(crate) async fn deserialize(
92 &self,
93 project: &ModelHandle<Project>,
94 workspace_id: WorkspaceId,
95 workspace: &ViewHandle<Workspace>,
96 cx: &mut AsyncAppContext,
97 ) -> (Member, Option<ViewHandle<Pane>>) {
98 match self {
99 SerializedPaneGroup::Group { axis, children } => {
100 let mut current_active_pane = None;
101 let mut members = Vec::new();
102 for child in children {
103 let (new_member, active_pane) = child
104 .deserialize(project, workspace_id, workspace, cx)
105 .await;
106 members.push(new_member);
107
108 current_active_pane = current_active_pane.or(active_pane);
109 }
110 (
111 Member::Axis(PaneAxis {
112 axis: *axis,
113 members,
114 }),
115 current_active_pane,
116 )
117 }
118 SerializedPaneGroup::Pane(serialized_pane) => {
119 let pane = workspace.update(cx, |workspace, cx| workspace.add_pane(cx));
120 let active = serialized_pane.active;
121 serialized_pane
122 .deserialize_to(project, &pane, workspace_id, workspace, cx)
123 .await;
124
125 (Member::Pane(pane.clone()), active.then(|| pane))
126 }
127 }
128 }
129}
130
131#[derive(Debug, PartialEq, Eq, Default, Clone)]
132pub struct SerializedPane {
133 pub(crate) active: bool,
134 pub(crate) children: Vec<SerializedItem>,
135}
136
137impl SerializedPane {
138 pub fn new(children: Vec<SerializedItem>, active: bool) -> Self {
139 SerializedPane { children, active }
140 }
141
142 pub async fn deserialize_to(
143 &self,
144 project: &ModelHandle<Project>,
145 pane_handle: &ViewHandle<Pane>,
146 workspace_id: WorkspaceId,
147 workspace: &ViewHandle<Workspace>,
148 cx: &mut AsyncAppContext,
149 ) {
150 for item in self.children.iter() {
151 let project = project.clone();
152 let item_handle = pane_handle
153 .update(cx, |_, cx| {
154 if let Some(deserializer) = cx.global::<ItemDeserializers>().get(&item.kind) {
155 deserializer(
156 project,
157 workspace.downgrade(),
158 workspace_id,
159 item.item_id,
160 cx,
161 )
162 } else {
163 Task::ready(Err(anyhow::anyhow!(
164 "Deserializer does not exist for item kind: {}",
165 item.kind
166 )))
167 }
168 })
169 .await
170 .log_err();
171
172 if let Some(item_handle) = item_handle {
173 workspace.update(cx, |workspace, cx| {
174 Pane::add_item(workspace, &pane_handle, item_handle, false, false, None, cx);
175 })
176 }
177 }
178 }
179}
180
181pub type GroupId = i64;
182pub type PaneId = i64;
183pub type ItemId = usize;
184
185#[derive(Debug, PartialEq, Eq, Clone)]
186pub struct SerializedItem {
187 pub kind: Arc<str>,
188 pub item_id: ItemId,
189}
190
191impl SerializedItem {
192 pub fn new(kind: impl AsRef<str>, item_id: ItemId) -> Self {
193 Self {
194 kind: Arc::from(kind.as_ref()),
195 item_id,
196 }
197 }
198}
199
200#[cfg(test)]
201impl Default for SerializedItem {
202 fn default() -> Self {
203 SerializedItem {
204 kind: Arc::from("Terminal"),
205 item_id: 100000,
206 }
207 }
208}
209
210impl Bind for &SerializedItem {
211 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
212 let next_index = statement.bind(self.kind.clone(), start_index)?;
213 statement.bind(self.item_id, next_index)
214 }
215}
216
217impl Column for SerializedItem {
218 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
219 let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
220 let (item_id, next_index) = ItemId::column(statement, next_index)?;
221 Ok((SerializedItem { kind, item_id }, next_index))
222 }
223}
224
225impl Bind for DockPosition {
226 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
227 let next_index = statement.bind(self.is_visible(), start_index)?;
228 statement.bind(self.anchor(), next_index)
229 }
230}
231
232impl Column for DockPosition {
233 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
234 let (visible, next_index) = bool::column(statement, start_index)?;
235 let (dock_anchor, next_index) = DockAnchor::column(statement, next_index)?;
236 let position = if visible {
237 DockPosition::Shown(dock_anchor)
238 } else {
239 DockPosition::Hidden(dock_anchor)
240 };
241 Ok((position, next_index))
242 }
243}
244
245#[cfg(test)]
246mod tests {
247 use db::sqlez::connection::Connection;
248 use settings::DockAnchor;
249
250 use super::WorkspaceLocation;
251
252 #[test]
253 fn test_workspace_round_trips() {
254 let db = Connection::open_memory(Some("workspace_id_round_trips"));
255
256 db.exec(indoc::indoc! {"
257 CREATE TABLE workspace_id_test(
258 workspace_id INTEGER,
259 dock_anchor TEXT
260 );"})
261 .unwrap()()
262 .unwrap();
263
264 let workspace_id: WorkspaceLocation = WorkspaceLocation::from(&["\test2", "\test1"]);
265
266 db.exec_bound("INSERT INTO workspace_id_test(workspace_id, dock_anchor) VALUES (?,?)")
267 .unwrap()((&workspace_id, DockAnchor::Bottom))
268 .unwrap();
269
270 assert_eq!(
271 db.select_row("SELECT workspace_id, dock_anchor FROM workspace_id_test LIMIT 1")
272 .unwrap()()
273 .unwrap(),
274 Some((
275 WorkspaceLocation::from(&["\test1", "\test2"]),
276 DockAnchor::Bottom
277 ))
278 );
279 }
280}