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