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