Compare commits

...

8 Commits

Author SHA1 Message Date
Enrico Lumetti 9c7ef5a55b [WIP] Allow dragging selections 2021-03-23 16:49:16 +01:00
Enrico Lumetti 393394ed53 Add selection toolbar and working delete action 2021-03-23 16:49:16 +01:00
Enrico Lumetti f71211a9e7 Add state management to display selections correctly 2021-03-23 16:49:16 +01:00
Enrico Lumetti 13bac91dbc Make 'VersionedCanvas' into a generic 'Versioned<T>' data structure 2021-03-23 16:49:13 +01:00
Enrico Lumetti b3748a6faa Add basic axis-aligned selection tool (working but not integrated) 2021-03-23 16:47:59 +01:00
Enrico Lumetti 32740f3b22 Use serde_bare and update format version 2021-03-18 21:21:48 +01:00
Enrico Lumetti 6a2460c42f Implement basics for document migration 2021-03-18 15:21:18 +01:00
Enrico Lumetti 721ad1eecf Fix notification handling when tool is already selected 2021-03-10 23:29:03 +01:00
12 changed files with 584 additions and 44 deletions

110
Cargo.lock generated
View File

@ -162,6 +162,38 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "3.0.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bd1061998a501ee7d4b6d449020df3266ca3124b941ec56cf2005c3779ca142"
dependencies = [
"atty",
"bitflags",
"clap_derive",
"indexmap",
"lazy_static",
"os_str_bytes",
"strsim",
"termcolor",
"textwrap",
"unicode-width",
"vec_map",
]
[[package]]
name = "clap_derive"
version = "3.0.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "370f715b81112975b1b69db93e0b56ea4cd4e5002ac43b2da8474106a54096a1"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "cmake" name = "cmake"
version = "0.1.45" version = "0.1.45"
@ -852,6 +884,12 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "hashbrown"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04"
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.3.2" version = "0.3.2"
@ -884,6 +922,16 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "indexmap"
version = "1.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3"
dependencies = [
"autocfg",
"hashbrown",
]
[[package]] [[package]]
name = "instant" name = "instant"
version = "0.1.9" version = "0.1.9"
@ -1034,6 +1082,12 @@ version = "1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13bd41f508810a131401606d54ac32a467c97172d74ba7662562ebba5ad07fa0" checksum = "13bd41f508810a131401606d54ac32a467c97172d74ba7662562ebba5ad07fa0"
[[package]]
name = "os_str_bytes"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afb2e1c3ee07430c2cf76151675e583e0f19985fa6efae47d6848a3e2c824f85"
[[package]] [[package]]
name = "pango" name = "pango"
version = "0.9.1" version = "0.9.1"
@ -1343,6 +1397,15 @@ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]]
name = "serde_bare"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01db2255aa98fb93ad74272d8b2e6fd4851860e733e944b9439cf148127164b2"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.117" version = "1.0.117"
@ -1487,6 +1550,7 @@ checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0"
name = "stiletto" name = "stiletto"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"clap",
"druid", "druid",
"gdk", "gdk",
"gio", "gio",
@ -1494,9 +1558,16 @@ dependencies = [
"im", "im",
"log", "log",
"serde", "serde",
"serde_bare",
"serde_json", "serde_json",
] ]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]] [[package]]
name = "strum" name = "strum"
version = "0.18.0" version = "0.18.0"
@ -1551,6 +1622,24 @@ dependencies = [
"version-compare", "version-compare",
] ]
[[package]]
name = "termcolor"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dfed899f0eb03f32ee8c6a0aabdb8a7949659e3466561fc0adf54e26d88c5f4"
dependencies = [
"winapi-util",
]
[[package]]
name = "textwrap"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "203008d98caf094106cfaba70acfed15e18ed3ddb7d94e49baec153a2b462789"
dependencies = [
"unicode-width",
]
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "1.0.24" version = "1.0.24"
@ -1759,6 +1848,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"
[[package]]
name = "unicode-width"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.1" version = "0.2.1"
@ -1807,6 +1902,12 @@ dependencies = [
"getrandom", "getrandom",
] ]
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]] [[package]]
name = "version-compare" name = "version-compare"
version = "0.0.10" version = "0.0.10"
@ -1905,6 +2006,15 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
"winapi",
]
[[package]] [[package]]
name = "winapi-x86_64-pc-windows-gnu" name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0" version = "0.4.0"

View File

