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 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}
220
221#[derive(Debug, PartialEq, Clone, Default)]
222pub struct DockStructure {
223    pub(crate) left: DockData,
224    pub(crate) right: DockData,
225    pub(crate) bottom: DockData,
226}
227
228impl Column for DockStructure {
229    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
230        let (left, next_index) = DockData::column(statement, start_index)?;
231        let (right, next_index) = DockData::column(statement, next_index)?;
232        let (bottom, next_index) = DockData::column(statement, next_index)?;
233        Ok((
234            DockStructure {
235                left,
236                right,
237                bottom,
238            },
239            next_index,
240        ))
241    }
242}
243
244impl Bind for DockStructure {
245    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
246        let next_index = statement.bind(&self.left, start_index)?;
247        let next_index = statement.bind(&self.right, next_index)?;
248        statement.bind(&self.bottom, next_index)
249    }
250}
251
252#[derive(Debug, PartialEq, Clone, Default)]
253pub struct DockData {
254    pub(crate) visible: bool,
255    pub(crate) active_panel: Option<String>,
256    pub(crate) zoom: bool,
257}
258
259impl Column for DockData {
260    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
261        let (visible, next_index) = Option::<bool>::column(statement, start_index)?;
262        let (active_panel, next_index) = Option::<String>::column(statement, next_index)?;
263        let (zoom, next_index) = Option::<bool>::column(statement, next_index)?;
264        Ok((
265            DockData {
266                visible: visible.unwrap_or(false),
267                active_panel,
268                zoom: zoom.unwrap_or(false),
269            },
270            next_index,
271        ))
272    }
273}
274
275impl Bind for DockData {
276    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
277        let next_index = statement.bind(&self.visible, start_index)?;
278        let next_index = statement.bind(&self.active_panel, next_index)?;
279        statement.bind(&self.zoom, next_index)
280    }
281}
282
283#[derive(Debug, PartialEq, Clone)]
284pub(crate) enum SerializedPaneGroup {
285    Group {
286        axis: SerializedAxis,
287        flexes: Option<Vec<f32>>,
288        children: Vec<SerializedPaneGroup>,
289    },
290    Pane(SerializedPane),
291}
292
293#[cfg(test)]
294impl Default for SerializedPaneGroup {
295    fn default() -> Self {
296        Self::Pane(SerializedPane {
297            children: vec![SerializedItem::default()],
298            active: false,
299        })
300    }
301}
302
303impl SerializedPaneGroup {
304    #[async_recursion(?Send)]
305    pub(crate) async fn deserialize(
306        self,
307        project: &Model<Project>,
308        workspace_id: WorkspaceId,
309        workspace: WeakView<Workspace>,
310        cx: &mut AsyncWindowContext,
311    ) -> Option<(Member, Option<View<Pane>>, Vec<Option<Box<dyn ItemHandle>>>)> {
312        match self {
313            SerializedPaneGroup::Group {
314                axis,
315                children,
316                flexes,
317            } => {
318                let mut current_active_pane = None;
319                let mut members = Vec::new();
320                let mut items = Vec::new();
321                for child in children {
322                    if let Some((new_member, active_pane, new_items)) = child
323                        .deserialize(project, workspace_id, workspace.clone(), cx)
324                        .await
325                    {
326                        members.push(new_member);
327                        items.extend(new_items);
328                        current_active_pane = current_active_pane.or(active_pane);
329                    }
330                }
331
332                if members.is_empty() {
333                    return None;
334                }
335
336                if members.len() == 1 {
337                    return Some((members.remove(0), current_active_pane, items));
338                }
339
340                Some((
341                    Member::Axis(PaneAxis::load(axis.0, members, flexes)),
342                    current_active_pane,
343                    items,
344                ))
345            }
346            SerializedPaneGroup::Pane(serialized_pane) => {
347                let pane = workspace
348                    .update(cx, |workspace, cx| workspace.add_pane(cx).downgrade())
349                    .log_err()?;
350                let active = serialized_pane.active;
351                let new_items = serialized_pane
352                    .deserialize_to(project, &pane, workspace_id, workspace.clone(), cx)
353                    .await
354                    .log_err()?;
355
356                if pane.update(cx, |pane, _| pane.items_len() != 0).log_err()? {
357                    let pane = pane.upgrade()?;
358                    Some((Member::Pane(pane.clone()), active.then(|| pane), new_items))
359                } else {
360                    let pane = pane.upgrade()?;
361                    workspace
362                        .update(cx, |workspace, cx| workspace.force_remove_pane(&pane, cx))
363                        .log_err()?;
364                    None
365                }
366            }
367        }
368    }
369}
370
371#[derive(Debug, PartialEq, Eq, Default, Clone)]
372pub struct SerializedPane {
373    pub(crate) active: bool,
374    pub(crate) children: Vec<SerializedItem>,
375}
376
377impl SerializedPane {
378    pub fn new(children: Vec<SerializedItem>, active: bool) -> Self {
379        SerializedPane { children, active }
380    }
381
382    pub async fn deserialize_to(
383        &self,
384        project: &Model<Project>,
385        pane: &WeakView<Pane>,
386        workspace_id: WorkspaceId,
387        workspace: WeakView<Workspace>,
388        cx: &mut AsyncWindowContext,
389    ) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
390        let mut item_tasks = Vec::new();
391        let mut active_item_index = None;
392        let mut preview_item_index = None;
393        for (index, item) in self.children.iter().enumerate() {
394            let project = project.clone();
395            item_tasks.push(pane.update(cx, |_, cx| {
396                SerializableItemRegistry::deserialize(
397                    &item.kind,
398                    project,
399                    workspace.clone(),
400                    workspace_id,
401                    item.item_id,
402                    cx,
403                )
404            })?);
405            if item.active {
406                active_item_index = Some(index);
407            }
408            if item.preview {
409                preview_item_index = Some(index);
410            }
411        }
412
413        let mut items = Vec::new();
414        for item_handle in futures::future::join_all(item_tasks).await {
415            let item_handle = item_handle.log_err();
416            items.push(item_handle.clone());
417
418            if let Some(item_handle) = item_handle {
419                pane.update(cx, |pane, cx| {
420                    pane.add_item(item_handle.clone(), true, true, None, cx);
421                })?;
422            }
423        }
424
425        if let Some(active_item_index) = active_item_index {
426            pane.update(cx, |pane, cx| {
427                pane.activate_item(active_item_index, false, false, cx);
428            })?;
429        }
430
431        if let Some(preview_item_index) = preview_item_index {
432            pane.update(cx, |pane, cx| {
433                if let Some(item) = pane.item_for_index(preview_item_index) {
434                    pane.set_preview_item_id(Some(item.item_id()), cx);
435                }
436            })?;
437        }
438
439        anyhow::Ok(items)
440    }
441}
442
443pub type GroupId = i64;
444pub type PaneId = i64;
445pub type ItemId = u64;
446
447#[derive(Debug, PartialEq, Eq, Clone)]
448pub struct SerializedItem {
449    pub kind: Arc<str>,
450    pub item_id: ItemId,
451    pub active: bool,
452    pub preview: bool,
453}
454
455impl SerializedItem {
456    pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool, preview: bool) -> Self {
457        Self {
458            kind: Arc::from(kind.as_ref()),
459            item_id,
460            active,
461            preview,
462        }
463    }
464}
465
466#[cfg(test)]
467impl Default for SerializedItem {
468    fn default() -> Self {
469        SerializedItem {
470            kind: Arc::from("Terminal"),
471            item_id: 100000,
472            active: false,
473            preview: false,
474        }
475    }
476}
477
478impl StaticColumnCount for SerializedItem {
479    fn column_count() -> usize {
480        4
481    }
482}
483impl Bind for &SerializedItem {
484    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
485        let next_index = statement.bind(&self.kind, start_index)?;
486        let next_index = statement.bind(&self.item_id, next_index)?;
487        let next_index = statement.bind(&self.active, next_index)?;
488        statement.bind(&self.preview, next_index)
489    }
490}
491
492impl Column for SerializedItem {
493    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
494        let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
495        let (item_id, next_index) = ItemId::column(statement, next_index)?;
496        let (active, next_index) = bool::column(statement, next_index)?;
497        let (preview, next_index) = bool::column(statement, next_index)?;
498        Ok((
499            SerializedItem {
500                kind,
501                item_id,
502                active,
503                preview,
504            },
505            next_index,
506        ))
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513
514    #[test]
515    fn test_serialize_local_paths() {
516        let paths = vec!["b", "a", "c"];
517        let serialized = SerializedWorkspaceLocation::from_local_paths(paths);
518
519        assert_eq!(
520            serialized,
521            SerializedWorkspaceLocation::Local(
522                LocalPaths::new(vec!["a", "b", "c"]),
523                LocalPathsOrder::new(vec![1, 0, 2])
524            )
525        );
526    }
527}