crisol_core/state/layout/
mod.rs1mod node;
12
13pub use node::{EditorGroup, EditorGroupId, LayoutNode, LayoutTab, SplitDirection};
14
15use std::collections::VecDeque;
16
17#[derive(Clone, Debug, PartialEq)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20#[cfg_attr(feature = "serde", serde(default))]
21#[non_exhaustive]
22pub struct Layout {
28 pub version: u32,
30 pub root: LayoutNode,
32 pub active: EditorGroupId,
34 pub maximized: Option<EditorGroupId>,
36 pub zen: bool,
38 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 pub const VERSION: u32 = 1;
60
61 pub fn single() -> Self {
63 Self::default()
64 }
65
66 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 pub fn groups(&self) -> Vec<EditorGroupId> {
76 self.root.ids()
77 }
78
79 pub fn group(&self, id: EditorGroupId) -> Option<&EditorGroup> {
81 self.root.group(id)
82 }
83
84 pub fn group_mut(&mut self, id: EditorGroupId) -> Option<&mut EditorGroup> {
86 self.root.group_mut(id)
87 }
88
89 pub fn active_group(&self) -> Option<&EditorGroup> {
91 self.group(self.active)
92 }
93
94 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 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 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 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 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 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 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 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 pub fn set_zen(&mut self, zen: bool) {
218 self.zen = zen;
219 }
220
221 #[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 #[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 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
289#[non_exhaustive]
290pub enum LayoutAction {
296 SplitRight,
298 SplitDown,
300 FocusNext,
302 FocusPrevious,
304 MoveTabToNextGroup,
306 CloseGroup,
308 ToggleMaximize,
310 ToggleZen,
312 ReopenClosed,
314}
315
316impl Layout {
317 #[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#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
377#[non_exhaustive]
378pub enum LayoutError {
384 #[error("invalid layout JSON: {0}")]
386 Json(String),
387 #[error("unsupported layout version {0}")]
389 UnsupportedVersion(u32),
390}
391
392#[cfg(test)]
393mod tests;