@ -3,18 +3,16 @@ name = "stiletto"
version = "0.1.0" version = "0.1.0"
authors = ["Enrico Lumetti <enrico.lumetti@gmail.com>"] authors = ["Enrico Lumetti <enrico.lumetti@gmail.com>"]
edition = "2018" edition = "2018"
default-run = "stiletto"
[dependencies] [dependencies]
log = "0.4" log = "0.4"
druid = { version = "0.7.0", features = ["im", "svg"] } druid = { version = "0.7.0", features = ["im", "svg"] }
im = { version = "*" } im = { version = "*" }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
#serde_bare = "0.3.0" serde_bare = "0.3.0"
serde_json = "1.0" serde_json = "1.0"
clap = "3.0.0-beta.2"
[patch.crates-io]
druid = { git = "https://github.com/doppioandante/druid", branch = "v0.7.0_stiletto", features = ["im", "svg"] }
#druid = { path = "../druid/druid/", features = ["im", "svg"] }
[target.'cfg(target_os="linux")'.dependencies.gtk] [target.'cfg(target_os="linux")'.dependencies.gtk]
version = "0.9.2" version = "0.9.2"
@ -27,3 +25,8 @@ features = ["v2_56"]
[target.'cfg(target_os="linux")'.dependencies.gdk] [target.'cfg(target_os="linux")'.dependencies.gdk]
version = "0.13.2" version = "0.13.2"
features = ["v3_22"] features = ["v3_22"]
[patch.crates-io]
druid = { git = "https://github.com/doppioandante/druid", branch = "v0.7.0_stiletto", features = ["im", "svg"] }
#druid = { path = "../druid/druid/", features = ["im", "svg"] }

48
src/bin/stlt_migrate.rs Normal file
View File

@ -0,0 +1,48 @@
// Stiletto
// Copyright (C) 2020 Stiletto Authors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use clap::{Arg, App};
use stiletto::migration::open_stiletto_document;
use std::fs::File;
use std::path::PathBuf;
fn main() {
let matches = App::new("Stiletto Migration CLI")
.version("0.1.0")
.author("Stiletto Authors")
.about("Migrate a stlt file to the latest version")
.arg(Arg::new("INPUT")
.about("Sets the input file to use")
.required(true)
.index(1))
.arg(Arg::new("OUTPUT")
.about("Sets the output file to use")
.required(true)
.index(2))
.get_matches();
let input_path = matches.value_of("INPUT").unwrap();
let output_path = matches.value_of("OUTPUT").unwrap();
let out_file = File::create(&output_path).expect("Cannot create output fle");
let result = open_stiletto_document(&PathBuf::from(&input_path));
if let Ok(document) = result {
let snapshot = document.migrate_to_latest();
snapshot.to_writer(out_file);
}
}

View File

@ -14,8 +14,6 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use std::vec::Vec;
use im::{vector, Vector}; use im::{vector, Vector};
use serde::de::{Deserializer, SeqAccess, Visitor}; use serde::de::{Deserializer, SeqAccess, Visitor};
@ -128,12 +126,26 @@ impl CanvasElement {
} }
} }
} }
pub fn draw_selected(&self, ctx: &mut druid::PaintCtx) {
match self {
CanvasElement::Freehand {
path,
thickness,
..
} => {
use druid::RenderContext;
ctx.stroke(&path.kurbo_path, &druid::Color::rgb(10.0, 0.0, 255.0), *thickness * 1.4);
}
}
}
} }
#[derive(Clone, druid::Data)] #[derive(Clone, druid::Data)]
pub struct Canvas { pub struct Canvas {
elements: Vector<CanvasElement>, elements: Vector<CanvasElement>,
content_size: druid::Size, content_size: druid::Size,
selected_elements: Vector<usize>,
} }
impl Canvas { impl Canvas {
@ -141,6 +153,7 @@ impl Canvas {
Canvas { Canvas {
elements: vector![], elements: vector![],
content_size: druid::Size::new(0.0, 0.0), content_size: druid::Size::new(0.0, 0.0),
selected_elements: vector![],
} }
} }
@ -165,25 +178,43 @@ impl Canvas {
&self.elements &self.elements
} }
/// Find all CanvasElement that intersect with rect pub fn has_elements_interesecting(&self, rect: druid::Rect) -> bool {
pub fn find_intersections(&self, rect: druid::Rect) -> Vec<usize> {
let mut found_elements = Vec::<usize>::new();
for (i, elem) in self.elements.iter().enumerate() { for (i, elem) in self.elements.iter().enumerate() {
// Check if the element intersects the eraser rect // Check if the element intersects the eraser rect
if elem.bounding_box().intersect(rect).area() > 0.0 { if elem.bounding_box().intersect(rect).area() > 0.0 {
if elem.intersects_rect(rect) { if elem.intersects_rect(rect) {
found_elements.push(i); return true;
} }
} }
} }
false
}
/// Find all CanvasElement that intersect with rect
pub fn find_elements_intersecting(&self, rect: druid::Rect) -> Vector<usize> {
let found_elements = self.elements.iter().enumerate()
.filter_map(|(i, elem)| {
if elem.bounding_box().intersect(rect).area() > 0.0 {
if elem.intersects_rect(rect) {
return Some(i);
}
}
None
}).collect::<Vector<usize>>();
found_elements found_elements
} }
pub fn content_size(&self) -> druid::Size { pub fn content_size(&self) -> druid::Size {
self.content_size self.content_size
} }
pub fn selected_elements(&self) -> &Vector<usize> {
&self.selected_elements
}
pub fn selected_elements_mut(&mut self) -> &mut Vector<usize> {
&mut self.selected_elements
}
} }
impl Serialize for Path { impl Serialize for Path {
@ -197,7 +228,7 @@ impl Serialize for Path {
PathEl::MoveTo(pt) => Some(Into::<(f64, f64)>::into(pt)), PathEl::MoveTo(pt) => Some(Into::<(f64, f64)>::into(pt)),
PathEl::LineTo(pt) => Some(Into::<(f64, f64)>::into(pt)), PathEl::LineTo(pt) => Some(Into::<(f64, f64)>::into(pt)),
_ => None, _ => None,
})) }).collect::<Vec<(f64, f64)>>())
} }
} }

