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