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.read_with(cx, |pane, _| pane.items_len() != 0) {
144 Some((Member::Pane(pane.clone()), active.then(|| pane)))
145 } else {
146 workspace
147 .update(cx, |workspace, cx| workspace.remove_pane(pane, cx))
148 .log_err()?;
149 None
150 }
151 }
152 }
153 }
154}
155
156#[derive(Debug, PartialEq, Eq, Default, Clone)]
157pub struct SerializedPane {
158 pub(crate) active: bool,
159 pub(crate) children: Vec<SerializedItem>,
160}
161
162impl SerializedPane {
163 pub fn new(children: Vec<SerializedItem>, active: bool) -> Self {
164 SerializedPane { children, active }
165 }
166
167 pub async fn deserialize_to(
168 &self,
169 project: &ModelHandle<Project>,
170 pane_handle: &ViewHandle<Pane>,
171 workspace_id: WorkspaceId,
172 workspace: &ViewHandle<Workspace>,
173 cx: &mut AsyncAppContext,
174 ) -> Result<()> {
175 let mut active_item_index = None;
176 for (index, item) in self.children.iter().enumerate() {
177 let project = project.clone();
178 let item_handle = pane_handle
179 .update(cx, |_, cx| {
180 if let Some(deserializer) = cx.global::<ItemDeserializers>().get(&item.kind) {
181 deserializer(
182 project,
183 workspace.downgrade(),
184 workspace_id,
185 item.item_id,
186 cx,
187 )
188 } else {
189 Task::ready(Err(anyhow::anyhow!(
190 "Deserializer does not exist for item kind: {}",
191 item.kind
192 )))
193 }
194 })?
195 .await
196 .log_err();
197
198 if let Some(item_handle) = item_handle {
199 workspace.update(cx, |workspace, cx| {
200 Pane::add_item(workspace, &pane_handle, item_handle, false, false, None, cx);
201 })?;
202 }
203
204 if item.active {
205 active_item_index = Some(index);
206 }
207 }
208
209 if let Some(active_item_index) = active_item_index {
210 pane_handle.update(cx, |pane, cx| {
211 pane.activate_item(active_item_index, false, false, cx);
212 })?;
213 }
214
215 anyhow::Ok(())
216 }
217}
218
219pub type GroupId = i64;
220pub type PaneId = i64;
221pub type ItemId = usize;
222
223#[derive(Debug, PartialEq, Eq, Clone)]
224pub struct SerializedItem {
225 pub kind: Arc<str>,
226 pub item_id: ItemId,
227 pub active: bool,
228}
229
230impl SerializedItem {
231 pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool) -> Self {
232 Self {
233 kind: Arc::from(kind.as_ref()),
234 item_id,
235 active,
236 }
237 }
238}
239
240#[cfg(test)]
241impl Default for SerializedItem {
242 fn default() -> Self {
243 SerializedItem {
244 kind: Arc::from("Terminal"),
245 item_id: 100000,
246 active: false,
247 }
248 }
249}
250
251impl StaticColumnCount for SerializedItem {
252 fn column_count() -> usize {
253 3
254 }
255}
256impl Bind for &SerializedItem {
257 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
258 let next_index = statement.bind(self.kind.clone(), start_index)?;
259 let next_index = statement.bind(self.item_id, next_index)?;
260 statement.bind(self.active, next_index)
261 }
262}
263
264impl Column for SerializedItem {
265 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
266 let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
267 let (item_id, next_index) = ItemId::column(statement, next_index)?;
268 let (active, next_index) = bool::column(statement, next_index)?;
269 Ok((
270 SerializedItem {
271 kind,
272 item_id,
273 active,
274 },
275 next_index,
276 ))
277 }
278}
279
280impl StaticColumnCount for DockPosition {
281 fn column_count() -> usize {
282 2
283 }
284}
285impl Bind for DockPosition {
286 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
287 let next_index = statement.bind(self.is_visible(), start_index)?;
288 statement.bind(self.anchor(), next_index)
289 }
290}
291
292impl Column for DockPosition {
293 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
294 let (visible, next_index) = bool::column(statement, start_index)?;
295 let (dock_anchor, next_index) = DockAnchor::column(statement, next_index)?;
296 let position = if visible {
297 DockPosition::Shown(dock_anchor)
298 } else {
299 DockPosition::Hidden(dock_anchor)
300 };
301 Ok((position, next_index))
302 }
303}
304
305#[cfg(test)]
306mod tests {
307 use db::sqlez::connection::Connection;
308 use settings::DockAnchor;
309
310 use super::WorkspaceLocation;
311
312 #[test]
313 fn test_workspace_round_trips() {
314 let db = Connection::open_memory(Some("workspace_id_round_trips"));
315
316 db.exec(indoc::indoc! {"
317 CREATE TABLE workspace_id_test(
318 workspace_id INTEGER,
319 dock_anchor TEXT
320 );"})
321 .unwrap()()
322 .unwrap();
323
324 let workspace_id: WorkspaceLocation = WorkspaceLocation::from(&["\test2", "\test1"]);
325
326 db.exec_bound("INSERT INTO workspace_id_test(workspace_id, dock_anchor) VALUES (?,?)")
327 .unwrap()((&workspace_id, DockAnchor::Bottom))
328 .unwrap();
329
330 assert_eq!(
331 db.select_row("SELECT workspace_id, dock_anchor FROM workspace_id_test LIMIT 1")
332 .unwrap()()
333 .unwrap(),
334 Some((
335 WorkspaceLocation::from(&["\test1", "\test2"]),
336 DockAnchor::Bottom
337 ))
338 );
339 }
340}