Make VersionedCanvas update function easier to use

This commit is contained in:
Francesco Magliocca 2020-11-11 20:12:52 +01:00
parent 2ddfef8416
commit d456725e23
2 changed files with 12 additions and 8 deletions

View File

@ -103,7 +103,13 @@ impl VersionedCanvas {
} }
} }
pub fn update(&mut self, update_fn: impl FnOnce(&Canvas) -> Canvas) { pub fn update(&mut self, update_fn: impl FnOnce(&mut Canvas)) {
// Make a new copy of the current canvas version,
// so that we can safely modify it without losing
// the previous canvas version
let mut new_version = self.get().clone();
update_fn(&mut new_version);
// This is a linear history, // This is a linear history,
// so we first check if there are newer versions, if so // so we first check if there are newer versions, if so
// this means we are in the past, so a change in the past destroys the future // this means we are in the past, so a change in the past destroys the future
@ -111,13 +117,15 @@ impl VersionedCanvas {
if self.has_newer_versions() { if self.has_newer_versions() {
self.versions = self.versions.take(self.curr_version + 1); self.versions = self.versions.take(self.curr_version + 1);
} }
let new_version = update_fn(self.get());
self.versions.push_back(new_version); self.versions.push_back(new_version);
self.curr_version = self.curr_version + 1; self.curr_version = self.curr_version + 1;
} }
// Do inplace update, which will be irreversible // Do inplace update, which will be irreversible
pub fn irreversible_update(&mut self, update_fn: impl FnOnce(&mut Canvas)) { pub fn irreversible_update(&mut self, update_fn: impl FnOnce(&mut Canvas)) {
// Do the update directly on the current canvas version
update_fn(self.versions.back_mut().unwrap());
// This is a linear history, // This is a linear history,
// so we first check if there are newer versions, if so // so we first check if there are newer versions, if so
// this means we are in the past, so a change in the past destroys the future // this means we are in the past, so a change in the past destroys the future
@ -125,8 +133,6 @@ impl VersionedCanvas {
if self.has_newer_versions() { if self.has_newer_versions() {
self.versions = self.versions.take(self.curr_version + 1); self.versions = self.versions.take(self.curr_version + 1);
} }
update_fn(self.versions.back_mut().unwrap());
} }
} }

View File

@ -89,10 +89,8 @@ impl Widget<CanvasData> for CanvasWidget {
if data.is_drawing() { if data.is_drawing() {
if let Some(current_element) = data.current_element.take() { if let Some(current_element) = data.current_element.take() {
data.elements.update(move |canvas: &Canvas| -> Canvas { data.elements.update(move |canvas: &mut Canvas| {
let mut new_canvas = canvas.clone(); canvas.push_back(current_element);
new_canvas.push_back(current_element);
new_canvas
}); });
} }