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