Graphite/frontend/iced/src/layout.rs

71 lines
2.2 KiB
Rust

/// applies the editor's layout diffs. each diff is comprised of a widget_path and a new_value. empty path = swap the whole layout.
/// otherwise, descend one step each index. tables descend through [row, col] indexed cells.
use graphite_editor::messages::layout::utility_types::widget_prelude::*;
use std::collections::HashMap;
#[derive(Default)]
pub struct LayoutStore {
layouts: HashMap<LayoutTarget, Layout>,
}
impl LayoutStore {
pub fn apply(&mut self, target: LayoutTarget, diff: WidgetDiff) {
let layout = self.layouts.entry(target).or_default();
apply_diff_layout(layout, &diff.widget_path, diff.new_value);
}
pub fn get(&self, target: LayoutTarget) -> Option<&Layout> {
self.layouts.get(&target)
}
pub fn iter(&self) -> impl Iterator<Item = (&LayoutTarget, &Layout)> {
self.layouts.iter()
}
}
fn apply_diff_layout(layout: &mut Layout, path: &[usize], new_value: DiffUpdate) {
let Some((first, rest)) = path.split_first() else {
if let DiffUpdate::Layout(new) = new_value {
*layout = new;
}
return;
};
if let Some(group) = layout.0.get_mut(*first) {
apply_diff_group(group, rest, new_value);
}
}
fn apply_diff_group(group: &mut LayoutGroup, path: &[usize], new_value: DiffUpdate) {
let Some((first, rest)) = path.split_first() else {
if let DiffUpdate::LayoutGroup(new) = new_value {
*group = new;
}
return;
};
match group {
LayoutGroup::Column(WidgetColumn { widgets }) => apply_diff_instance(widgets.get_mut(*first), rest, new_value),
LayoutGroup::Row(WidgetRow { widgets }) => apply_diff_instance(widgets.get_mut(*first), rest, new_value),
LayoutGroup::Section(WidgetSection { layout, .. }) => {
if let Some(child) = layout.0.get_mut(*first) {
apply_diff_group(child, rest, new_value);
}
}
LayoutGroup::Table(WidgetTable { rows, .. }) => {
if let Some(table_row) = rows.get_mut(*first)
&& let Some((col, rest_after_col)) = rest.split_first()
{
apply_diff_instance(table_row.get_mut(*col), rest_after_col, new_value);
}
}
}
}
fn apply_diff_instance(slot: Option<&mut WidgetInstance>, rest: &[usize], new_value: DiffUpdate) {
if !rest.is_empty() {
return;
}
if let (Some(slot), DiffUpdate::Widget(new)) = (slot, new_value) {
*slot = new;
}
}