crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Layouts as data: editor groups, splits, tabs, named layouts, and focus tools.
//!
//! The layout is a serializable tree. A host can save it with the workspace, switch
//! named layouts from the palette, and drive every drag with a keyboard action; the UI
//! is a view of this tree, not the source of truth.
//!
//! ```
//! use crisol_core::state::layout;
//! ```

mod node;

pub use node::{EditorGroup, EditorGroupId, LayoutNode, LayoutTab, SplitDirection};

/// A free-floating panel (a tool window, not a split).
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::FloatingPanel;
///
/// let panel = FloatingPanel::new("inspector", [20.0, 40.0, 320.0, 200.0]);
/// assert!(panel.visible);
/// ```
pub struct FloatingPanel {
    /// Stable application id.
    pub id: String,
    /// Screen rectangle: x, y, width, height.
    pub rect: [f32; 4],
    /// Whether it is visible.
    pub visible: bool,
}

impl FloatingPanel {
    /// A visible floating panel.
    pub fn new(id: impl Into<String>, rect: [f32; 4]) -> Self {
        Self {
            id: id.into(),
            rect,
            visible: true,
        }
    }
}

use std::collections::VecDeque;

/// The whole layout.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::Layout;
/// ```
pub struct Layout {
    /// File format version.
    pub version: u32,
    /// The tree.
    pub root: LayoutNode,
    /// The focused group.
    pub active: EditorGroupId,
    /// A maximized group (the rest are hidden until restored).
    pub maximized: Option<EditorGroupId>,
    /// Zen mode hides the side bars, status bar, and activity bar.
    pub zen: bool,
    /// The last closed tabs, newest first.
    pub closed: VecDeque<LayoutTab>,
    /// Free-floating panels, with their screen rectangles.
    #[cfg_attr(feature = "serde", serde(default))]
    pub floating: Vec<FloatingPanel>,
    next_id: u64,
}

impl Default for Layout {
    fn default() -> Self {
        Self {
            version: Self::VERSION,
            root: LayoutNode::Group(EditorGroup::new(EditorGroupId(0))),
            active: EditorGroupId(0),
            maximized: None,
            zen: false,
            closed: VecDeque::new(),
            floating: Vec::new(),
            next_id: 1,
        }
    }
}

impl Layout {
    /// The current file version.
    pub const VERSION: u32 = 1;

    /// A layout with one empty group.
    pub fn single() -> Self {
        Self::default()
    }

    /// A layout with one group and `tabs`.
    pub fn with_tabs(tabs: Vec<LayoutTab>) -> Self {
        Self {
            root: LayoutNode::Group(EditorGroup::with_tabs(EditorGroupId(0), tabs)),
            ..Self::default()
        }
    }

    /// The group ids.
    pub fn groups(&self) -> Vec<EditorGroupId> {
        self.root.ids()
    }

    /// A group by id.
    pub fn group(&self, id: EditorGroupId) -> Option<&EditorGroup> {
        self.root.group(id)
    }

    /// A group by id, mutably.
    pub fn group_mut(&mut self, id: EditorGroupId) -> Option<&mut EditorGroup> {
        self.root.group_mut(id)
    }

    /// The focused group.
    pub fn active_group(&self) -> Option<&EditorGroup> {
        self.group(self.active)
    }

    /// Focus a group.
    pub fn focus(&mut self, id: EditorGroupId) -> bool {
        if self.group(id).is_some() {
            self.active = id;
            true
        } else {
            false
        }
    }

    /// Split `group` and return the new group id.
    ///
    /// The original group keeps the first half; the new group is empty and focused.
    pub fn split(&mut self, group: EditorGroupId, direction: SplitDirection) -> Option<EditorGroupId> {
        let old = self.root.group(group)?.clone();
        let new_id = EditorGroupId(self.next_id);
        self.next_id += 1;
        self.root = replace_group(
            std::mem::replace(&mut self.root, LayoutNode::Group(EditorGroup::new(EditorGroupId(0)))),
            group,
            LayoutNode::Split {
                direction,
                ratio: 0.5,
                first: Box::new(LayoutNode::Group(old)),
                second: Box::new(LayoutNode::Group(EditorGroup::new(new_id))),
            },
        );
        self.active = new_id;
        Some(new_id)
    }

