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