crisol_core/state/layout/
mod.rs1mod node;
12
13pub use node::{EditorGroup, EditorGroupId, LayoutNode, LayoutTab, SplitDirection};
14
15#[derive(Clone, Debug, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[non_exhaustive]
19pub struct FloatingPanel {
28 pub id: String,
30 pub rect: [f32; 4],
32 pub visible: bool,
34}
35
36impl FloatingPanel {
37 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#[derive(Clone, Debug, PartialEq)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
52#[cfg_attr(feature = "serde", serde(default))]
53#[non_exhaustive]
54pub struct Layout {
60 pub version: u32,
62 pub root: LayoutNode,
64 pub active: EditorGroupId,
66 pub maximized: Option<EditorGroupId>,
68 pub zen: bool,
70 pub closed: VecDeque<LayoutTab>,
72 #[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 pub const VERSION: u32 = 1;
96
97 pub fn single() -> Self {
99 Self::default()
100 }
101
102 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 pub fn groups(&self) -> Vec<EditorGroupId> {
112 self.root.ids()
113 }
114
115 pub fn group(&self, id: EditorGroupId) -> Option<&EditorGroup> {
117 self.root.group(id)
118 }
119
120 pub fn group_mut(&mut self, id: EditorGroupId) -> Option<&mut EditorGroup> {
122 self.root.group_mut(id)
123 }
124
125 pub fn active_group(&self) -> Option<&EditorGroup> {
127 self.group(self.active)
128 }
129
130 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 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 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 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 pub fn floating_panel(&self, id: &str) -> Option<&FloatingPanel> {
183 self.floating.iter().find(|panel| panel.id == id)
184 }
185
186 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 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 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 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 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 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 pub fn set_zen(&mut self, zen: bool) {
279 self.zen = zen;
280 }
281
282 #[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 #[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 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
350#[non_exhaustive]
351pub enum LayoutAction {
357 SplitRight,
359 SplitDown,
361 FocusNext,
363 FocusPrevious,
365 MoveTabToNextGroup,
367 CloseGroup,
369 ToggleMaximize,
371 ToggleZen,
373 ReopenClosed,
375}
376
377impl Layout {
378 #[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#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
438#[non_exhaustive]
439pub enum LayoutError {
445 #[error("invalid layout JSON: {0}")]
447 Json(String),
448 #[error("unsupported layout version {0}")]
450 UnsupportedVersion(u32),
451}
452
453#[cfg(test)]
454mod tests;