    /// Open or raise a floating panel.
    pub fn float(&mut self, panel: FloatingPanel) {
        if let Some(existing) = self.floating.iter_mut().find(|candidate| candidate.id == panel.id) {
            existing.rect = panel.rect;
            existing.visible = true;
        } else {
            self.floating.push(panel);
        }
    }

    /// Close a floating panel by id.
    pub fn close_floating(&mut self, id: &str) -> bool {
        if let Some(index) = self.floating.iter().position(|panel| panel.id == id) {
            self.floating.remove(index);
            true
        } else {
            false
        }
    }

    /// A floating panel by id.
    pub fn floating_panel(&self, id: &str) -> Option<&FloatingPanel> {
        self.floating.iter().find(|panel| panel.id == id)
    }

    /// Close a group, promoting its sibling. The last group cannot be closed.
    pub fn close_group(&mut self, id: EditorGroupId) -> bool {
        if self.groups().len() <= 1 || self.group(id).is_none() {
            return false;
        }
        let removed = self.root.remove_group(id);
        if removed {
            if self.active == id
                && let Some(first) = self.root.first_id()
            {
                self.active = first;
            }
            if self.maximized == Some(id) {
                self.maximized = None;
            }
        }
        removed
    }

    /// Move a tab from one group to another. Returns whether it moved.
    pub fn move_tab(&mut self, from: EditorGroupId, index: usize, to: EditorGroupId, target: usize) -> bool {
        if from == to || !self.groups().contains(&to) {
            return false;
        }
        let Some(tab) = self
            .group_mut(from)
            .and_then(|group| (index < group.tabs.len()).then(|| group.tabs.remove(index)))
        else {
            return false;
        };
        if let Some(group) = self.group_mut(from) {
            group.normalize();
        }
        let Some(group) = self.group_mut(to) else {
            return false;
        };
        let target = target.min(group.tabs.len());
        group.tabs.insert(target, tab);
        group.active = target;
        self.active = to;
        true
    }

    /// Close a tab and remember it for Reopen.
    pub fn close_tab(&mut self, group: EditorGroupId, index: usize) -> Option<LayoutTab> {
        let tab = self
            .group_mut(group)
            .and_then(|group| (index < group.tabs.len()).then(|| group.tabs.remove(index)))?;
        if let Some(group) = self.group_mut(group) {
            group.normalize();
        }
        self.closed.push_front(tab.clone());
        self.closed.truncate(20);
        Some(tab)
    }

    /// Reopen the newest closed tab in the focused group.
    pub fn reopen_closed(&mut self) -> Option<LayoutTab> {
        let tab = self.closed.pop_front()?;
        let Some(group) = self.group_mut(self.active) else {
            self.closed.push_front(tab);
            return None;
        };
        group.tabs.push(tab.clone());
        group.active = group.tabs.len() - 1;
        Some(tab)
    }

    /// Pin or unpin a tab.
    pub fn pin_tab(&mut self, group: EditorGroupId, index: usize, pinned: bool) -> bool {
        let Some(tab) = self.group_mut(group).and_then(|group| group.tabs.get_mut(index)) else {
            return false;
        };
        tab.pinned = pinned;
        if pinned {
            tab.preview = false;
        }
        true
    }

    /// Maximize a group, or restore with `None`.
    pub fn maximize(&mut self, group: Option<EditorGroupId>) -> bool {
        if let Some(group) = group
            && self.group(group).is_none()
        {
            return false;
        }
        self.maximized = group;
        true
    }

    /// Toggle Zen mode.
    pub fn set_zen(&mut self, zen: bool) {
        self.zen = zen;
    }

    /// Clamp active indices and the focused group after a load.
    #[allow(clippy::indexing_slicing)]
    pub fn normalize(&mut self) {
        for id in self.groups() {
            if let Some(group) = self.group_mut(id) {
                group.normalize();
            }
        }
        if self.group(self.active).is_none()
            && let Some(first) = self.root.first_id()
        {
            self.active = first;
        }
        if let Some(maximized) = self.maximized
            && self.group(maximized).is_none()
        {
            self.maximized = None;
        }
        self.closed.truncate(20);
    }

    /// A JSON representation, for a host or a test.
    ///
    /// # Errors
    /// When serialization fails (it does not for this type).
    #[cfg(feature = "serde")]
    pub fn to_json(&self) -> Result<String, LayoutError> {
        serde_json::to_string_pretty(self).map_err(|error| LayoutError::Json(error.to_string()))
    }

