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