mod node;
pub use node::{EditorGroup, EditorGroupId, LayoutNode, LayoutTab, SplitDirection};
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct FloatingPanel {
pub id: String,
pub rect: [f32; 4],
pub visible: bool,
}
impl FloatingPanel {
pub fn new(id: impl Into<String>, rect: [f32; 4]) -> Self {
Self {
id: id.into(),
rect,
visible: true,
}
}
}
use std::collections::VecDeque;
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
#[non_exhaustive]
pub struct Layout {
pub version: u32,
pub root: LayoutNode,
pub active: EditorGroupId,
pub maximized: Option<EditorGroupId>,
pub zen: bool,
pub closed: VecDeque<LayoutTab>,
#[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 {
pub const VERSION: u32 = 1;
pub fn single() -> Self {
Self::default()
}
pub fn with_tabs(tabs: Vec<LayoutTab>) -> Self {
Self {
root: LayoutNode::Group(EditorGroup::with_tabs(EditorGroupId(0), tabs)),
..Self::default()
}
}
pub fn groups(&self) -> Vec<EditorGroupId> {
self.root.ids()
}
pub fn group(&self, id: EditorGroupId) -> Option<&EditorGroup> {
self.root.group(id)
}
pub fn group_mut(&mut self, id: EditorGroupId) -> Option<&mut EditorGroup> {
self.root.group_mut(id)
}
pub fn active_group(&self) -> Option<&EditorGroup> {
self.group(self.active)
}
pub fn focus(&mut self, id: EditorGroupId) -> bool {
if self.group(id).is_some() {
self.active = id;
true
} else {
false
}
}
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)
}
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);
}
}
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
}
}
pub fn floating_panel(&self, id: &str) -> Option<&FloatingPanel> {
self.floating.iter().find(|panel| panel.id == id)
}
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
}
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
}
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)
}
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)
}
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
}
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
}
pub fn set_zen(&mut self, zen: bool) {
self.zen = zen;
}
#[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);
}
#[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()))
}
#[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)),
},
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum LayoutAction {
SplitRight,
SplitDown,
FocusNext,
FocusPrevious,
MoveTabToNextGroup,
CloseGroup,
ToggleMaximize,
ToggleZen,
ReopenClosed,
}
impl Layout {
#[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)
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum LayoutError {
#[error("invalid layout JSON: {0}")]
Json(String),
#[error("unsupported layout version {0}")]
UnsupportedVersion(u32),
}
#[cfg(test)]
mod tests;