model.rs

  1use crate::{item::ItemHandle, ItemDeserializers, Member, Pane, PaneAxis, Workspace, WorkspaceId};
  2use anyhow::{Context, Result};
  3use async_recursion::async_recursion;
  4use db::sqlez::{
  5    bindable::{Bind, Column, StaticColumnCount},
  6    statement::Statement,
  7};
  8use gpui::{
  9    platform::WindowBounds, AsyncAppContext, Axis, ModelHandle, Task, ViewHandle, WeakViewHandle,
 10};
 11use project::Project;
 12use std::{
 13    path::{Path, PathBuf},
 14    sync::Arc,
 15};
 16use util::ResultExt;
 17use uuid::Uuid;
 18
 19#[derive(Debug, Clone, PartialEq, Eq)]
 20pub struct WorkspaceLocation(Arc<Vec<PathBuf>>);
 21
 22impl WorkspaceLocation {
 23    pub fn paths(&self) -> Arc<Vec<PathBuf>> {
 24        self.0.clone()
 25    }
 26}
 27
 28impl<P: AsRef<Path>, T: IntoIterator<Item = P>> From<T> for WorkspaceLocation {
 29    fn from(iterator: T) -> Self {
 30        let mut roots = iterator
 31            .into_iter()
 32            .map(|p| p.as_ref().to_path_buf())
 33            .collect::<Vec<_>>();
 34        roots.sort();
 35        Self(Arc::new(roots))
 36    }
 37}
 38
 39impl StaticColumnCount for WorkspaceLocation {}
 40impl Bind for &WorkspaceLocation {
 41    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
 42        bincode::serialize(&self.0)
 43            .expect("Bincode serialization of paths should not fail")
 44            .bind(statement, start_index)
 45    }
 46}
 47
 48impl Column for WorkspaceLocation {
 49    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
 50        let blob = statement.column_blob(start_index)?;
 51        Ok((
 52            WorkspaceLocation(bincode::deserialize(blob).context("Bincode failed")?),
 53            start_index + 1,
 54        ))
 55    }
 56}
 57
 58#[derive(Debug, PartialEq, Clone)]
 59pub struct SerializedWorkspace {
 60    pub id: WorkspaceId,
 61    pub location: WorkspaceLocation,
 62    pub center_group: SerializedPaneGroup,
 63    pub bounds: Option<WindowBounds>,
 64    pub display: Option<Uuid>,
 65    pub docks: DockStructure,
 66}
 67
 68#[derive(Debug, PartialEq, Clone, Default)]
 69pub struct DockStructure {
 70    pub(crate) left: DockData,
 71    pub(crate) right: DockData,
 72    pub(crate) bottom: DockData,
 73}
 74
 75impl Column for DockStructure {
 76    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
 77        let (left, next_index) = DockData::column(statement, start_index)?;
 78        let (right, next_index) = DockData::column(statement, next_index)?;
 79        let (bottom, next_index) = DockData::column(statement, next_index)?;
 80        Ok((
 81            DockStructure {
 82                left,
 83                right,
 84                bottom,
 85            },
 86            next_index,
 87        ))
 88    }
 89}
 90
 91impl Bind for DockStructure {
 92    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
 93        let next_index = statement.bind(&self.left, start_index)?;
 94        let next_index = statement.bind(&self.right, next_index)?;
 95        statement.bind(&self.bottom, next_index)
 96    }
 97}
 98
 99#[derive(Debug, PartialEq, Clone, Default)]
