Skip to main content

crisol_core/state/layout/
mod.rs

1//! Layouts as data: editor groups, splits, tabs, named layouts, and focus tools.
2//!
3//! The layout is a serializable tree. A host can save it with the workspace, switch
4//! named layouts from the palette, and drive every drag with a keyboard action; the UI
5//! is a view of this tree, not the source of truth.
6//!
7//! ```
8//! use crisol_core::state::layout;
9//! ```
10
11mod node;
12
13pub use node::{EditorGroup, EditorGroupId, LayoutNode, LayoutTab, SplitDirection};
14
15use std::collections::VecDeque;
16
17/// The whole layout.
18#[derive(Clone, Debug, PartialEq)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20#[cfg_attr(feature = "serde", serde(default))]
21#[non_exhaustive]
22/// # Example
23///
24/// ```
25/// use crisol_core::state::Layout;
26/// ```
27pub struct Layout {
28    /// File format version.
29    pub version: u32,
30    /// The tree.
31    pub root: LayoutNode,
32    /// The focused group.
33    pub active: EditorGroupId,
34    /// A maximized group (the rest are hidden until restored).
35    pub maximized: Option<EditorGroupId>,
36    /// Zen mode hides the side bars, status bar, and activity bar.
37    pub zen: bool,
38    /// The last closed tabs, newest first.
39    pub closed: VecDeque<LayoutTab>,
40    next_id: u64,
41}
42
43impl Default for Layout {
44    fn default() -> Self {
45        Self {
46            version: Self::VERSION,
47            root: LayoutNode::Group(EditorGroup::new(EditorGroupId(0))),
48            active: EditorGroupId(0),
49            maximized: None,
50            zen: false,
51            closed: VecDeque::new(),
52            next_id: 1,
53        }
54    }
55}
56
57impl Layout {
58    /// The current file version.
59    pub const VERSION: u32 = 1;
60
61    /// A layout with one empty group.
62    pub fn single() -> Self {
63        Self::default()
64    }
65
66    /// A layout with one group and `tabs`.
67    pub fn with_tabs(tabs: Vec<LayoutTab>) -> Self {
68        Self {
69            root: LayoutNode::Group(EditorGroup::with_tabs(EditorGroupId(0), tabs)),
70            ..Self::default()
71        }
72    }
73
74    /// The group ids.
75    pub fn groups(&self) -> Vec<EditorGroupId> {
76        self.root.ids()
77    }
78
79    /// A group by id.
80    pub fn group(&self, id: EditorGroupId) -> Option<&EditorGroup> {
81        self.root.group(id)
82    }
83
84    /// A group by id, mutably.
85    pub fn group_mut(&mut self, id: EditorGroupId) -> Option<&mut EditorGroup> {
86        self.root.group_mut(id)
87    }
88
89    /// The focused group.
90    pub fn active_group(&self) -> Option<&EditorGroup> {
91        self.group(self.active)
92    }
93
94    /// Focus a group.
95    pub fn focus(&mut self, id: EditorGroupId) -> bool {
96        if self.group(id).is_some() {
97            self.active = id;
98            true
99        } else {
100            false
101        }
102    }
103
104    /// Split `group` and return the new group id.
105    ///
106    /// The original group keeps the first half; the new group is empty and focused.
107    pub fn split(&mut self, group: EditorGroupId, direction: SplitDirection) -> Option<EditorGroupId> {
108        let old = self.root.group(group)?.clone();
109        let new_id = EditorGroupId(self.next_id);
110        self.next_id += 1;
111        self.root = replace_group(
112            std::mem::replace(&mut self.root, LayoutNode::Group(EditorGroup::new(EditorGroupId(0)))),
113            group,
114            LayoutNode::Split {
115                direction,
116                ratio: 0.5,
117                first: Box::new(LayoutNode::Group(old)),
118                second: Box::new(LayoutNode::Group(EditorGroup::new(new_id))),
119            },
120        );
121        self.active = new_id;
122        Some(new_id)
123    }
124
125    /// Close a group, promoting its sibling. The last group cannot be closed.
126    pub fn close_group(&mut self, id: EditorGroupId) -> bool {
127        if self.groups().len() <= 1 || self.group(id).is_none() {
128            return false;
129        }
130        let removed = self.root.remove_group(id);
131        if removed {
132            if self.active == id
133                && let Some(first) = self.root.first_id()
134            {
135                self.active = first;
136            }
137            if self.maximized == Some(id) {
138                self.maximized = None;
139            }
140        }
141        removed
142    }
143
144    /// Move a tab from one group to another. Returns whether it moved.
145    pub fn move_tab(&mut self, from: EditorGroupId, index: usize, to: EditorGroupId, target: usize) -> bool {
146        if from == to || !self.groups().contains(&to) {
147            return false;
148        }
149        let Some(tab) = self
150            .group_mut(from)
151            .and_then(|group| (index < group.tabs.len()).then(|| group.tabs.remove(index)))
152        else {
153            return false;
154        };
155        if let Some(group) = self.group_mut(from) {
156            group.normalize();
157        }
158        let Some(group) = self.group_mut(to) else {
159            return false;
160        };
161        let target = target.min(group.tabs.len());
162        group.tabs.insert(target, tab);
163        group.active = target;
164        self.active = to;
165        true
166    }
167
168    /// Close a tab and remember it for Reopen.
169    pub fn close_tab(&mut self, group: EditorGroupId, index: usize) -> Option<LayoutTab> {
170        let tab = self
171            .group_mut(group)
172            .and_then(|group| (index < group.tabs.len()).then(|| group.tabs.remove(index)))?;
173        if let Some(group) = self.group_mut(group) {
174            group.normalize();
175        }
176        self.closed.push_front(tab.clone());
177        self.closed.truncate(20);
178        Some(tab)
179    }
180
181    /// Reopen the newest closed tab in the focused group.
182    pub fn reopen_closed(&mut self) -> Option<LayoutTab> {
183        let tab = self.closed.pop_front()?;
184        let Some(group) = self.group_mut(self.active) else {
185            self.closed.push_front(tab);
186            return None;
187        };
188        group.tabs.push(tab.clone());
189        group.active = group.tabs.len() - 1;
190        Some(tab)
191    }
192
193    /// Pin or unpin a tab.
194    pub fn pin_tab(&mut self, group: EditorGroupId, index: usize, pinned: bool) -> bool {
195        let Some(tab) = self.group_mut(group).and_then(|group| group.tabs.get_mut(index)) else {
196            return false;
197        };
198        tab.pinned = pinned;
199        if pinned {
200            tab.preview = false;
201        }
202        true
203    }
204
205    /// Maximize a group, or restore with `None`.
206    pub fn maximize(&mut self, group: Option<EditorGroupId>) -> bool {
207        if let Some(group) = group
208            && self.group(group).is_none()
209        {
210            return false;
211        }
212        self.maximized = group;
213        true
214    }
215
216    /// Toggle Zen mode.
217    pub fn set_zen(&mut self, zen: bool) {
218        self.zen = zen;
219    }
220
221    /// Clamp active indices and the focused group after a load.
222    #[allow(clippy::indexing_slicing)]
223    pub fn normalize(&mut self) {
224        for id in self.groups() {
225            if let Some(group) = self.group_mut(id) {
226                group.normalize();
227            }
228        }
229        if self.group(self.active).is_none()
230            && let Some(first) = self.root.first_id()
231        {
232            self.active = first;
233        }
234        if let Some(maximized) = self.maximized
235            && self.group(maximized).is_none()
236        {
237            self.maximized = None;
238        }
239        self.closed.truncate(20);
240    }
241
242    /// A JSON representation, for a host or a test.
243    ///
244    /// # Errors
245    /// When serialization fails (it does not for this type).
246    #[cfg(feature = "serde")]
247    pub fn to_json(&self) -> Result<String, LayoutError> {
248        serde_json::to_string_pretty(self).map_err(|error| LayoutError::Json(error.to_string()))
249    }
250
251    /// Parse a layout, rejecting a newer version.
252    ///
253    /// # Errors
254    /// When the JSON is malformed or the version is newer than [`Self::VERSION`].
255    #[cfg(feature = "serde")]
256    pub fn from_json(json: &str) -> Result<Self, LayoutError> {
257        let mut layout: Self = serde_json::from_str(json).map_err(|error| LayoutError::Json(error.to_string()))?;
258        if layout.version > Self::VERSION {
259            return Err(LayoutError::UnsupportedVersion(layout.version));
260        }
261        if layout.version < Self::VERSION {
262            layout.version = Self::VERSION;
263        }
264        layout.normalize();
265        Ok(layout)
266    }
267}
268
269fn replace_group(node: LayoutNode, id: EditorGroupId, replacement: LayoutNode) -> LayoutNode {
270    match node {
271        LayoutNode::Group(group) if group.id == id => replacement,
272        LayoutNode::Group(group) => LayoutNode::Group(group),
273        LayoutNode::Split {
274            direction,
275            ratio,
276            first,
277            second,
278        } => LayoutNode::Split {
279            direction,
280            ratio,
281            first: Box::new(replace_group(*first, id, replacement.clone())),
282            second: Box::new(replace_group(*second, id, replacement)),
283        },
284    }
285}
286
287/// A keyboard-drivable layout action. Every drag has one of these equivalents.
288#[derive(Clone, Copy, Debug, PartialEq, Eq)]
289#[non_exhaustive]
290/// # Example
291///
292/// ```
293/// use crisol_core::state::layout::LayoutAction;
294/// ```
295pub enum LayoutAction {
296    /// Split the focused group horizontally.
297    SplitRight,
298    /// Split the focused group vertically.
299    SplitDown,
300    /// Focus the next group.
301    FocusNext,
302    /// Focus the previous group.
303    FocusPrevious,
304    /// Move the active tab to the next group.
305    MoveTabToNextGroup,
306    /// Close the focused group.
307    CloseGroup,
308    /// Maximize or restore the focused group.
309    ToggleMaximize,
310    /// Toggle Zen mode.
311    ToggleZen,
312    /// Reopen the last closed tab.
313    ReopenClosed,
314}
315
316impl Layout {
317    /// Apply a keyboard action. Returns whether the layout changed.
318    #[allow(clippy::indexing_slicing)]
319    pub fn apply(&mut self, action: LayoutAction) -> bool {
320        match action {
321            LayoutAction::SplitRight => self.split(self.active, SplitDirection::Horizontal).is_some(),
322            LayoutAction::SplitDown => self.split(self.active, SplitDirection::Vertical).is_some(),
323            LayoutAction::FocusNext => self.cycle_focus(1),
324            LayoutAction::FocusPrevious => self.cycle_focus(-1),
325            LayoutAction::MoveTabToNextGroup => self.move_active_tab_to_next(),
326            LayoutAction::CloseGroup => self.close_group(self.active),
327            LayoutAction::ToggleMaximize => self.maximize(if self.maximized.is_some() {
328                None
329            } else {
330                Some(self.active)
331            }),
332            LayoutAction::ToggleZen => {
333                self.zen = !self.zen;
334                true
335            }
336            LayoutAction::ReopenClosed => self.reopen_closed().is_some(),
337        }
338    }
339
340    fn cycle_focus(&mut self, step: isize) -> bool {
341        let groups = self.groups();
342        if groups.len() <= 1 {
343            return false;
344        }
345        let Some(current) = groups.iter().position(|id| *id == self.active) else {
346            return false;
347        };
348        let next = (current as isize + step).rem_euclid(groups.len() as isize) as usize;
349        let Some(id) = groups.get(next) else {
350            return false;
351        };
352        self.active = *id;
353        true
354    }
355
356    fn move_active_tab_to_next(&mut self) -> bool {
357        let groups = self.groups();
358        if groups.len() <= 1 {
359            return false;
360        }
361        let Some(current) = groups.iter().position(|id| *id == self.active) else {
362            return false;
363        };
364        let Some(next) = groups.get((current + 1) % groups.len()).copied() else {
365            return false;
366        };
367        let index = self.active_group().map_or(0, |group| group.active);
368        if self.group(self.active).is_none_or(|group| index >= group.tabs.len()) {
369            return false;
370        }
371        self.move_tab(self.active, index, next, 0)
372    }
373}
374
375/// Why a layout could not be read or written.
376#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
377#[non_exhaustive]
378/// # Example
379///
380/// ```
381/// use crisol_core::state::layout::LayoutError;
382/// ```
383pub enum LayoutError {
384    /// Malformed JSON.
385    #[error("invalid layout JSON: {0}")]
386    Json(String),
387    /// A newer file version.
388    #[error("unsupported layout version {0}")]
389    UnsupportedVersion(u32),
390}
391
392#[cfg(test)]
393mod tests;