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