    /// Parse a layout, rejecting a newer version.
    ///
    /// # Errors
    /// When the JSON is malformed or the version is newer than [`Self::VERSION`].
    #[cfg(feature = "serde")]
    pub fn from_json(json: &str) -> Result<Self, LayoutError> {
        let mut layout: Self = serde_json::from_str(json).map_err(|error| LayoutError::Json(error.to_string()))?;
        if layout.version > Self::VERSION {
            return Err(LayoutError::UnsupportedVersion(layout.version));
        }
        if layout.version < Self::VERSION {
            layout.version = Self::VERSION;
        }
        layout.normalize();
        Ok(layout)
    }
}

fn replace_group(node: LayoutNode, id: EditorGroupId, replacement: LayoutNode) -> LayoutNode {
    match node {
        LayoutNode::Group(group) if group.id == id => replacement,
        LayoutNode::Group(group) => LayoutNode::Group(group),
        LayoutNode::Split {
            direction,
            ratio,
            first,
            second,
        } => LayoutNode::Split {
            direction,
            ratio,
            first: Box::new(replace_group(*first, id, replacement.clone())),
            second: Box::new(replace_group(*second, id, replacement)),
        },
    }
}

/// A keyboard-drivable layout action. Every drag has one of these equivalents.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::layout::LayoutAction;
/// ```
pub enum LayoutAction {
    /// Split the focused group horizontally.
    SplitRight,
    /// Split the focused group vertically.
    SplitDown,
    /// Focus the next group.
    FocusNext,
    /// Focus the previous group.
    FocusPrevious,
    /// Move the active tab to the next group.
    MoveTabToNextGroup,
    /// Close the focused group.
    CloseGroup,
    /// Maximize or restore the focused group.
    ToggleMaximize,
    /// Toggle Zen mode.
    ToggleZen,
    /// Reopen the last closed tab.
    ReopenClosed,
}

impl Layout {
    /// Apply a keyboard action. Returns whether the layout changed.
    #[allow(clippy::indexing_slicing)]
    pub fn apply(&mut self, action: LayoutAction) -> bool {
        match action {
            LayoutAction::SplitRight => self.split(self.active, SplitDirection::Horizontal).is_some(),
            LayoutAction::SplitDown => self.split(self.active, SplitDirection::Vertical).is_some(),
            LayoutAction::FocusNext => self.cycle_focus(1),
            LayoutAction::FocusPrevious => self.cycle_focus(-1),
            LayoutAction::MoveTabToNextGroup => self.move_active_tab_to_next(),
            LayoutAction::CloseGroup => self.close_group(self.active),
            LayoutAction::ToggleMaximize => self.maximize(if self.maximized.is_some() {
                None
            } else {
                Some(self.active)
            }),
            LayoutAction::ToggleZen => {
                self.zen = !self.zen;
                true
            }
            LayoutAction::ReopenClosed => self.reopen_closed().is_some(),
        }
    }

    fn cycle_focus(&mut self, step: isize) -> bool {
        let groups = self.groups();
        if groups.len() <= 1 {
            return false;
        }
        let Some(current) = groups.iter().position(|id| *id == self.active) else {
            return false;
        };
        let next = (current as isize + step).rem_euclid(groups.len() as isize) as usize;
        let Some(id) = groups.get(next) else {
            return false;
        };
        self.active = *id;
        true
    }

    fn move_active_tab_to_next(&mut self) -> bool {
        let groups = self.groups();
        if groups.len() <= 1 {
            return false;
        }
        let Some(current) = groups.iter().position(|id| *id == self.active) else {
            return false;
        };
        let Some(next) = groups.get((current + 1) % groups.len()).copied() else {
            return false;
        };
        let index = self.active_group().map_or(0, |group| group.active);
        if self.group(self.active).is_none_or(|group| index >= group.tabs.len()) {
            return false;
        }
        self.move_tab(self.active, index, next, 0)
    }
}

/// Why a layout could not be read or written.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::layout::LayoutError;
/// ```
pub enum LayoutError {
    /// Malformed JSON.
    #[error("invalid layout JSON: {0}")]
    Json(String),
    /// A newer file version.
    #[error("unsupported layout version {0}")]
    UnsupportedVersion(u32),
}

#[cfg(test)]
mod tests;