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 let mut active_item_index = None;
151 for (index, item) in self.children.iter().enumerate() {
152 let project = project.clone();
153 let item_handle = pane_handle
154 .update(cx, |_, cx| {
155 if let Some(deserializer) = cx.global::<ItemDeserializers>().get(&item.kind) {
156 deserializer(
157 project,
158 workspace.downgrade(),
159 workspace_id,
160 item.item_id,
161 cx,
162 )
163 } else {
164 Task::ready(Err(anyhow::anyhow!(
165 "Deserializer does not exist for item kind: {}",
166 item.kind
167 )))
168 }
169 })
170 .await
171 .log_err();
172
173 if let Some(item_handle) = item_handle {
174 workspace.update(cx, |workspace, cx| {
175 Pane::add_item(workspace, &pane_handle, item_handle, false, false, None, cx);
176 })
177 }
178
179 if item.active {
180 active_item_index = Some(index);
181 }
182 }
183
184 if let Some(active_item_index) = active_item_index {
185 pane_handle.update(cx, |pane, cx| {
186 pane.activate_item(active_item_index, false, false, cx);
187 })
188 }
189 }
190}
191
192pub type GroupId = i64;
193pub type PaneId = i64;
194pub type ItemId = usize;
195
196#[derive(Debug, PartialEq, Eq, Clone)]
197pub struct SerializedItem {
198 pub kind: Arc<str>,
199 pub item_id: ItemId,
200 pub active: bool,
201}
202
203impl SerializedItem {
204 pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool) -> Self {
205 Self {
206 kind: Arc::from(kind.as_ref()),
207 item_id,
208 active,
209 }
210 }
211}
212
213#[cfg(test)]
214impl Default for SerializedItem {
215 fn default() -> Self {
216 SerializedItem {
217 kind: Arc::from("Terminal"),
218 item_id: 100000,
219 active: false,
220 }
221 }
222}
223
224impl Bind for &SerializedItem {
225 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
226 let next_index = statement.bind(self.kind.clone(), start_index)?;
227 let next_index = statement.bind(self.item_id, next_index)?;
228 statement.bind(self.active, next_index)
229 }
230}
231
232impl Column for SerializedItem {
233 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
234 let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
235 let (item_id, next_index) = ItemId::column(statement, next_index)?;
236 let (active, next_index) = bool::column(statement, next_index)?;
237 Ok((
238 SerializedItem {
239 kind,
240 item_id,
241 active,
242 },
243 next_index,
244 ))
245 }
246}
247
248impl Bind for DockPosition {
249 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
250 let next_index = statement.bind(self.is_visible(), start_index)?;
251 statement.bind(self.anchor(), next_index)
252 }
253}
254
255impl Column for DockPosition {
256 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
257 let (visible, next_index) = bool::column(statement, start_index)?;
258 let (dock_anchor, next_index) = DockAnchor::column(statement, next_index)?;
259 let position = if visible {
260 DockPosition::Shown(dock_anchor)
261 } else {
262 DockPosition::Hidden(dock_anchor)
263 };
264 Ok((position, next_index))
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use db::sqlez::connection::Connection;
271 use settings::DockAnchor;
272
273 use super::WorkspaceLocation;
274
275 #[test]
276 fn test_workspace_round_trips() {
277 let db = Connection::open_memory(Some("workspace_id_round_trips"));
278
279 db.exec(indoc::indoc! {"
280 CREATE TABLE workspace_id_test(
281 workspace_id INTEGER,
282 dock_anchor TEXT
283 );"})
284 .unwrap()()
285 .unwrap();
286
287 let workspace_id: WorkspaceLocation = WorkspaceLocation::from(&["\test2", "\test1"]);
288
289 db.exec_bound("INSERT INTO workspace_id_test(workspace_id, dock_anchor) VALUES (?,?)")
290 .unwrap()((&workspace_id, DockAnchor::Bottom))
291 .unwrap();
292
293 assert_eq!(
294 db.select_row("SELECT workspace_id, dock_anchor FROM workspace_id_test LIMIT 1")
295 .unwrap()()
296 .unwrap(),
297 Some((
298 WorkspaceLocation::from(&["\test1", "\test2"]),
299 DockAnchor::Bottom
300 ))
301 );
302 }
303}