View File

@ -14,27 +14,26 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use super::canvas::Canvas;
use im::Vector; use im::Vector;
#[derive(Clone, druid::Data)] #[derive(Clone, druid::Data)]
pub struct VersionedCanvas { pub struct Versioned<T: druid::Data + Clone> {
// We internally guarantee that this vector // We internally guarantee that this vector
// is never empty // is never empty
versions: Vector<Canvas>, versions: Vector<T>,
curr_version: usize, curr_version: usize,
} }
impl VersionedCanvas { impl<T: druid::Data + Clone> Versioned<T> {
pub fn new(canvas: Canvas) -> VersionedCanvas { pub fn new(first_version: T) -> Versioned<T> {
VersionedCanvas { Versioned {
versions: im::vector![canvas], versions: im::vector![first_version],
curr_version: 0, curr_version: 0,
} }
} }
// Get current canvas version // Get current version
pub fn get(&self) -> &Canvas { pub fn get(&self) -> &T {
self.versions.get(self.curr_version).unwrap() self.versions.get(self.curr_version).unwrap()
} }
@ -58,10 +57,10 @@ impl VersionedCanvas {
} }
} }
pub fn update(&mut self, update_fn: impl FnOnce(&mut Canvas)) { pub fn update(&mut self, update_fn: impl FnOnce(&mut T)) {
// Make a new copy of the current canvas version, // Make a new copy of the current version,
// so that we can safely modify it without losing // so that we can safely modify it without losing
// the previous canvas version // the previous version
let mut new_version = self.get().clone(); let mut new_version = self.get().clone();
update_fn(&mut new_version); update_fn(&mut new_version);
@ -77,8 +76,8 @@ impl VersionedCanvas {
} }
// 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 T)) {
// Do the update directly on the current canvas version // Do the update directly on the current version
update_fn(self.versions.back_mut().unwrap()); update_fn(self.versions.back_mut().unwrap());
// This is a linear history, // This is a linear history,

View File

@ -21,6 +21,12 @@ pub mod canvas;
pub mod history; pub mod history;
pub mod tool; pub mod tool;
pub mod widget; pub mod widget;
pub mod migration;
pub mod colors {
//use druid::Color;
//pub const SELECTED_STROKE: Color = Color::rgb(10.0, 0.0, 255.0);
}
pub mod commands { pub mod commands {
use druid::Selector; use druid::Selector;
@ -30,9 +36,20 @@ pub mod commands {
pub const POP_ERASER: Selector<()> = Selector::new("pop_eraser_context"); pub const POP_ERASER: Selector<()> = Selector::new("pop_eraser_context");
} }
pub const STILETTO_FORMAT_MAJOR: u16 = 0;
pub const STILETTO_FORMAT_MINOR: u16 = 2;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct DocumentSnapshot { pub struct DocumentSnapshot {
pub format_version_major: u16, pub format_version_major: u16,
pub format_version_minor: u16, pub format_version_minor: u16,
pub canvas_elements: Vec<canvas::CanvasElement>, pub canvas_elements: Vec<canvas::CanvasElement>,
} }
impl DocumentSnapshot {
pub fn to_writer<W: std::io::Write>(&self, writer: W) -> Result<(), serde_bare::Error> {
serde_bare::to_writer(writer, &self)
}
}
pub type VersionedCanvas = history::Versioned<canvas::Canvas>;

View File

@ -71,6 +71,10 @@ pub fn main() {
tool_params: CanvasToolParams::Eraser, tool_params: CanvasToolParams::Eraser,
selected: false, selected: false,
}, },
CanvasToolIconState {
tool_params: CanvasToolParams::RectangularSelection,
selected: false,
},
], ],
current_tool: 0, current_tool: 0,
eraser_tool_id: 2, eraser_tool_id: 2,
@ -100,9 +104,9 @@ impl StilettoState {
self.tool_icons.get_mut(old_tool).unwrap().selected = false; self.tool_icons.get_mut(old_tool).unwrap().selected = false;
self.tool_icons.get_mut(new_tool).unwrap().selected = true; self.tool_icons.get_mut(new_tool).unwrap().selected = true;
self.current_tool = new_tool; self.current_tool = new_tool;
self.canvas.set_tool_ctx(CanvasToolCtx::new( self.canvas.change_tool(
self.tool_icons.get(new_tool).unwrap().tool_params.clone(), self.tool_icons.get(new_tool).unwrap().tool_params.clone(),
)); );
} }
} }
@ -116,6 +120,18 @@ fn build_ui() -> impl Widget<StilettoState> {
|_ctx: &mut EventCtx, data: &mut StilettoState, _env: &Env| data.canvas.perform_redo(), |_ctx: &mut EventCtx, data: &mut StilettoState, _env: &Env| data.canvas.perform_redo(),
)); ));
let selection_buttons = Flex::row()
.cross_axis_alignment(CrossAxisAlignment::Center)
.with_child(Button::new("Copy").on_click(
|_ctx: &mut EventCtx, data: &mut StilettoState, _env: &Env| {},
))
.with_child(Button::new("Cut").on_click(
|_ctx: &mut EventCtx, data: &mut StilettoState, _env: &Env| {},
))
.with_child(Button::new("Delete").on_click(
|_ctx: &mut EventCtx, data: &mut StilettoState, _env: &Env| data.canvas.delete_selected(),
));
let stlt = FileSpec::new("Stiletto notebook", &["stlt"]); let stlt = FileSpec::new("Stiletto notebook", &["stlt"]);
let save_dialog_options = FileDialogOptions::new() let save_dialog_options = FileDialogOptions::new()
.allowed_types(vec![stlt]) .allowed_types(vec![stlt])
@ -174,6 +190,8 @@ fn build_ui() -> impl Widget<StilettoState> {
.with_spacer(30.0) .with_spacer(30.0)
.with_flex_child(Align::left(history_buttons), 1.0) .with_flex_child(Align::left(history_buttons), 1.0)
.with_spacer(10.0) .with_spacer(10.0)
.with_flex_child(Align::left(selection_buttons), 1.0)
.with_spacer(10.0)
.with_flex_child(Align::left(tool_buttons), 2.0) .with_flex_child(Align::left(tool_buttons), 2.0)
.with_spacer(20.0) .with_spacer(20.0)
.with_flex_child(Align::right(save_buttons), 1.0) .with_flex_child(Align::right(save_buttons), 1.0)
@ -209,11 +227,14 @@ impl<W: Widget<StilettoState>> Controller<StilettoState, W> for ToolSwitcher {
match event { match event {
Event::Notification(cmd) => { Event::Notification(cmd) => {
let new_tool = if cmd.get(stiletto::commands::PUSH_ERASER).is_some() { let new_tool = if cmd.get(stiletto::commands::PUSH_ERASER).is_some() {
ctx.set_handled();
self.saved_tool = data.current_tool; self.saved_tool = data.current_tool;
Some(data.eraser_tool_id) Some(data.eraser_tool_id)
} else if cmd.get(stiletto::commands::POP_ERASER).is_some() { } else if cmd.get(stiletto::commands::POP_ERASER).is_some() {
ctx.set_handled();
Some(self.saved_tool) Some(self.saved_tool)
} else if cmd.get(stiletto::commands::UPDATE_TOOL).is_some() { } else if cmd.get(stiletto::commands::UPDATE_TOOL).is_some() {
ctx.set_handled();
let old_tool = data.current_tool; let old_tool = data.current_tool;
data.tool_icons data.tool_icons
.iter() .iter()
@ -225,7 +246,6 @@ impl<W: Widget<StilettoState>> Controller<StilettoState, W> for ToolSwitcher {
if let Some(new_tool) = new_tool { if let Some(new_tool) = new_tool {
data.set_tool(new_tool); data.set_tool(new_tool);
ctx.set_handled();
} }
} }
_ => {} _ => {}
@ -258,7 +278,7 @@ impl AppDelegate<StilettoState> for Delegate {
let res_file = File::create(&path_buf); let res_file = File::create(&path_buf);
if let Ok(f) = res_file { if let Ok(f) = res_file {
let write_res = let write_res =
serde_json::to_writer_pretty(f, &data.canvas.get_document_snapshot()); data.canvas.get_document_snapshot().to_writer(f);
if write_res.is_err() { if write_res.is_err() {
warn!("Error while saving: {:?}", write_res.err()); warn!("Error while saving: {:?}", write_res.err());
} else { } else {
@ -272,8 +292,8 @@ impl AppDelegate<StilettoState> for Delegate {
} }
if let Some(file_info) = cmd.get(commands::OPEN_FILE) { if let Some(file_info) = cmd.get(commands::OPEN_FILE) {
if let Ok(f) = File::open(file_info.path()) { if let Ok(f) = File::open(file_info.path()) {
let res_snapshot: Result<DocumentSnapshot, serde_json::Error> = let res_snapshot: Result<DocumentSnapshot, serde_bare::Error> =
serde_json::from_reader(f); serde_bare::from_reader(f);
if let Ok(document_snapshot) = res_snapshot { if let Ok(document_snapshot) = res_snapshot {
data.canvas.set_from_snapshot(document_snapshot); data.canvas.set_from_snapshot(document_snapshot);
data.current_file_path = Some(file_info.path().to_path_buf()); data.current_file_path = Some(file_info.path().to_path_buf());

142
src/migration.rs Normal file
View File

@ -0,0 +1,142 @@
// Stiletto
// Copyright (C) 2020 Stiletto Authors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{DocumentSnapshot, STILETTO_FORMAT_MAJOR, STILETTO_FORMAT_MINOR};
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io;
use std::path::PathBuf;
#[derive(Debug)]
pub enum MigrationError {
SerdeJsonError(serde_json::Error),
SerdeBareError(serde_bare::Error),
IoError(io::Error),
UnexpectedVersion(u16, u16, u16, u16),
}
#[derive(Debug)]
pub enum StilettoDocument {
DocumentSnapshot0_1(DocumentSnapshot),
DocumentSnapshot0_2(DocumentSnapshot),
}
impl StilettoDocument {
pub fn version(&self) -> (u16, u16) {
match &self {
StilettoDocument::DocumentSnapshot0_1(_) => (0, 1),
StilettoDocument::DocumentSnapshot0_2(_) => (0, 2),
}
}
pub fn migrate_to_next(self) -> StilettoDocument {
match self {
StilettoDocument::DocumentSnapshot0_1(snapshot) => StilettoDocument::DocumentSnapshot0_2(snapshot) ,
StilettoDocument::DocumentSnapshot0_2(_) => self,
}
}
pub fn migrate_to_latest(mut self) -> DocumentSnapshot {
while self.version() != (STILETTO_FORMAT_MAJOR, STILETTO_FORMAT_MINOR) {
self = self.migrate_to_next()
}
assert!(matches!(self, StilettoDocument::DocumentSnapshot0_2(_)));
match self {
StilettoDocument::DocumentSnapshot0_2(snapshot) => snapshot,
_ => panic!("Wrong Document Snapshot Version")
}
}
}
impl fmt::Display for MigrationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self {
MigrationError::SerdeJsonError(e) => e.fmt(f),
MigrationError::SerdeBareError(e) => e.fmt(f),
MigrationError::IoError(e) => e.fmt(f),
MigrationError::UnexpectedVersion(major, minor, e_major, e_minor) => {
write!(
f, "Unexpected version ({}, {}): was expecting ({}, {})",
major, minor, e_major, e_minor
)
},
}
}
}
impl Error for MigrationError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
MigrationError::SerdeJsonError(e) => e.source(),
MigrationError::SerdeBareError(e) => e.source(),
MigrationError::IoError(e) => e.source(),
MigrationError::UnexpectedVersion(..) => None,
}
}
}
impl From<io::Error> for MigrationError {
fn from(error: io::Error) -> Self {
MigrationError::IoError(error)
}
}
impl From<serde_json::Error> for MigrationError {
fn from(error: serde_json::Error) -> Self {
MigrationError::SerdeJsonError(error)
}
}
impl From<serde_bare::Error> for MigrationError {
fn from(error: serde_bare::Error) -> Self {
MigrationError::SerdeBareError(error)
}
}
fn open_0_1(path: &PathBuf) -> Result<StilettoDocument, MigrationError> {
let f = File::open(path)?;
let document_snapshot: DocumentSnapshot = serde_json::from_reader(f)?;
if document_snapshot.format_version_major != 0 ||
document_snapshot.format_version_minor != 1 {
Err(MigrationError::UnexpectedVersion(
document_snapshot.format_version_major,
document_snapshot.format_version_minor,
0, 1
))
} else {
Ok(StilettoDocument::DocumentSnapshot0_1(document_snapshot))
}
}
fn open_0_2(path: &PathBuf) -> Result<StilettoDocument, MigrationError> {
let f = File::open(path)?;
let document_snapshot: DocumentSnapshot = serde_bare::from_reader(f)?;
Ok(StilettoDocument::DocumentSnapshot0_2(document_snapshot))
}
pub fn open_stiletto_document(path: &PathBuf) -> Result<StilettoDocument, MigrationError> {
if let Ok(res) = open_0_1(path) {
return Ok(res);
}
open_0_2(path)
}

View File

@ -20,11 +20,13 @@ use druid::{Color, Data};
pub enum CanvasToolParams { pub enum CanvasToolParams {
Pen { thickness: f64, color: Color }, Pen { thickness: f64, color: Color },
Eraser, Eraser,
RectangularSelection,
} }
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub enum CanvasToolType { pub enum CanvasToolType {
Pen, Pen,
Eraser, Eraser,
RectangularSelection,
} }

View File

@ -16,13 +16,13 @@
use im::Vector; use im::Vector;
use super::tool_ctx::{CanvasToolCtx}; use super::tool_ctx::{CanvasToolCtx, CanvasToolState};
use crate::canvas::Canvas; use crate::canvas::{Canvas, CanvasElement};
use crate::history::VersionedCanvas; use crate::tool::CanvasToolParams;
use crate::DocumentSnapshot; use crate::{DocumentSnapshot, VersionedCanvas};
use druid::widget::prelude::*; use druid::widget::prelude::*;
use druid::{Color, Data, Env, Event, PointerType}; use druid::{Color, Data, Env, Event, PointerType, Selector};
#[derive(Clone, Data)] #[derive(Clone, Data)]
pub struct CanvasState { pub struct CanvasState {
@ -42,12 +42,14 @@ impl CanvasState {
pub fn perform_undo(&mut self) { pub fn perform_undo(&mut self) {
//if !self.is_drawing() { //if !self.is_drawing() {
self.versioned_canvas.undo(); self.versioned_canvas.undo();
self.set_ctx_selection_state();
//} //}
} }
pub fn perform_redo(&mut self) { pub fn perform_redo(&mut self) {
//if !self.is_drawing() { //if !self.is_drawing() {
self.versioned_canvas.redo(); self.versioned_canvas.redo();
self.set_ctx_selection_state();
//} //}
} }
@ -71,6 +73,44 @@ impl CanvasState {
))); )));
} }
fn set_ctx_selection_state(&mut self) {
if !self.versioned_canvas.get().selected_elements().is_empty() {
self.tool_ctx.set_state(CanvasToolState::ActiveSelection);
}
}
pub fn delete_selected(&mut self) {
let selected_elements = self.versioned_canvas.get().selected_elements();
if !selected_elements.is_empty() {
if !selected_elements.is_empty() {
let elements = self.versioned_canvas.get().elements();
// TODO(enrico): is this memory efficient?
// what is the difference between this and
// im::Vector::retain?
let new_elements = elements.iter().enumerate()
.filter_map(|(i, elem)| {
if !selected_elements.contains(&i) {
Some(elem)
} else {
None
}
})
.cloned()
.collect::<Vector<CanvasElement>>();
self.versioned_canvas.update(move |canvas: &mut Canvas| {
*canvas = Canvas::new_with_elements(new_elements);
});
}
}
}
/// Changes tool while mantaining the current CanvasToolCtx
pub fn change_tool(&mut self, tool_params: CanvasToolParams) {
self.tool_ctx.set_params(tool_params);
}
pub fn set_tool_ctx(&mut self, ctx: CanvasToolCtx) { pub fn set_tool_ctx(&mut self, ctx: CanvasToolCtx) {
self.tool_ctx = ctx; self.tool_ctx = ctx;
} }
@ -91,12 +131,28 @@ impl CanvasState {
pub struct CanvasWidget; pub struct CanvasWidget;
impl CanvasWidget {
pub const IS_OVER_SELECTION: Selector<bool> = Selector::new("is_over_selection");
}
impl Widget<CanvasState> for CanvasWidget { impl Widget<CanvasState> for CanvasWidget {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut CanvasState, env: &Env) { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut CanvasState, env: &Env) {
ctx.request_focus(); ctx.request_focus();
let mut toggle_eraser_event = false; let mut toggle_eraser_event = false;
let mut enable_temporary_erasing = false; let mut enable_temporary_erasing = false;
match event { match event {
Event::Notification(cmd) => {
cmd.get(CanvasWidget::IS_OVER_SELECTION).map(|is_over_sel| {
if *is_over_sel {
use druid::Cursor;
ctx.set_cursor(&Cursor::OpenHand);
} else {
// TODO: this is not correct. Must check if had modified cursor before
ctx.clear_cursor();
}
});
ctx.set_handled();
}
Event::MouseDown(mouse_event) => { Event::MouseDown(mouse_event) => {
toggle_eraser_event = true; toggle_eraser_event = true;
enable_temporary_erasing = mouse_event.pointer_type == PointerType::Eraser; enable_temporary_erasing = mouse_event.pointer_type == PointerType::Eraser;
@ -178,11 +234,20 @@ impl Widget<CanvasState> for CanvasWidget {
let rect = size.to_rect(); let rect = size.to_rect();
ctx.fill(rect, &Color::WHITE); ctx.fill(rect, &Color::WHITE);
for element in data.versioned_canvas.get().elements().iter() { let canvas = data.versioned_canvas.get();
let selected = canvas.selected_elements();
for (pos, element) in canvas.elements().iter().enumerate() {
if data.tool_ctx.has_active_selection() && selected.contains(&pos) {
element.draw_selected(ctx);
} else {
element.draw(ctx); element.draw(ctx);
} }
}
if data.tool_ctx.needs_repaint() { if data.tool_ctx.needs_repaint() {
data.tool_ctx.paint(ctx, env); data.tool_ctx.paint(ctx, env);
} }
} }
} }

View File

@ -16,10 +16,13 @@
use crate::tool::{CanvasToolParams, CanvasToolType}; use crate::tool::{CanvasToolParams, CanvasToolType};
use crate::canvas::{Canvas, CanvasElement}; use crate::canvas::{Canvas, CanvasElement};
use crate::history::VersionedCanvas; use crate::widget::CanvasWidget;
use crate::VersionedCanvas;
use druid::kurbo::BezPath; use druid::kurbo::BezPath;
use druid::{Data, Env, Event, EventCtx, MouseButton, MouseEvent, PaintCtx}; use druid::{Color, Data, Env, Event, EventCtx, MouseButton, MouseEvent, PaintCtx, RenderContext};
use im::{vector, Vector};
#[derive(Clone, Data)] #[derive(Clone, Data)]
pub enum CanvasToolState { pub enum CanvasToolState {
@ -29,6 +32,12 @@ pub enum CanvasToolState {
current_path: CanvasElement, current_path: CanvasElement,
}, },
Erasing, Erasing,
SelectingRect {
origin: druid::Point,
current_rect: druid::Rect,
},
DraggingSelection,
ActiveSelection,
} }
#[derive(Clone, Data)] #[derive(Clone, Data)]
@ -42,6 +51,7 @@ impl CanvasToolParams {
match self { match self {
CanvasToolParams::Pen { .. } => CanvasToolType::Pen, CanvasToolParams::Pen { .. } => CanvasToolType::Pen,
CanvasToolParams::Eraser => CanvasToolType::Eraser, CanvasToolParams::Eraser => CanvasToolType::Eraser,
CanvasToolParams::RectangularSelection => CanvasToolType::RectangularSelection,
} }
} }
} }
@ -51,6 +61,14 @@ fn pressed(mouse_event: &MouseEvent) -> bool {
|| mouse_event.button == MouseButton::Left || mouse_event.button == MouseButton::Left
} }
fn is_over_active_selection(mouse_event: &MouseEvent, vcanvas: &VersionedCanvas) -> bool {
let mouse_rect = druid::Rect::from_center_size(mouse_event.pos, (5.0, 5.0));
// TODO(enrico): this can be faster
let intersecting_elements = vcanvas.get().find_elements_intersecting(mouse_rect);
let selected_elements = vcanvas.get().selected_elements();
false
}
impl CanvasToolCtx { impl CanvasToolCtx {
pub fn new(params: CanvasToolParams) -> Self { pub fn new(params: CanvasToolParams) -> Self {
CanvasToolCtx { CanvasToolCtx {
@ -59,9 +77,22 @@ impl CanvasToolCtx {
} }
} }
pub fn set_params(&mut self, params: CanvasToolParams) {
self.initial_params = params;
// TODO(enrico) is this necessary?
match self.state {
CanvasToolState::Idle | CanvasToolState::ActiveSelection => {}
_ => { self.state = CanvasToolState::Idle; }
}
}
pub fn set_state(&mut self, state: CanvasToolState) {
self.state = state;
}
pub fn handle_event( pub fn handle_event(
&mut self, &mut self,
ctx: &EventCtx, mut ctx: &mut EventCtx,
event: &Event, event: &Event,
mut vcanvas: &mut VersionedCanvas, mut vcanvas: &mut VersionedCanvas,
env: &Env, env: &Env,
@ -69,6 +100,7 @@ impl CanvasToolCtx {
match self.initial_params.tool_type() { match self.initial_params.tool_type() {
CanvasToolType::Pen => self.handle_pen_event(&ctx, &event, &mut vcanvas, &env), CanvasToolType::Pen => self.handle_pen_event(&ctx, &event, &mut vcanvas, &env),
CanvasToolType::Eraser => self.handle_erase_event(&ctx, &event, &mut vcanvas, &env), CanvasToolType::Eraser => self.handle_erase_event(&ctx, &event, &mut vcanvas, &env),
CanvasToolType::RectangularSelection => self.handle_rectangular_select_event(&mut ctx, &event, &mut vcanvas, &env),
} }
} }
@ -80,6 +112,7 @@ impl CanvasToolCtx {
_env: &Env, _env: &Env,
) { ) {
match (&mut self.state, event) { match (&mut self.state, event) {
(CanvasToolState::ActiveSelection, Event::MouseDown(mouse_event)) |
(CanvasToolState::Idle, Event::MouseDown(mouse_event)) if pressed(mouse_event) => { (CanvasToolState::Idle, Event::MouseDown(mouse_event)) if pressed(mouse_event) => {
self.state = CanvasToolState::Erasing; self.state = CanvasToolState::Erasing;
} }
@ -117,6 +150,7 @@ impl CanvasToolCtx {
_env: &Env, _env: &Env,
) { ) {
match (&mut self.state, event) { match (&mut self.state, event) {
(CanvasToolState::ActiveSelection, Event::MouseDown(mouse_event)) |
(CanvasToolState::Idle, Event::MouseDown(mouse_event)) if pressed(mouse_event) => { (CanvasToolState::Idle, Event::MouseDown(mouse_event)) if pressed(mouse_event) => {
let mut kurbo_path = BezPath::new(); let mut kurbo_path = BezPath::new();
kurbo_path.move_to((mouse_event.pos.x, mouse_event.pos.y)); kurbo_path.move_to((mouse_event.pos.x, mouse_event.pos.y));
@ -137,7 +171,7 @@ impl CanvasToolCtx {
.. ..
}, },
Event::MouseMove(mouse_event), Event::MouseMove(mouse_event),
) => if pressed(mouse_event) { ) if pressed(mouse_event) => {
if let CanvasElement::Freehand { ref mut path, .. } = current_path { if let CanvasElement::Freehand { ref mut path, .. } = current_path {
path.kurbo_path path.kurbo_path
.line_to((mouse_event.pos.x, mouse_event.pos.y)); .line_to((mouse_event.pos.x, mouse_event.pos.y));
@ -158,6 +192,7 @@ impl CanvasToolCtx {
thickness, thickness,
stroke_color, stroke_color,
}); });
*canvas.selected_elements_mut() = vector![];
} }
} }
}); });
@ -166,13 +201,78 @@ impl CanvasToolCtx {
} }
} }
pub fn handle_rectangular_select_event(
&mut self,
ctx: &mut EventCtx,
event: &Event,
vcanvas: &mut VersionedCanvas,
_env: &Env,
) {
match (&mut self.state, event) {
(CanvasToolState::ActiveSelection, Event::MouseMove(mouse_event)) if !pressed(mouse_event) => {
ctx.submit_notification(CanvasWidget::IS_OVER_SELECTION.with(is_over_active_selection(mouse_event, vcanvas)));
}
(CanvasToolState::ActiveSelection, Event::MouseDown(mouse_event)) if pressed(mouse_event)
&& is_over_active_selection(mouse_event, vcanvas) => {
}
(CanvasToolState::DraggingSelection, Event::MouseMove(mouse_event)) if pressed(mouse_event) => {
}
(CanvasToolState::DraggingSelection, Event::MouseUp(mouse_event)) if pressed(mouse_event) => {
}
(CanvasToolState::ActiveSelection, Event::MouseDown(mouse_event)) |
(CanvasToolState::Idle, Event::MouseDown(mouse_event)) if pressed(mouse_event) => {
self.state = CanvasToolState::SelectingRect {
origin: mouse_event.pos,
current_rect: druid::Rect::from_origin_size(mouse_event.pos, (0.0, 0.0))
};
}
(CanvasToolState::SelectingRect{ ref mut current_rect, ref origin }, Event::MouseMove(mouse_event)) if pressed(mouse_event) => {
*current_rect = druid::Rect::from_origin_size(*origin, (0.0, 0.0))
.union_pt(mouse_event.pos);
}
(CanvasToolState::SelectingRect{ ref mut current_rect, ref origin }, Event::MouseUp(mouse_event)) if pressed(mouse_event) => {
*current_rect = druid::Rect::from_origin_size(*origin, (0.0, 0.0))
.union_pt(mouse_event.pos);
let elements = vcanvas.get().elements();
let selected_elements_idx = elements.iter().enumerate()
.filter_map(|(i, elem)| {
let bbox = elem.bounding_box();
let p0 = druid::Point::new(bbox.x0, bbox.y0);
let p1 = druid::Point::new(bbox.x1, bbox.y1);
if current_rect.contains(p0) && current_rect.contains(p1) {
return Some(i);
}
None
}).collect::<Vector<usize>>();
if !elements.is_empty() {
vcanvas.update(move |canvas: &mut Canvas| {
*canvas.selected_elements_mut() = selected_elements_idx;
});
}
self.state = CanvasToolState::ActiveSelection;
}
_ => {}
}
}
pub fn needs_repaint(&self) -> bool { pub fn needs_repaint(&self) -> bool {
true true
} }
pub fn has_active_selection(&self) -> bool {
match self.state {
CanvasToolState::ActiveSelection => true,
_ => false,
}
}
pub fn paint(&self, ctx: &mut PaintCtx, _env: &Env) { pub fn paint(&self, ctx: &mut PaintCtx, _env: &Env) {
match &self.state { match &self.state {
CanvasToolState::DrawingFreehand { current_path, .. } => current_path.draw(ctx), CanvasToolState::DrawingFreehand { current_path, .. } => current_path.draw(ctx),
CanvasToolState::SelectingRect { current_rect, .. } => ctx.stroke(current_rect, &Color::BLACK, 0.5),
_ => {} _ => {}
} }
} }

View File

@ -34,6 +34,9 @@ impl CanvasToolIconState {
CanvasToolParams::Eraser => include_str!("../../icons/eraser.svg") CanvasToolParams::Eraser => include_str!("../../icons/eraser.svg")
.parse::<SvgData>() .parse::<SvgData>()
.unwrap(), .unwrap(),
CanvasToolParams::RectangularSelection => include_str!("../../icons/eraser.svg")
.parse::<SvgData>()
.unwrap(),
} }
} }
} }