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