1use super::{SerializedAxis, SerializedWindowBounds};
2use crate::{
3 item::ItemHandle, Member, Pane, PaneAxis, SerializableItemRegistry, Workspace, WorkspaceId,
4};
5use anyhow::{Context, Result};
6use async_recursion::async_recursion;
7use client::DevServerProjectId;
8use db::sqlez::{
9 bindable::{Bind, Column, StaticColumnCount},
10 statement::Statement,
11};
12use gpui::{AsyncWindowContext, Model, View, WeakView};
13use project::Project;
14use serde::{Deserialize, Serialize};
15use std::{
16 path::{Path, PathBuf},
17 sync::Arc,
18};
19use ui::SharedString;
20use util::ResultExt;
21use uuid::Uuid;
22
23#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
24pub struct SerializedDevServerProject {
25 pub id: DevServerProjectId,
26 pub dev_server_name: String,
27 pub paths: Vec<SharedString>,
28}
29
30#[derive(Debug, PartialEq, Clone)]
31pub struct LocalPaths(Arc<Vec<PathBuf>>);
32
33impl LocalPaths {
34 pub fn new<P: AsRef<Path>>(paths: impl IntoIterator<Item = P>) -> Self {
35 let mut paths: Vec<PathBuf> = paths
36 .into_iter()
37 .map(|p| p.as_ref().to_path_buf())
38 .collect();
39 // Ensure all future `zed workspace1 workspace2` and `zed workspace2 workspace1` calls are using the same workspace.
40 // The actual workspace order is stored in the `LocalPathsOrder` struct.
41 paths.sort();
42 Self(Arc::new(paths))
43 }
44
45 pub fn paths(&self) -> &Arc<Vec<PathBuf>> {
46 &self.0
47 }
48}
49
50impl StaticColumnCount for LocalPaths {}
51impl Bind for &LocalPaths {
52 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
53 statement.bind(&bincode::serialize(&self.0)?, start_index)
54 }
55}
56
57impl Column for LocalPaths {
58 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
59 let path_blob = statement.column_blob(start_index)?;
60 let paths: Arc<Vec<PathBuf>> = if path_blob.is_empty() {
61 println!("path blog is empty");
62 Default::default()
63 } else {
64 bincode::deserialize(path_blob).context("Bincode deserialization of paths failed")?
65 };
66
67 Ok((Self(paths), start_index + 1))
68 }
69}
70
71#[derive(Debug, PartialEq, Clone)]
72pub struct LocalPathsOrder(Vec<usize>);
73
74impl LocalPathsOrder {
75 pub fn new(order: impl IntoIterator<Item = usize>) -> Self {
76 Self(order.into_iter().collect())
77 }
78
79 pub fn order(&self) -> &[usize] {
80 self.0.as_slice()
81 }
82
83 pub fn default_for_paths(paths: &LocalPaths) -> Self {
84 Self::new(0..paths.0.len())
85 }
86}
87
88impl StaticColumnCount for LocalPathsOrder {}
89impl Bind for &LocalPathsOrder {
90 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
91 statement.bind(&bincode::serialize(&self.0)?, start_index)
92 }
93}
94
95impl Column for LocalPathsOrder {
96 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
97 let order_blob = statement.column_blob(start_index)?;
98 let order = if order_blob.is_empty() {
99 Vec::new()
100 } else {
101 bincode::deserialize(order_blob).context("deserializing workspace root order")?
102 };
103
104 Ok((Self(order), start_index + 1))
105 }
106}
107
108impl From<SerializedDevServerProject> for SerializedWorkspaceLocation {
109 fn from(dev_server_project: SerializedDevServerProject) -> Self {
110 Self::DevServer(dev_server_project)
111 }
112}
113
114impl StaticColumnCount for SerializedDevServerProject {}
115impl Bind for &SerializedDevServerProject {
116 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
117 let next_index = statement.bind(&self.id.0, start_index)?;
118 let next_index = statement.bind(&self.dev_server_name, next_index)?;
119 let paths = serde_json::to_string(&self.paths)?;
120 statement.bind(&paths, next_index)
121 }
122}
123
124impl Column for SerializedDevServerProject {
125 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
126 let id = statement.column_int64(start_index)?;
127 let dev_server_name = statement.column_text(start_index + 1)?.to_string();
128 let paths = statement.column_text(start_index + 2)?.to_string();
129 let paths: Vec<SharedString> = if paths.starts_with('[') {
130 serde_json::from_str(&paths).context("JSON deserialization of paths failed")?
131 } else {
132 vec![paths.into()]
133 };
134
135 Ok((
136 Self {
137 id: DevServerProjectId(id as u64),
138 dev_server_name,
139 paths,
140 },
141 start_index + 3,
142 ))
143 }
144}
145
146#[derive(Debug, PartialEq, Clone)]
147pub enum SerializedWorkspaceLocation {
148 Local(LocalPaths, LocalPathsOrder),
149 DevServer(SerializedDevServerProject),
150}
151
152impl SerializedWorkspaceLocation {
153 /// Create a new `SerializedWorkspaceLocation` from a list of local paths.
154 ///
155 /// The paths will be sorted and the order will be stored in the `LocalPathsOrder` struct.
156 ///
157 /// # Examples
158 ///
159 /// ```
160 /// use std::path::Path;
161 /// use zed_workspace::SerializedWorkspaceLocation;
162 ///
163 /// let location = SerializedWorkspaceLocation::from_local_paths(vec![
164 /// Path::new("path/to/workspace1"),
165 /// Path::new("path/to/workspace2"),
166 /// ]);
167 /// assert_eq!(location, SerializedWorkspaceLocation::Local(
168 /// LocalPaths::new(vec![
169 /// Path::new("path/to/workspace1"),
170 /// Path::new("path/to/workspace2"),
171 /// ]),
172 /// LocalPathsOrder::new(vec![0, 1]),
173 /// ));
174 /// ```
175 ///
176 /// ```
177 /// use std::path::Path;
178 /// use zed_workspace::SerializedWorkspaceLocation;
179 ///
180 /// let location = SerializedWorkspaceLocation::from_local_paths(vec![
181 /// Path::new("path/to/workspace2"),
182 /// Path::new("path/to/workspace1"),
183 /// ]);
184 ///
185 /// assert_eq!(location, SerializedWorkspaceLocation::Local(
186 /// LocalPaths::new(vec![
187 /// Path::new("path/to/workspace1"),
188 /// Path::new("path/to/workspace2"),
189 /// ]),
190 /// LocalPathsOrder::new(vec![1, 0]),
191 /// ));
192 /// ```
193 pub fn from_local_paths<P: AsRef<Path>>(paths: impl IntoIterator<Item = P>) -> Self {
194 let mut indexed_paths: Vec<_> = paths
195 .into_iter()
196 .map(|p| p.as_ref().to_path_buf())
197 .enumerate()
198 .collect();
199
200 indexed_paths.sort_by(|(_, a), (_, b)| a.cmp(b));
201
202 let sorted_paths: Vec<_> = indexed_paths.iter().map(|(_, path)| path.clone()).collect();
203 let order: Vec<_> = indexed_paths.iter().map(|(index, _)| *index).collect();
204
205 Self::Local(LocalPaths::new(sorted_paths), LocalPathsOrder::new(order))
206 }
207}
208
209#[derive(Debug, PartialEq, Clone)]
210pub(crate) struct SerializedWorkspace {
211 pub(crate) id: WorkspaceId,
212 pub(crate) location: SerializedWorkspaceLocation,
213 pub(crate) center_group: SerializedPaneGroup,
214 pub(crate) window_bounds: Option<SerializedWindowBounds>,
215 pub(crate) centered_layout: bool,
216 pub(crate) display: Option<Uuid>,
217 pub(crate) docks: DockStructure,
218 pub(crate) session_id: Option<String>,
219 pub(crate) window_id: Option<u64>,
220}
221
222#[derive(Debug, PartialEq, Clone, Default)]
223pub struct DockStructure {
224 pub(crate) left: DockData,
225 pub(crate) right: DockData,
226 pub(crate) bottom: DockData,
227}
228
229impl Column for DockStructure {
230 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
231 let (left, next_index) = DockData::column(statement, start_index)?;
232 let (right, next_index) = DockData::column(statement, next_index)?;
233 let (bottom, next_index) = DockData::column(statement, next_index)?;
234 Ok((
235 DockStructure {
236 left,
237 right,
238 bottom,
239 },
240 next_index,
241 ))
242 }
243}
244
245impl Bind for DockStructure {
246 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
247 let next_index = statement.bind(&self.left, start_index)?;
248 let next_index = statement.bind(&self.right, next_index)?;
249 statement.bind(&self.bottom, next_index)
250 }
251}
252
253#[derive(Debug, PartialEq, Clone, Default)]
254pub struct DockData {
255 pub(crate) visible: bool,
256 pub(crate) active_panel: Option<String>,
257 pub(crate) zoom: bool,
258}
259
260impl Column for DockData {
261 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
262 let (visible, next_index) = Option::<bool>::column(statement, start_index)?;
263 let (active_panel, next_index) = Option::<String>::column(statement, next_index)?;
264 let (zoom, next_index) = Option::<bool>::column(statement, next_index)?;
265 Ok((
266 DockData {
267 visible: visible.unwrap_or(false),
268 active_panel,
269 zoom: zoom.unwrap_or(false),
270 },
271 next_index,
272 ))
273 }
274}
275
276impl Bind for DockData {
277 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
278 let next_index = statement.bind(&self.visible, start_index)?;
279 let next_index = statement.bind(&self.active_panel, next_index)?;
280 statement.bind(&self.zoom, next_index)
281 }
282}
283
284#[derive(Debug, PartialEq, Clone)]
285pub(crate) enum SerializedPaneGroup {
286 Group {
287 axis: SerializedAxis,
288 flexes: Option<Vec<f32>>,
289 children: Vec<SerializedPaneGroup>,
290 },
291 Pane(SerializedPane),
292}
293
294#[cfg(test)]
295impl Default for SerializedPaneGroup {
296 fn default() -> Self {
297 Self::Pane(SerializedPane {
298 children: vec![SerializedItem::default()],
299 active: false,
300 pinned_count: 0,
301 })
302 }
303}
304
305impl SerializedPaneGroup {
306 #[async_recursion(?Send)]
307 pub(crate) async fn deserialize(
308 self,
309 project: &Model<Project>,
310 workspace_id: WorkspaceId,
311 workspace: WeakView<Workspace>,
312 cx: &mut AsyncWindowContext,
313 ) -> Option<(Member, Option<View<Pane>>, Vec<Option<Box<dyn ItemHandle>>>)> {
314 match self {
315 SerializedPaneGroup::Group {
316 axis,
317 children,
318 flexes,
319 } => {
320 let mut current_active_pane = None;
321 let mut members = Vec::new();
322 let mut items = Vec::new();
323 for child in children {
324 if let Some((new_member, active_pane, new_items)) = child
325 .deserialize(project, workspace_id, workspace.clone(), cx)
326 .await
327 {
328 members.push(new_member);
329 items.extend(new_items);
330 current_active_pane = current_active_pane.or(active_pane);
331 }
332 }
333
334 if members.is_empty() {
335 return None;
336 }
337
338 if members.len() == 1 {
339 return Some((members.remove(0), current_active_pane, items));
340 }
341
342 Some((
343 Member::Axis(PaneAxis::load(axis.0, members, flexes)),
344 current_active_pane,
345 items,
346 ))
347 }
348 SerializedPaneGroup::Pane(serialized_pane) => {
349 let pane = workspace
350 .update(cx, |workspace, cx| workspace.add_pane(cx).downgrade())
351 .log_err()?;
352 let active = serialized_pane.active;
353 let new_items = serialized_pane
354 .deserialize_to(project, &pane, workspace_id, workspace.clone(), cx)
355 .await
356 .log_err()?;
357
358 if pane.update(cx, |pane, _| pane.items_len() != 0).log_err()? {
359 let pane = pane.upgrade()?;
360 Some((
361 Member::Pane(pane.clone()),
362 active.then_some(pane),
363 new_items,
364 ))
365 } else {
366 let pane = pane.upgrade()?;
367 workspace
368 .update(cx, |workspace, cx| {
369 workspace.force_remove_pane(&pane, &None, cx)
370 })
371 .log_err()?;
372 None
373 }
374 }
375 }
376 }
377}
378
379#[derive(Debug, PartialEq, Eq, Default, Clone)]
380pub struct SerializedPane {
381 pub(crate) active: bool,
382 pub(crate) children: Vec<SerializedItem>,
383 pub(crate) pinned_count: usize,
384}
385
386impl SerializedPane {
387 pub fn new(children: Vec<SerializedItem>, active: bool, pinned_count: usize) -> Self {
388 SerializedPane {
389 children,
390 active,
391 pinned_count,
392 }
393 }
394
395 pub async fn deserialize_to(
396 &self,
397 project: &Model<Project>,
398 pane: &WeakView<Pane>,
399 workspace_id: WorkspaceId,
400 workspace: WeakView<Workspace>,
401 cx: &mut AsyncWindowContext,
402 ) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
403 let mut item_tasks = Vec::new();
404 let mut active_item_index = None;
405 let mut preview_item_index = None;
406 for (index, item) in self.children.iter().enumerate() {
407 let project = project.clone();
408 item_tasks.push(pane.update(cx, |_, cx| {
409 SerializableItemRegistry::deserialize(
410 &item.kind,
411 project,
412 workspace.clone(),
413 workspace_id,
414 item.item_id,
415 cx,
416 )
417 })?);
418 if item.active {
419 active_item_index = Some(index);
420 }
421 if item.preview {
422 preview_item_index = Some(index);
423 }
424 }
425
426 let mut items = Vec::new();
427 for item_handle in futures::future::join_all(item_tasks).await {
428 let item_handle = item_handle.log_err();
429 items.push(item_handle.clone());
430
431 if let Some(item_handle) = item_handle {
432 pane.update(cx, |pane, cx| {
433 pane.add_item(item_handle.clone(), true, true, None, cx);
434 })?;
435 }
436 }
437
438 if let Some(active_item_index) = active_item_index {
439 pane.update(cx, |pane, cx| {
440 pane.activate_item(active_item_index, false, false, cx);
441 })?;
442 }
443
444 if let Some(preview_item_index) = preview_item_index {
445 pane.update(cx, |pane, cx| {
446 if let Some(item) = pane.item_for_index(preview_item_index) {
447 pane.set_preview_item_id(Some(item.item_id()), cx);
448 }
449 })?;
450 }
451 pane.update(cx, |pane, _| {
452 pane.set_pinned_count(self.pinned_count);
453 })?;
454
455 anyhow::Ok(items)
456 }
457}
458
459pub type GroupId = i64;
460pub type PaneId = i64;
461pub type ItemId = u64;
462
463#[derive(Debug, PartialEq, Eq, Clone)]
464pub struct SerializedItem {
465 pub kind: Arc<str>,
466 pub item_id: ItemId,
467 pub active: bool,
468 pub preview: bool,
469}
470
471impl SerializedItem {
472 pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool, preview: bool) -> Self {
473 Self {
474 kind: Arc::from(kind.as_ref()),
475 item_id,
476 active,
477 preview,
478 }
479 }
480}
481
482#[cfg(test)]
483impl Default for SerializedItem {
484 fn default() -> Self {
485 SerializedItem {
486 kind: Arc::from("Terminal"),
487 item_id: 100000,
488 active: false,
489 preview: false,
490 }
491 }
492}
493
494impl StaticColumnCount for SerializedItem {
495 fn column_count() -> usize {
496 4
497 }
498}
499impl Bind for &SerializedItem {
500 fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
501 let next_index = statement.bind(&self.kind, start_index)?;
502 let next_index = statement.bind(&self.item_id, next_index)?;
503 let next_index = statement.bind(&self.active, next_index)?;
504 statement.bind(&self.preview, next_index)
505 }
506}
507
508impl Column for SerializedItem {
509 fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
510 let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
511 let (item_id, next_index) = ItemId::column(statement, next_index)?;
512 let (active, next_index) = bool::column(statement, next_index)?;
513 let (preview, next_index) = bool::column(statement, next_index)?;
514 Ok((
515 SerializedItem {
516 kind,
517 item_id,
518 active,
519 preview,
520 },
521 next_index,
522 ))
523 }
524}
525
526#[cfg(test)]
527mod tests {
528 use super::*;
529
530 #[test]
531 fn test_serialize_local_paths() {
532 let paths = vec!["b", "a", "c"];
533 let serialized = SerializedWorkspaceLocation::from_local_paths(paths);
534
535 assert_eq!(
536 serialized,
537 SerializedWorkspaceLocation::Local(
538 LocalPaths::new(vec!["a", "b", "c"]),
539 LocalPathsOrder::new(vec![1, 0, 2])
540 )
541 );
542 }
543}