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