use brep_ecad_core::History;
use egui::Vec2;
use crate::{Change, HistoryKey};
pub(crate) struct EditorCore<Doc, Selection, Drag> {
pub history: History<Doc>,
pub pending_change: Option<Change>,
pub selected: Option<Selection>,
pub also: Vec<Selection>,
pub drag: Option<Drag>,
pub pan: Vec2,
pub zoom: f32,
}
impl<Doc, Selection: Copy + PartialEq, Drag> EditorCore<Doc, Selection, Drag> {
pub fn members(&self) -> Vec<Selection> {
let mut all = self.also.clone();
all.extend(self.selected);
all
}
pub fn count(&self) -> usize {
self.also.len() + usize::from(self.selected.is_some())
}
pub fn is_selected(&self, item: Selection) -> bool {
self.selected == Some(item) || self.also.contains(&item)
}
pub fn select_only(&mut self, item: Option<Selection>) {
self.selected = item;
self.also.clear();
}
pub fn add(&mut self, item: Selection) {
if self.selected == Some(item) {
return;
}
self.also.retain(|other| *other != item);
if let Some(primary) = self.selected.replace(item) {
self.also.push(primary);
}
}
pub fn toggle(&mut self, item: Selection) {
if self.selected == Some(item) {
self.selected = self.also.pop();
} else if self.also.contains(&item) {
self.also.retain(|other| *other != item);
} else {
self.add(item);
}
}
pub fn remove(&mut self, item: Selection) {
if self.is_selected(item) {
self.toggle(item);
}
}
pub fn select_all(&mut self, items: impl IntoIterator<Item = Selection>) {
self.select_only(None);
for item in items {
self.add(item);
}
}
}
impl<Doc: PartialEq, Selection, Drag> EditorCore<Doc, Selection, Drag> {
pub fn new(zoom: f32) -> Self {
Self {
history: History::default(), pending_change: None,
selected: None, also: Vec::new(), drag: None, pan: Vec2::ZERO, zoom,
}
}
pub fn zoom_about(&mut self, factor: f32, anchor: Vec2) {
crate::zoom_at(&mut self.zoom, &mut self.pan, factor, anchor);
}
pub fn record(&mut self, before: Doc, after: &Doc, coalesce: Option<&str>) {
if before != *after {
self.history.record(before, after);
self.note_change(coalesce.map(str::to_owned));
}
}
pub fn note_change(&mut self, coalesce: Option<String>) {
Change::record(&mut self.pending_change, coalesce);
}
pub fn take_change(&mut self) -> Option<Change> {
self.pending_change.take()
}
pub fn undo(&mut self, doc: &mut Doc) {
if self.history.can_undo() {
self.history.undo(doc);
self.selected = None;
self.also.clear();
self.note_change(None);
}
}
pub fn redo(&mut self, doc: &mut Doc) {
if self.history.can_redo() {
self.history.redo(doc);
self.selected = None;
self.also.clear();
self.note_change(None);
}
}
pub fn can_step_history(&self, key: HistoryKey) -> bool {
self.drag.is_none() && match key {
HistoryKey::Undo => self.history.can_undo(),
HistoryKey::Redo => self.history.can_redo(),
}
}
}