model.rs

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