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::{AsyncAppContext, Handle, Task, View, WeakView, WindowBounds};
 11use project2::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, Clone)]
131pub enum SerializedPaneGroup {
132    Group {
133        axis: Axis,
134        flexes: Option<Vec<f32>>,
135        children: Vec<SerializedPaneGroup>,
136    },
137    Pane(SerializedPane),
138}
139
140#[cfg(test)]
141impl Default for SerializedPaneGroup {
142    fn default() -> Self {
143        Self::Pane(SerializedPane {
144            children: vec![SerializedItem::default()],
145            active: false,
146        })
147    }
148}
149
150impl SerializedPaneGroup {
151    #[async_recursion(?Send)]
152    pub(crate) async fn deserialize(
153        self,
154        project: &Handle<Project>,
155        workspace_id: WorkspaceId,
156        workspace: &WeakView<Workspace>,
157        cx: &mut AsyncAppContext,
158    ) -> Option<(Member, Option<View<Pane>>, Vec<Option<Box<dyn ItemHandle>>>)> {
159        match self {
160            SerializedPaneGroup::Group {
161                axis,
162                children,
163                flexes,
164            } => {
165                let mut current_active_pane = None;
166                let mut members = Vec::new();
167                let mut items = Vec::new();
168                for child in children {
169                    if let Some((new_member, active_pane, new_items)) = child
170                        .deserialize(project, workspace_id, workspace, cx)
171                        .await
172                    {
173                        members.push(new_member);
174                        items.extend(new_items);
175                        current_active_pane = current_active_pane.or(active_pane);
176                    }
177                }
178
179                if members.is_empty() {
180                    return None;
181                }
182
183                if members.len() == 1 {
184                    return Some((members.remove(0), current_active_pane, items));
185                }
186
187                Some((
188                    Member::Axis(PaneAxis::load(axis, members, flexes)),
189                    current_active_pane,
190                    items,
191                ))
192            }
193            SerializedPaneGroup::Pane(serialized_pane) => {
194                let pane = workspace
195                    .update(cx, |workspace, cx| workspace.add_pane(cx).downgrade())
196                    .log_err()?;
197                let active = serialized_pane.active;
198                let new_items = serialized_pane
199                    .deserialize_to(project, &pane, workspace_id, workspace, cx)
200                    .await
201                    .log_err()?;
202
203                if pane
204                    .read_with(cx, |pane, _| pane.items_len() != 0)
205                    .log_err()?
206                {
207                    let pane = pane.upgrade()?;
208                    Some((Member::Pane(pane.clone()), active.then(|| pane), new_items))
209                } else {
210                    let pane = pane.upgrade()?;
211                    workspace
212                        .update(cx, |workspace, cx| workspace.force_remove_pane(&pane, cx))
213                        .log_err()?;
214                    None
215                }
216            }
217        }
218    }
219}
220
221#[derive(Debug, PartialEq, Eq, Default, Clone)]
222pub struct SerializedPane {
223    pub(crate) active: bool,
224    pub(crate) children: Vec<SerializedItem>,
225}
226
227impl SerializedPane {
228    pub fn new(children: Vec<SerializedItem>, active: bool) -> Self {
229        SerializedPane { children, active }
230    }
231
232    pub async fn deserialize_to(
233        &self,
234        project: &Handle<Project>,
235        pane: &WeakView<Pane>,
236        workspace_id: WorkspaceId,
237        workspace: &WeakView<Workspace>,
238        cx: &mut AsyncAppContext,
239    ) -> Result<Vec<Option<Box<dyn ItemHandle>>>> {
240        let mut items = Vec::new();
241        let mut active_item_index = None;
242        for (index, item) in self.children.iter().enumerate() {
243            let project = project.clone();
244            let item_handle = pane
245                .update(cx, |_, cx| {
246                    if let Some(deserializer) = cx.global::<ItemDeserializers>().get(&item.kind) {
247                        deserializer(project, workspace.clone(), workspace_id, item.item_id, cx)
248                    } else {
249                        Task::ready(Err(anyhow::anyhow!(
250                            "Deserializer does not exist for item kind: {}",
251                            item.kind
252                        )))
253                    }
254                })?
255                .await
256                .log_err();
257
258            items.push(item_handle.clone());
259
260            if let Some(item_handle) = item_handle {
261                pane.update(cx, |pane, cx| {
262                    pane.add_item(item_handle.clone(), true, true, None, cx);
263                })?;
264            }
265
266            if item.active {
267                active_item_index = Some(index);
268            }
269        }
270
271        if let Some(active_item_index) = active_item_index {
272            pane.update(cx, |pane, cx| {
273                pane.activate_item(active_item_index, false, false, cx);
274            })?;
275        }
276
277        anyhow::Ok(items)
278    }
279}
280
281pub type GroupId = i64;
282pub type PaneId = i64;
283pub type ItemId = usize;
284
285#[derive(Debug, PartialEq, Eq, Clone)]
286pub struct SerializedItem {
287    pub kind: Arc<str>,
288    pub item_id: ItemId,
289    pub active: bool,
290}
291
292impl SerializedItem {
293    pub fn new(kind: impl AsRef<str>, item_id: ItemId, active: bool) -> Self {
294        Self {
295            kind: Arc::from(kind.as_ref()),
296            item_id,
297            active,
298        }
299    }
300}
301
302#[cfg(test)]
303impl Default for SerializedItem {
304    fn default() -> Self {
305        SerializedItem {
306            kind: Arc::from("Terminal"),
307            item_id: 100000,
308            active: false,
309        }
310    }
311}
312
313impl StaticColumnCount for SerializedItem {
314    fn column_count() -> usize {
315        3
316    }
317}
318impl Bind for &SerializedItem {
319    fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
320        let next_index = statement.bind(&self.kind, start_index)?;
321        let next_index = statement.bind(&self.item_id, next_index)?;
322        statement.bind(&self.active, next_index)
323    }
324}
325
326impl Column for SerializedItem {
327    fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
328        let (kind, next_index) = Arc::<str>::column(statement, start_index)?;
329        let (item_id, next_index) = ItemId::column(statement, next_index)?;
330        let (active, next_index) = bool::column(statement, next_index)?;
331        Ok((
332            SerializedItem {
333                kind,
334                item_id,
335                active,
336            },
337            next_index,
338        ))
339    }
340}