model.rs

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