model.rs

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