100pub struct DockData {
101    pub(crate) visible: bool,
102    pub(crate) active_panel: Option<String>,
103    pub(crate) zoom: bool,
104}
105
106impl Column for DockData {
107    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
108        let (visible, next_index) = Option::<bool>::column(statement, start_index)?;
109        let (active_panel, next_index) = Option::<String>::column(statement, next_index)?;
110        let (zoom, next_index) = Option::<bool>::column(statement, next_index)?;
111        Ok((
112            DockData {
113                visible: visible.unwrap_or(false),
114                active_panel,
115                zoom: zoom.unwrap_or(false),
116            },
117            next_index,
118        ))
119    }
120}
121
122impl Bind for DockData {
123    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
124        let next_index = statement.bind(&self.visible, start_index)?;
125        let next_index = statement.bind(&self.active_panel, next_index)?;
126        statement.bind(&self.zoom, next_index)
127    }
128}
129
130#[derive(Debug, PartialEq, Eq, Clone)]
131pub enum SerializedPaneGroup {
132    Group {
133        axis: Axis,
134        children: Vec<SerializedPaneGroup>,
135    },
136    Pane(SerializedPane),
137}
138
139#[cfg(test)]
140impl Default for SerializedPaneGroup {
141    fn default() -> Self {
142        Self::Pane(SerializedPane {
143            children: vec![SerializedItem::default()],
144            active: false,
145        })
146    }
147}
148
149impl SerializedPaneGroup {
150    #[async_recursion(?Send)]
151    pub(crate) async fn deserialize(
152        &self,
153        project: &ModelHandle<Project>,
154        workspace_id: WorkspaceId,
155        workspace: &WeakViewHandle<Workspace>,
156        cx: &mut AsyncAppContext,
157    ) -> Option<(
158        Member,
159        Option<ViewHandle<Pane>>,
160        Vec<Option<Box<dyn ItemHandle>>>,
161    )> {
162        match self {
163            SerializedPaneGroup::Group { axis, children } => {
164                let mut current_active_pane = None;
165                let mut members = Vec::new();
166                let mut items = Vec::new();
167                for child in children {
168                    if let Some((new_member, active_pane, new_items)) = child
169                        .deserialize(project, workspace_id, workspace, cx)
170                        .await
171                    {
172                        members.push(new_member);
173                        items.extend(new_items);
174                        current_active_pane = current_active_pane.or(active_pane);
175                    }
176                }
177
178                if members.is_empty() {
179                    return None;
180                }
181
182                if members.len() == 1 {
183                    return Some((members.remove(0), current_active_pane, items));
184                }
185
186                Some((
187                    Member::Axis(PaneAxis::new(*axis, members)),
188                    current_active_pane,
189                    items,
190                ))
191            }
192            SerializedPaneGroup::Pane(serialized_pane) => {
193                let pane = workspace
194                    .update(cx, |workspace, cx| workspace.add_pane(cx).downgrade())
195                    .log_err()?;
196                let active = serialized_pane.active;
197                let new_items = serialized_pane
198                    .deserialize_to(project, &pane, workspace_id, workspace, cx)
199                    .await
200                    .log_err()?;
201
202                if pane
203                    .read_with(cx, |pane, _| pane.items_len() != 0)
204                    .log_err()?
205                {
206                    let pane = pane.upgrade(cx)?;
207                    Some((Member::Pane(pane.clone()), active.then(|| pane), new_items))
208                } else {
209                    let pane = pane.upgrade(cx)?;
210                    workspace
211                        .update(cx, |workspace, cx| workspace.force_remove_pane(&pane, cx))
212                        .log_err()?;
213                    None
214                }
215            }
216        }
217    }
218}
219
220#[derive(Debug, PartialEq, Eq, Default, Clone)]
221pub struct SerializedPane {
222    pub(crate) active: bool,
223    pub(crate) children: Vec<SerializedItem>,
224}
225
226impl SerializedPane {
227    pub fn new(children: Vec<SerializedItem>, active: bool) -> Self {
228        SerializedPane { children, active }
229    }
230
231    pub async fn deserialize_to(
232        &self,
233        project: &ModelHandle<Project>,
234        pane: &WeakViewHandle<Pane>,
235        workspace_id: WorkspaceId,
236        workspace: &WeakViewHandle<Workspace>,
237        cx: &mut AsyncAppContext,
238    ) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
239        let mut items = Vec::new();
240        let mut active_item_index = None;
241        for (index, item) in self.children.iter().enumerate() {
242            let project = project.clone();
243            let item_handle = pane
244                .update(cx, |_, cx| {
245                    if let Some(deserializer) = cx.global::<ItemDeserializers>().get(&item.kind) {
246                        deserializer(project, workspace.clone(), workspace_id, item.item_id, cx)
247                    } else {
248                        Task::ready(Err(anyhow::anyhow!(
249                            "Deserializer does not exist for item kind: {}",
250                            item.kind
251                        )))
252                    }
253                })?
254                .await
255                .log_err();
256
257            items.push(item_handle.clone());
258
259            if let Some(item_handle) = item_handle {
260                pane.update(cx, |pane, cx| {
261                    pane.add_item(item_handle.clone(), true, true, None, cx);
262                })?;
263            }
264
265            if item.active {
266                active_item_index = Some(index);
267            }
268        }
269
270        if let Some(active_item_index) = active_item_index {
271            pane.update(cx, |pane, cx| {
272                pane.activate_item(active_item_index, false, false, cx);
273            })?;
274        }
275
276        anyhow::Ok(items)
277    }
278}
279
280pub type GroupId = i64;
281pub type PaneId = i64;
282pub type ItemId = usize;
283
284#[derive(Debug, PartialEq, Eq, Clone)]
285pub struct SerializedItem {
286    pub kind: Arc<str>,
287    pub item_id: ItemId,
288    pub active: bool,
289}
290
291impl SerializedItem {
292    pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool) -> Self {
293        Self {
294            kind: Arc::from(kind.as_ref()),
295            item_id,
296            active,
297        }
298    }
299}
300
301#[cfg(test)]
302impl Default for SerializedItem {
303    fn default() -> Self {
304        SerializedItem {
305            kind: Arc::from("Terminal"),
306            item_id: 100000,
307            active: false,
308        }
309    }
310}
311
312impl StaticColumnCount for SerializedItem {
313    fn column_count() -> usize {
314        3
315    }
316}
317impl Bind for &SerializedItem {
318    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
319        let next_index = statement.bind(&self.kind, start_index)?;
320        let next_index = statement.bind(&self.item_id, next_index)?;
321        statement.bind(&self.active, next_index)
322    }
323}
324
325impl Column for SerializedItem {
326    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
327        let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
328        let (item_id, next_index) = ItemId::column(statement, next_index)?;
329        let (active, next_index) = bool::column(statement, next_index)?;
330        Ok((
331            SerializedItem {
332                kind,
333                item_id,
334                active,
335            },
336            next_index,
337        ))
338    }
339}