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