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