model.rs

  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 db::sqlez::{
  8    bindable::{Bind, Column, StaticColumnCount},
  9    statement::Statement,
 10};
 11use gpui::{AsyncWindowContext, Model, View, WeakView};
 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::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| p.as_ref().to_path_buf())
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: &Model<Project>,
357        workspace_id: WorkspaceId,
358        workspace: WeakView<Workspace>,
359        cx: &mut AsyncWindowContext,
360    ) -> Option<(Member, Option<View<Pane>>, Vec<Option<Box<dyn ItemHandle>>>)> {
361        match self {
362            SerializedPaneGroup::Group {
363                axis,
364                children,
365                flexes,
366            } => {
367                let mut current_active_pane = None;
368                let mut members = Vec::new();
369                let mut items = Vec::new();
370                for child in children {
371                    if let Some((new_member, active_pane, new_items)) = child
372                        .deserialize(project, workspace_id, workspace.clone(), cx)
373                        .await
374                    {
375                        members.push(new_member);
376                        items.extend(new_items);
377                        current_active_pane = current_active_pane.or(active_pane);
378                    }
379                }
380
381                if members.is_empty() {
382                    return None;
383                }
384
385                if members.len() == 1 {
386                    return Some((members.remove(0), current_active_pane, items));
387                }
388
389                Some((
390                    Member::Axis(PaneAxis::load(axis.0, members, flexes)),
391                    current_active_pane,
392                    items,
393                ))
394            }
395            SerializedPaneGroup::Pane(serialized_pane) => {
396                let pane = workspace
397                    .update(cx, |workspace, cx| workspace.add_pane(cx).downgrade())
398                    .log_err()?;
399                let active = serialized_pane.active;
400                let new_items = serialized_pane
401                    .deserialize_to(project, &pane, workspace_id, workspace.clone(), cx)
402                    .await
403                    .log_err()?;
404
405                if pane.update(cx, |pane, _| pane.items_len() != 0).log_err()? {
406                    let pane = pane.upgrade()?;
407                    Some((
408                        Member::Pane(pane.clone()),
409                        active.then_some(pane),
410                        new_items,
411                    ))
412                } else {
413                    let pane = pane.upgrade()?;
414                    workspace
415                        .update(cx, |workspace, cx| {
416                            workspace.force_remove_pane(&pane, &None, cx)
417                        })
418                        .log_err()?;
419                    None
420                }
421            }
422        }
423    }
424}
425
426#[derive(Debug, PartialEq, Eq, Default, Clone)]
427pub struct SerializedPane {
428    pub(crate) active: bool,
429    pub(crate) children: Vec<SerializedItem>,
430    pub(crate) pinned_count: usize,
431}
432
433impl SerializedPane {
434    pub fn new(children: Vec<SerializedItem>, active: bool, pinned_count: usize) -> Self {
435        SerializedPane {
436            children,
437            active,
438            pinned_count,
439        }
440    }
441
442    pub async fn deserialize_to(
443        &self,
444        project: &Model<Project>,
445        pane: &WeakView<Pane>,
446        workspace_id: WorkspaceId,
447        workspace: WeakView<Workspace>,
448        cx: &mut AsyncWindowContext,
449    ) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
450        let mut item_tasks = Vec::new();
451        let mut active_item_index = None;
452        let mut preview_item_index = None;
453        for (index, item) in self.children.iter().enumerate() {
454            let project = project.clone();
455            item_tasks.push(pane.update(cx, |_, cx| {
456                SerializableItemRegistry::deserialize(
457                    &item.kind,
458                    project,
459                    workspace.clone(),
460                    workspace_id,
461                    item.item_id,
462                    cx,
463                )
464            })?);
465            if item.active {
466                active_item_index = Some(index);
467            }
468            if item.preview {
469                preview_item_index = Some(index);
470            }
471        }
472
473        let mut items = Vec::new();
474        for item_handle in futures::future::join_all(item_tasks).await {
475            let item_handle = item_handle.log_err();
476            items.push(item_handle.clone());
477
478            if let Some(item_handle) = item_handle {
479                pane.update(cx, |pane, cx| {
480                    pane.add_item(item_handle.clone(), true, true, None, cx);
481                })?;
482            }
483        }
484
485        if let Some(active_item_index) = active_item_index {
486            pane.update(cx, |pane, cx| {
487                pane.activate_item(active_item_index, false, false, cx);
488            })?;
489        }
490
491        if let Some(preview_item_index) = preview_item_index {
492            pane.update(cx, |pane, cx| {
493                if let Some(item) = pane.item_for_index(preview_item_index) {
494                    pane.set_preview_item_id(Some(item.item_id()), cx);
495                }
496            })?;
497        }
498        pane.update(cx, |pane, _| {
499            pane.set_pinned_count(self.pinned_count.min(items.len()));
500        })?;
501
502        anyhow::Ok(items)
503    }
504}
505
506pub type GroupId = i64;
507pub type PaneId = i64;
508pub type ItemId = u64;
509
510#[derive(Debug, PartialEq, Eq, Clone)]
511pub struct SerializedItem {
512    pub kind: Arc<str>,
513    pub item_id: ItemId,
514    pub active: bool,
515    pub preview: bool,
516}
517
518impl SerializedItem {
519    pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool, preview: bool) -> Self {
520        Self {
521            kind: Arc::from(kind.as_ref()),
522            item_id,
523            active,
524            preview,
525        }
526    }
527}
528
529#[cfg(test)]
530impl Default for SerializedItem {
531    fn default() -> Self {
532        SerializedItem {
533            kind: Arc::from("Terminal"),
534            item_id: 100000,
535            active: false,
536            preview: false,
537        }
538    }
539}
540
541impl StaticColumnCount for SerializedItem {
542    fn column_count() -> usize {
543        4
544    }
545}
546impl Bind for &SerializedItem {
547    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
548        let next_index = statement.bind(&self.kind, start_index)?;
549        let next_index = statement.bind(&self.item_id, next_index)?;
550        let next_index = statement.bind(&self.active, next_index)?;
551        statement.bind(&self.preview, next_index)
552    }
553}
554
555impl Column for SerializedItem {
556    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
557        let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
558        let (item_id, next_index) = ItemId::column(statement, next_index)?;
559        let (active, next_index) = bool::column(statement, next_index)?;
560        let (preview, next_index) = bool::column(statement, next_index)?;
561        Ok((
562            SerializedItem {
563                kind,
564                item_id,
565                active,
566                preview,
567            },
568            next_index,
569        ))
570    }
571}
572
573#[cfg(test)]
574mod tests {
575    use super::*;
576
577    #[test]
578    fn test_serialize_local_paths() {
579        let paths = vec!["b", "a", "c"];
580        let serialized = SerializedWorkspaceLocation::from_local_paths(paths);
581
582        assert_eq!(
583            serialized,
584            SerializedWorkspaceLocation::Local(
585                LocalPaths::new(vec!["a", "b", "c"]),
586                LocalPathsOrder::new(vec![1, 0, 2])
587            )
588        );
589    }
590
591    #[test]
592    fn test_sorted_paths() {
593        let paths = vec!["b", "a", "c"];
594        let serialized = SerializedWorkspaceLocation::from_local_paths(paths);
595        assert_eq!(
596            serialized.sorted_paths(),
597            Arc::new(vec![
598                PathBuf::from("b"),
599                PathBuf::from("a"),
600                PathBuf::from("c"),
601            ])
602        );
603
604        let paths = Arc::new(vec![
605            PathBuf::from("a"),
606            PathBuf::from("b"),
607            PathBuf::from("c"),
608        ]);
609        let order = vec![2, 0, 1];
610        let serialized =
611            SerializedWorkspaceLocation::Local(LocalPaths(paths.clone()), LocalPathsOrder(order));
612        assert_eq!(
613            serialized.sorted_paths(),
614            Arc::new(vec![
615                PathBuf::from("b"),
616                PathBuf::from("c"),
617                PathBuf::from("a"),
618            ])
619        );
620
621        let paths = Arc::new(vec![
622            PathBuf::from("a"),
623            PathBuf::from("b"),
624            PathBuf::from("c"),
625        ]);
626        let order = vec![];
627        let serialized =
628            SerializedWorkspaceLocation::Local(LocalPaths(paths.clone()), LocalPathsOrder(order));
629        assert_eq!(serialized.sorted_paths(), paths);
630
631        let urls = ["/a", "/b", "/c"];
632        let serialized = SerializedWorkspaceLocation::Ssh(SerializedSshProject {
633            id: SshProjectId(0),
634            host: "host".to_string(),
635            port: Some(22),
636            paths: urls.iter().map(|s| s.to_string()).collect(),
637            user: Some("user".to_string()),
638        });
639        assert_eq!(
640            serialized.sorted_paths(),
641            Arc::new(
642                urls.iter()
643                    .map(|p| PathBuf::from(format!("user@host:22{}", p)))
644                    .collect()
645            )
646        );
647    }
648}