model.rs

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