model.rs

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