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