model.rs

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