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 pub left_sidebar_open: bool,
69}
70
71#[derive(Debug, PartialEq, Eq, Clone)]
72pub enum SerializedPaneGroup {
73 Group {
74 axis: Axis,
75 children: Vec<SerializedPaneGroup>,
76 },
77 Pane(SerializedPane),
78}
79
80#[cfg(test)]
81impl Default for SerializedPaneGroup {
82 fn default() -> Self {
83 Self::Pane(SerializedPane {
84 children: vec![SerializedItem::default()],
85 active: false,
86 })
87 }
88}
89
90impl SerializedPaneGroup {
91 #[async_recursion(?Send)]
92 pub(crate) async fn deserialize(
93 &self,
94 project: &ModelHandle<Project>,
95 workspace_id: WorkspaceId,
96 workspace: &ViewHandle<Workspace>,
97 cx: &mut AsyncAppContext,
98 ) -> Option<(Member, Option<ViewHandle<Pane>>)> {
99 match self {
100 SerializedPaneGroup::Group { axis, children } => {
101 let mut current_active_pane = None;
102 let mut members = Vec::new();
103 for child in children {
104 if let Some((new_member, active_pane)) = child
105 .deserialize(project, workspace_id, workspace, cx)
106 .await
107 {
108 members.push(new_member);
109 current_active_pane = current_active_pane.or(active_pane);
110 }
111 }
112
113 if members.is_empty() {
114 return None;
115 }
116
117 if members.len() == 1 {
118 return Some((members.remove(0), current_active_pane));
119 }
120
121 Some((
122 Member::Axis(PaneAxis {
123 axis: *axis,
124 members,
125 }),
126 current_active_pane,
127 ))
128 }
129 SerializedPaneGroup::Pane(serialized_pane) => {
130 let pane = workspace.update(cx, |workspace, cx| workspace.add_pane(cx));
131 let active = serialized_pane.active;
132 serialized_pane
133 .deserialize_to(project, &pane, workspace_id, workspace, cx)
134 .await;
135
136 if pane.read_with(cx, |pane, _| pane.items_len() != 0) {
137 Some((Member::Pane(pane.clone()), active.then(|| pane)))
138 } else {
139 workspace.update(cx, |workspace, cx| workspace.remove_pane(pane, cx));
140 None
141 }
142 }
143 }
144 }
145}
146
147#[derive(Debug, PartialEq, Eq, Default, Clone)]
148pub struct SerializedPane {
149 pub(crate) active: bool,
150 pub(crate) children: Vec<SerializedItem>,
151}
152
153impl SerializedPane {
154 pub fn new(children: Vec<SerializedItem>, active: bool) -> Self {
155 SerializedPane { children, active }
156 }
157
158 pub async fn deserialize_to(
159 &self,
160 project: &ModelHandle<Project>,
161 pane_handle: &ViewHandle<Pane>,
162 workspace_id: WorkspaceId,
163 workspace: &ViewHandle<Workspace>,
164 cx: &mut AsyncAppContext,
165 ) {
166 let mut active_item_index = None;
167 for (index, item) in self.children.iter().enumerate() {
168 let project = project.clone();
169 let item_handle = pane_handle
170 .update(cx, |_, cx| {
171 if let Some(deserializer) = cx.global::<ItemDeserializers>().get(&item.kind) {
172 deserializer(
173 project,
174 workspace.downgrade(),
175 workspace_id,
176 item.item_id,
177 cx,
178 )
179 } else {
180 Task::ready(Err(anyhow::anyhow!(
181 "Deserializer does not exist for item kind: {}",
182 item.kind
183 )))
184 }
185 })
186 .await
187 .log_err();
188
189 if let Some(item_handle) = item_handle {
190 workspace.update(cx, |workspace, cx| {
191 Pane::add_item(workspace, &pane_handle, item_handle, false, false, None, cx);
192 })
193 }
194
195 if item.active {
196 active_item_index = Some(index);
197 }
198 }
199
200 if let Some(active_item_index) = active_item_index {
201 pane_handle.update(cx, |pane, cx| {
202 pane.activate_item(active_item_index, false, false, cx);
203 })
204 }
205 }
206}
207
208pub type GroupId = i64;
209pub type PaneId = i64;
210pub type ItemId = usize;
211
212#[derive(Debug, PartialEq, Eq, Clone)]
213pub struct SerializedItem {
214 pub kind: Arc<str>,
215 pub item_id: ItemId,
216 pub active: bool,
217}
218
219impl SerializedItem {
220 pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool) -> Self {
221 Self {
222 kind: Arc::from(kind.as_ref()),
223 item_id,
224 active,
225 }
226 }
227}
228
229#[cfg(test)]
230impl Default for SerializedItem {
231 fn default() -> Self {
232 SerializedItem {
233 kind: Arc::from("Terminal"),
234 item_id: 100000,
235 active: false,
236 }
237 }
238}
239
240impl Bind for &SerializedItem {
241 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
242 let next_index = statement.bind(self.kind.clone(), start_index)?;
243 let next_index = statement.bind(self.item_id, next_index)?;
244 statement.bind(self.active, next_index)
245 }
246}
247
248impl Column for SerializedItem {
249 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
250 let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
251 let (item_id, next_index) = ItemId::column(statement, next_index)?;
252 let (active, next_index) = bool::column(statement, next_index)?;
253 Ok((
254 SerializedItem {
255 kind,
256 item_id,
257 active,
258 },
259 next_index,
260 ))
261 }
262}
263
264impl Bind for DockPosition {
265 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
266 let next_index = statement.bind(self.is_visible(), start_index)?;
267 statement.bind(self.anchor(), next_index)
268 }
269}
270
271impl Column for DockPosition {
272 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
273 let (visible, next_index) = bool::column(statement, start_index)?;
274 let (dock_anchor, next_index) = DockAnchor::column(statement, next_index)?;
275 let position = if visible {
276 DockPosition::Shown(dock_anchor)
277 } else {
278 DockPosition::Hidden(dock_anchor)
279 };
280 Ok((position, next_index))
281 }
282}
283
284#[cfg(test)]
285mod tests {
286 use db::sqlez::connection::Connection;
287 use settings::DockAnchor;
288
289 use super::WorkspaceLocation;
290
291 #[test]
292 fn test_workspace_round_trips() {
293 let db = Connection::open_memory(Some("workspace_id_round_trips"));
294
295 db.exec(indoc::indoc! {"
296 CREATE TABLE workspace_id_test(
297 workspace_id INTEGER,
298 dock_anchor TEXT
299 );"})
300 .unwrap()()
301 .unwrap();
302
303 let workspace_id: WorkspaceLocation = WorkspaceLocation::from(&["\test2", "\test1"]);
304
305 db.exec_bound("INSERT INTO workspace_id_test(workspace_id, dock_anchor) VALUES (?,?)")
306 .unwrap()((&workspace_id, DockAnchor::Bottom))
307 .unwrap();
308
309 assert_eq!(
310 db.select_row("SELECT workspace_id, dock_anchor FROM workspace_id_test LIMIT 1")
311 .unwrap()()
312 .unwrap(),
313 Some((
314 WorkspaceLocation::from(&["\test1", "\test2"]),
315 DockAnchor::Bottom
316 ))
317 );
318 }
319}