model.rs

  1use crate::{
  2    item::ItemHandle, Axis, ItemDeserializers, Member, Pane, PaneAxis, Workspace, WorkspaceId,
  3};
  4use anyhow::{Context, Result};
  5use async_recursion::async_recursion;
  6use db2::sqlez::{
  7    bindable::{Bind, Column, StaticColumnCount},
  8    statement::Statement,
  9};
 10use gpui2::{
 11    AsyncAppContext, AsyncWindowContext, Model, Task, View, WeakView, WindowBounds, WindowHandle,
 12};
 13use project2::Project;
 14use std::{
 15    path::{Path, PathBuf},
 16    sync::Arc,
 17};
 18use util::ResultExt;
 19use uuid::Uuid;
 20
 21#[derive(Debug, Clone, PartialEq, Eq)]
 22pub struct WorkspaceLocation(Arc<Vec<PathBuf>>);
 23
 24impl WorkspaceLocation {
 25    pub fn paths(&self) -> Arc<Vec<PathBuf>> {
 26        self.0.clone()
 27    }
 28}
 29
 30impl<P: AsRef<Path>, T: IntoIterator<Item = P>> From<T> for WorkspaceLocation {
 31    fn from(iterator: T) -> Self {
 32        let mut roots = iterator
 33            .into_iter()
 34            .map(|p| p.as_ref().to_path_buf())
 35            .collect::<Vec<_>>();
 36        roots.sort();
 37        Self(Arc::new(roots))
 38    }
 39}
 40
 41impl StaticColumnCount for WorkspaceLocation {}
 42impl Bind for &WorkspaceLocation {
 43    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
 44        bincode::serialize(&self.0)
 45            .expect("Bincode serialization of paths should not fail")
 46            .bind(statement, start_index)
 47    }
 48}
 49
 50impl Column for WorkspaceLocation {
 51    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
 52        let blob = statement.column_blob(start_index)?;
 53        Ok((
 54            WorkspaceLocation(bincode::deserialize(blob).context("Bincode failed")?),
 55            start_index + 1,
 56        ))
 57    }
 58}
 59
 60#[derive(PartialEq, Clone)]
 61pub struct SerializedWorkspace {
 62    pub id: WorkspaceId,
 63    pub location: WorkspaceLocation,
 64    pub center_group: SerializedPaneGroup,
 65    pub bounds: Option<WindowBounds>,
 66    pub display: Option<Uuid>,
 67    pub docks: DockStructure,
 68}
 69
 70#[derive(Debug, PartialEq, Clone, Default)]
 71pub struct DockStructure {
 72    pub(crate) left: DockData,
 73    pub(crate) right: DockData,
 74    pub(crate) bottom: DockData,
 75}
 76
 77impl Column for DockStructure {
 78    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
 79        let (left, next_index) = DockData::column(statement, start_index)?;
 80        let (right, next_index) = DockData::column(statement, next_index)?;
 81        let (bottom, next_index) = DockData::column(statement, next_index)?;
 82        Ok((
 83            DockStructure {
 84                left,
 85                right,
 86                bottom,
 87            },
 88            next_index,
 89        ))
 90    }
 91}
 92
 93impl Bind for DockStructure {
 94    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
 95        let next_index = statement.bind(&self.left, start_index)?;
 96        let next_index = statement.bind(&self.right, next_index)?;
 97        statement.bind(&self.bottom, next_index)
 98    }
 99}
100
101#[derive(Debug, PartialEq, Clone, Default)]
102pub struct DockData {
103    pub(crate) visible: bool,
104    pub(crate) active_panel: Option<String>,
105    pub(crate) zoom: bool,
106}
107
108impl Column for DockData {
109    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
110        let (visible, next_index) = Option::<bool>::column(statement, start_index)?;
111        let (active_panel, next_index) = Option::<String>::column(statement, next_index)?;
112        let (zoom, next_index) = Option::<bool>::column(statement, next_index)?;
113        Ok((
114            DockData {
115                visible: visible.unwrap_or(false),
116                active_panel,
117                zoom: zoom.unwrap_or(false),
118            },
119            next_index,
120        ))
121    }
122}
123
124impl Bind for DockData {
125    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
126        let next_index = statement.bind(&self.visible, start_index)?;
127        let next_index = statement.bind(&self.active_panel, next_index)?;
128        statement.bind(&self.zoom, next_index)
129    }
130}
131
132#[derive(PartialEq, Clone)]
133pub enum SerializedPaneGroup {
134    Group {
135        axis: Axis,
136        flexes: Option<Vec<f32>>,
137        children: Vec<SerializedPaneGroup>,
138    },
139    Pane(SerializedPane),
140}
141
142#[cfg(test)]
143impl Default for SerializedPaneGroup {
144    fn default() -> Self {
145        Self::Pane(SerializedPane {
146            children: vec![SerializedItem::default()],
147            active: false,
148        })
149    }
150}
151
152impl SerializedPaneGroup {
153    #[async_recursion(?Send)]
154    pub(crate) async fn deserialize(
155        self,
156        project: &Model<Project>,
157        workspace_id: WorkspaceId,
158        workspace: WindowHandle<Workspace>,
159        cx: &mut AsyncAppContext,
160    ) -> Option<(Member, Option<View<Pane>>, Vec<Option<Box<dyn ItemHandle>>>)> {
161        match self {
162            SerializedPaneGroup::Group {
163                axis,
164                children,
165                flexes,
166            } => {
167                let mut current_active_pane = None;
168                let mut members = Vec::new();
169                let mut items = Vec::new();
170                for child in children {
171                    if let Some((new_member, active_pane, new_items)) = child
172                        .deserialize(project, workspace_id, workspace, cx)
173                        .await
174                    {
175                        members.push(new_member);
176                        items.extend(new_items);
177                        current_active_pane = current_active_pane.or(active_pane);
178                    }
179                }
180
181                if members.is_empty() {
182                    return None;
183                }
184
185                if members.len() == 1 {
186                    return Some((members.remove(0), current_active_pane, items));
187                }
188
189                Some((
190                    Member::Axis(PaneAxis::load(axis, members, flexes)),
191                    current_active_pane,
192                    items,
193                ))
194            }
195            SerializedPaneGroup::Pane(serialized_pane) => {
196                let pane = workspace
197                    .update(cx, |workspace, cx| workspace.add_pane(cx).downgrade())
198                    .log_err()?;
199                let active = serialized_pane.active;
200                let new_items = serialized_pane
201                    .deserialize_to(project, &pane, workspace_id, workspace, cx)
202                    .await
203                    .log_err()?;
204
205                if pane.update(cx, |pane, _| pane.items_len() != 0).log_err()? {
206                    let pane = pane.upgrade()?;
207                    Some((Member::Pane(pane.clone()), active.then(|| pane), new_items))
208                } else {
209                    let pane = pane.upgrade()?;
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: &Model<Project>,
234        pane: &WeakView<Pane>,
235        workspace_id: WorkspaceId,
236        workspace: WindowHandle<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, 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}