[doc] Editor core: document model, exact undo, .pictor format, text layout, display list, tiny-skia render, bitmap tools, SVG import, PNG/JPG/SVG/PDF export; worker doc.open and doc.import_svg
This commit is contained in:
@@ -0,0 +1,321 @@
|
||||
//! Every edit is an [`Op`]. Applying one returns its exact inverse, so undo is applying inverses back; the
|
||||
//! [`History`] keeps both without a limit within a session.
|
||||
use crate::model::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case")]
|
||||
pub enum Op {
|
||||
InsertPage {
|
||||
index: usize,
|
||||
page: Page,
|
||||
},
|
||||
RemovePage {
|
||||
index: usize,
|
||||
},
|
||||
/// Size, margins, guides and paper colour (the layers are untouched).
|
||||
SetPage {
|
||||
page: Id,
|
||||
width: f32,
|
||||
height: f32,
|
||||
margins: [f32; 4],
|
||||
guides: Vec<Guide>,
|
||||
background: Option<Rgba>,
|
||||
},
|
||||
/// Into the page's layers (`parent` none) or a group layer's, at `index`.
|
||||
InsertLayer {
|
||||
page: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
layer: Layer,
|
||||
},
|
||||
RemoveLayer {
|
||||
page: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
},
|
||||
/// Name, visibility, lock, opacity and, for a bitmap layer, its placement (not its children).
|
||||
SetLayer {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
name: String,
|
||||
visible: bool,
|
||||
locked: bool,
|
||||
opacity: f32,
|
||||
place: Option<Rect>,
|
||||
},
|
||||
InsertObject {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
object: Object,
|
||||
},
|
||||
RemoveObject {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
parent: Option<Id>,
|
||||
index: usize,
|
||||
},
|
||||
/// The whole object with this id, replaced (a move, scale, colour or text change).
|
||||
ReplaceObject {
|
||||
page: Id,
|
||||
layer: Id,
|
||||
object: Object,
|
||||
},
|
||||
/// Pixels of an asset: `rect` gets `pixels` (w × h RGBA).
|
||||
Patch {
|
||||
asset: String,
|
||||
rect: PixelRect,
|
||||
#[serde(skip)]
|
||||
pixels: Vec<u8>,
|
||||
},
|
||||
/// Adds (`raster` some), replaces or removes (none) an asset.
|
||||
PutAsset {
|
||||
asset: String,
|
||||
#[serde(skip)]
|
||||
raster: Option<Raster>,
|
||||
},
|
||||
Batch {
|
||||
ops: Vec<Op>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
pub enum OpError {
|
||||
#[error("there is no page {0}")]
|
||||
NoPage(Id),
|
||||
#[error("there is no layer {0}")]
|
||||
NoLayer(Id),
|
||||
#[error("there is no object {0}")]
|
||||
NoObject(Id),
|
||||
#[error("there is no asset {0}")]
|
||||
NoAsset(String),
|
||||
#[error("index {0} is out of range")]
|
||||
Index(usize),
|
||||
#[error("layer {0} does not hold objects")]
|
||||
NotVector(Id),
|
||||
#[error("the pixels do not fit the rectangle")]
|
||||
PatchSize,
|
||||
}
|
||||
|
||||
/// Applies `op` and returns its inverse. On an error the document is unchanged.
|
||||
pub fn apply(doc: &mut Document, op: Op) -> Result<Op, OpError> {
|
||||
match op {
|
||||
Op::InsertPage { index, page } => {
|
||||
if index > doc.pages.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
doc.pages.insert(index, page);
|
||||
Ok(Op::RemovePage { index })
|
||||
}
|
||||
Op::RemovePage { index } => {
|
||||
if index >= doc.pages.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
let page = doc.pages.remove(index);
|
||||
Ok(Op::InsertPage { index, page })
|
||||
}
|
||||
Op::SetPage { page, width, height, margins, guides, background } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let inv = Op::SetPage {
|
||||
page,
|
||||
width: p.width,
|
||||
height: p.height,
|
||||
margins: p.margins,
|
||||
guides: std::mem::take(&mut p.guides),
|
||||
background: p.background,
|
||||
};
|
||||
p.width = width;
|
||||
p.height = height;
|
||||
p.margins = margins;
|
||||
p.guides = guides;
|
||||
p.background = background;
|
||||
Ok(inv)
|
||||
}
|
||||
Op::InsertLayer { page, parent, index, layer } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let list = p.layer_list_mut(parent).ok_or(OpError::NoLayer(parent.unwrap_or(0)))?;
|
||||
if index > list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
list.insert(index, layer);
|
||||
Ok(Op::RemoveLayer { page, parent, index })
|
||||
}
|
||||
Op::RemoveLayer { page, parent, index } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let list = p.layer_list_mut(parent).ok_or(OpError::NoLayer(parent.unwrap_or(0)))?;
|
||||
if index >= list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
let layer = list.remove(index);
|
||||
Ok(Op::InsertLayer { page, parent, index, layer })
|
||||
}
|
||||
Op::SetLayer { page, layer, name, visible, locked, opacity, place } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let old_place = match &mut l.kind {
|
||||
LayerKind::Bitmap { x, y, w, h, .. } => {
|
||||
let old = Rect { x: *x, y: *y, w: *w, h: *h };
|
||||
if let Some(r) = place {
|
||||
(*x, *y, *w, *h) = (r.x, r.y, r.w, r.h);
|
||||
}
|
||||
Some(old)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let inv = Op::SetLayer {
|
||||
page,
|
||||
layer,
|
||||
name: std::mem::replace(&mut l.name, name),
|
||||
visible: std::mem::replace(&mut l.visible, visible),
|
||||
locked: std::mem::replace(&mut l.locked, locked),
|
||||
opacity: std::mem::replace(&mut l.opacity, opacity),
|
||||
place: if place.is_some() { old_place } else { None },
|
||||
};
|
||||
Ok(inv)
|
||||
}
|
||||
Op::InsertObject { page, layer, parent, index, object } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let list = object_list_mut(l, parent).ok_or(match parent {
|
||||
Some(o) => OpError::NoObject(o),
|
||||
None => OpError::NotVector(layer),
|
||||
})?;
|
||||
if index > list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
list.insert(index, object);
|
||||
Ok(Op::RemoveObject { page, layer, parent, index })
|
||||
}
|
||||
Op::RemoveObject { page, layer, parent, index } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let list = object_list_mut(l, parent).ok_or(match parent {
|
||||
Some(o) => OpError::NoObject(o),
|
||||
None => OpError::NotVector(layer),
|
||||
})?;
|
||||
if index >= list.len() {
|
||||
return Err(OpError::Index(index));
|
||||
}
|
||||
let object = list.remove(index);
|
||||
Ok(Op::InsertObject { page, layer, parent, index, object })
|
||||
}
|
||||
Op::ReplaceObject { page, layer, object } => {
|
||||
let p = doc.page_mut(page).ok_or(OpError::NoPage(page))?;
|
||||
let l = p.layer_mut(layer).ok_or(OpError::NoLayer(layer))?;
|
||||
let o = find_object_mut(l, object.id).ok_or(OpError::NoObject(object.id))?;
|
||||
let old = std::mem::replace(o, object);
|
||||
Ok(Op::ReplaceObject { page, layer, object: old })
|
||||
}
|
||||
Op::Patch { asset, rect, pixels } => {
|
||||
let r = doc.assets.get_mut(&asset).ok_or_else(|| OpError::NoAsset(asset.clone()))?;
|
||||
if rect.clamp(r.width, r.height) != rect || pixels.len() != rect.w as usize * rect.h as usize * 4 {
|
||||
return Err(OpError::PatchSize);
|
||||
}
|
||||
let before = r.crop(rect);
|
||||
r.put(rect.x, rect.y, &Raster { width: rect.w, height: rect.h, rgba: pixels });
|
||||
Ok(Op::Patch { asset, rect, pixels: before.rgba })
|
||||
}
|
||||
Op::PutAsset { asset, raster } => {
|
||||
let old = match raster {
|
||||
Some(r) => doc.assets.insert(asset.clone(), r),
|
||||
None => doc.assets.remove(&asset),
|
||||
};
|
||||
Ok(Op::PutAsset { asset, raster: old })
|
||||
}
|
||||
Op::Batch { ops } => {
|
||||
let mut done: Vec<Op> = Vec::with_capacity(ops.len());
|
||||
for op in ops {
|
||||
match apply(doc, op) {
|
||||
Ok(inv) => done.push(inv),
|
||||
Err(e) => {
|
||||
// Roll back what was done, so a failed batch leaves no trace.
|
||||
for inv in done.into_iter().rev() {
|
||||
let _ = apply(doc, inv);
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
done.reverse();
|
||||
Ok(Op::Batch { ops: done })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A patch op for the rectangle `rect` that turns `before` into `after` (both the whole asset).
|
||||
pub fn patch_between(asset: &str, after: &Raster, rect: PixelRect) -> Op {
|
||||
Op::Patch { asset: asset.to_string(), rect, pixels: after.crop(rect).rgba }
|
||||
}
|
||||
|
||||
/// Done and undone operations, each with its inverse.
|
||||
#[derive(Default)]
|
||||
pub struct History {
|
||||
done: Vec<(Op, Op)>,
|
||||
undone: Vec<(Op, Op)>,
|
||||
/// Bumped on every change, so the face and "unsaved changes" can tell.
|
||||
pub revision: u64,
|
||||
saved_revision: u64,
|
||||
}
|
||||
|
||||
impl History {
|
||||
/// Applies an operation and records it.
|
||||
pub fn apply(&mut self, doc: &mut Document, op: Op) -> Result<(), OpError> {
|
||||
let inv = apply(doc, op.clone())?;
|
||||
self.done.push((op, inv));
|
||||
self.undone.clear();
|
||||
self.revision += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Records an operation that was applied outside (`op` was applied, `inverse` undoes it).
|
||||
pub fn record(&mut self, op: Op, inverse: Op) {
|
||||
self.done.push((op, inverse));
|
||||
self.undone.clear();
|
||||
self.revision += 1;
|
||||
}
|
||||
|
||||
pub fn undo(&mut self, doc: &mut Document) -> Result<bool, OpError> {
|
||||
let Some((op, inv)) = self.done.pop() else { return Ok(false) };
|
||||
match apply(doc, inv.clone()) {
|
||||
Ok(_) => {
|
||||
self.undone.push((op, inv));
|
||||
self.revision += 1;
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
self.done.push((op, inv));
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn redo(&mut self, doc: &mut Document) -> Result<bool, OpError> {
|
||||
let Some((op, inv)) = self.undone.pop() else { return Ok(false) };
|
||||
match apply(doc, op.clone()) {
|
||||
Ok(_) => {
|
||||
self.done.push((op, inv));
|
||||
self.revision += 1;
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
self.undone.push((op, inv));
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_undo(&self) -> bool {
|
||||
!self.done.is_empty()
|
||||
}
|
||||
pub fn can_redo(&self) -> bool {
|
||||
!self.undone.is_empty()
|
||||
}
|
||||
pub fn mark_saved(&mut self) {
|
||||
self.saved_revision = self.revision;
|
||||
}
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
self.revision != self.saved_revision
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user