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