Compare commits
14 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
32740f3b22 | |
|
|
6a2460c42f | |
|
|
721ad1eecf | |
|
|
0fdc73b9e4 | |
|
|
a2cf104697 | |
|
|
a1f813631b | |
|
|
f330760c1c | |
|
|
022377cb48 | |
|
|
3b048896e0 | |
|
|
390de72aa2 | |
|
|
57ef9e5e0e | |
|
|
56ed3b7c01 | |
|
|
827d8d6a1c | |
|
|
0b74394042 |
File diff suppressed because it is too large
Load Diff
26
Cargo.toml
26
Cargo.toml
|
|
@ -3,26 +3,30 @@ 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.6.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]
|
[target.'cfg(target_os="linux")'.dependencies.gtk]
|
||||||
druid = { git = "https://github.com/doppioandante/druid", branch = "v0.6.0_stiletto", features = ["im", "svg"] }
|
version = "0.9.2"
|
||||||
|
|
||||||
[dependencies.gtk]
|
|
||||||
version = "0.8.1"
|
|
||||||
features = ["v3_22"]
|
features = ["v3_22"]
|
||||||
|
|
||||||
[dependencies.gio]
|
[target.'cfg(target_os="linux")'.dependencies.gio]
|
||||||
version = "0.8.1"
|
version = "0.9.1"
|
||||||
features = ["v2_56"]
|
features = ["v2_56"]
|
||||||
|
|
||||||
[dependencies.gdk]
|
[target.'cfg(target_os="linux")'.dependencies.gdk]
|
||||||
version = "0.12.1"
|
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"] }
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
164
src/canvas.rs
164
src/canvas.rs
|
|
@ -14,7 +14,9 @@
|
||||||
// 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 im::Vector;
|
use std::vec::Vec;
|
||||||
|
|
||||||
|
use im::{vector, Vector};
|
||||||
|
|
||||||
use serde::de::{Deserializer, SeqAccess, Visitor};
|
use serde::de::{Deserializer, SeqAccess, Visitor};
|
||||||
use serde::ser::Serializer;
|
use serde::ser::Serializer;
|
||||||
|
|
@ -25,17 +27,76 @@ pub struct Path {
|
||||||
pub kurbo_path: druid::kurbo::BezPath,
|
pub kurbo_path: druid::kurbo::BezPath,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type Canvas = Vector<CanvasElement>;
|
#[derive(Serialize, Deserialize)]
|
||||||
|
#[serde(remote = "druid::Color")]
|
||||||
|
enum ColorDef {
|
||||||
|
Rgba32(u32),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Interval {
|
||||||
|
start_pos: f64,
|
||||||
|
end_pos: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Interval {
|
||||||
|
fn new(x1: f64, x2: f64) -> Interval {
|
||||||
|
Interval {
|
||||||
|
start_pos: x1.min(x2),
|
||||||
|
end_pos: x1.max(x2),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_ordered(start: f64, end: f64) -> Interval {
|
||||||
|
Interval {
|
||||||
|
start_pos: start,
|
||||||
|
end_pos: end,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn overlaps(&self, other: &Self) -> bool {
|
||||||
|
self.start_pos < other.end_pos && other.start_pos < self.end_pos
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// O(1) complexity
|
||||||
|
// TODO(francesco): Implement this in a way that is not so flamboyant
|
||||||
|
// TODO(francesco): Implement intersection test for bezier curves
|
||||||
|
fn segment_intersects_rect(segment: &druid::kurbo::PathSeg, rect: druid::Rect) -> bool {
|
||||||
|
match segment {
|
||||||
|
druid::kurbo::PathSeg::Line(line) => {
|
||||||
|
// A Segment intersects the rect
|
||||||
|
// if their projections on the x and y line both overlap
|
||||||
|
let line_x_proj = Interval::new(line.p0.x, line.p1.x);
|
||||||
|
let line_y_proj = Interval::new(line.p0.y, line.p1.y);
|
||||||
|
|
||||||
|
let rect_x_proj = Interval::new_ordered(rect.min_x(), rect.max_x());
|
||||||
|
let rect_y_proj = Interval::new_ordered(rect.min_y(), rect.max_y());
|
||||||
|
|
||||||
|
line_x_proj.overlaps(&rect_x_proj) && line_y_proj.overlaps(&rect_y_proj)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ => {
|
||||||
|
unimplemented!();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, druid::Data, Serialize, Deserialize)]
|
#[derive(Debug, Clone, druid::Data, Serialize, Deserialize)]
|
||||||
pub enum CanvasElement {
|
pub enum CanvasElement {
|
||||||
Freehand { path: Path, thickness: f64 },
|
Freehand {
|
||||||
|
path: Path,
|
||||||
|
thickness: f64,
|
||||||
|
#[serde(with = "ColorDef")]
|
||||||
|
stroke_color: druid::Color,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CanvasElement {
|
impl CanvasElement {
|
||||||
pub fn bounding_box(&self) -> druid::Rect {
|
pub fn bounding_box(&self) -> druid::Rect {
|
||||||
match self {
|
match self {
|
||||||
CanvasElement::Freehand { path, thickness } => {
|
CanvasElement::Freehand {
|
||||||
|
path, thickness, ..
|
||||||
|
} => {
|
||||||
use druid::kurbo::Shape;
|
use druid::kurbo::Shape;
|
||||||
path.kurbo_path
|
path.kurbo_path
|
||||||
.bounding_box()
|
.bounding_box()
|
||||||
|
|
@ -43,29 +104,85 @@ impl CanvasElement {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn intersects_rect(&self, rect: druid::Rect) -> bool {
|
||||||
|
match self {
|
||||||
|
CanvasElement::Freehand { path, .. } => {
|
||||||
|
// TODO(enrico) this doesn't handle thickness
|
||||||
|
path.kurbo_path
|
||||||
|
.segments()
|
||||||
|
.any(|segment| segment_intersects_rect(&segment, rect))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn draw(&self, ctx: &mut druid::PaintCtx) {
|
pub fn draw(&self, ctx: &mut druid::PaintCtx) {
|
||||||
match self {
|
match self {
|
||||||
CanvasElement::Freehand { path, thickness } => {
|
CanvasElement::Freehand {
|
||||||
|
path,
|
||||||
|
thickness,
|
||||||
|
stroke_color,
|
||||||
|
} => {
|
||||||
use druid::RenderContext;
|
use druid::RenderContext;
|
||||||
let stroke_color = druid::Color::rgb8(0, 128, 0);
|
ctx.stroke(&path.kurbo_path, &*stroke_color, *thickness);
|
||||||
ctx.stroke(&path.kurbo_path, &stroke_color, *thickness);
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_path_mut(&mut self) -> Option<&mut Path> {
|
#[derive(Clone, druid::Data)]
|
||||||
match self {
|
pub struct Canvas {
|
||||||
CanvasElement::Freehand { path, .. } => Some(path),
|
elements: Vector<CanvasElement>,
|
||||||
|
content_size: druid::Size,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Canvas {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Canvas {
|
||||||
|
elements: vector![],
|
||||||
|
content_size: druid::Size::new(0.0, 0.0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_with_elements(elements: Vector<CanvasElement>) -> Self {
|
||||||
|
let mut cv = Canvas::new();
|
||||||
|
for e in elements {
|
||||||
|
cv.add_element(e);
|
||||||
|
}
|
||||||
|
cv
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_element(&mut self, element: CanvasElement) {
|
||||||
|
self.content_size = self
|
||||||
|
.content_size
|
||||||
|
.to_rect()
|
||||||
|
.union(element.bounding_box())
|
||||||
|
.size();
|
||||||
|
self.elements.push_back(element);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn elements(&self) -> &Vector<CanvasElement> {
|
||||||
|
&self.elements
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Find all CanvasElement that intersect with rect
|
||||||
|
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() {
|
||||||
|
// Check if the element intersects the eraser rect
|
||||||
|
if elem.bounding_box().intersect(rect).area() > 0.0 {
|
||||||
|
if elem.intersects_rect(rect) {
|
||||||
|
found_elements.push(i);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for Path {
|
found_elements
|
||||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
}
|
||||||
where
|
|
||||||
D: Deserializer<'de>,
|
pub fn content_size(&self) -> druid::Size {
|
||||||
{
|
self.content_size
|
||||||
deserializer.deserialize_seq(PathDeserializer)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -80,13 +197,18 @@ 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)>>())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct PathDeserializer;
|
impl<'de> Deserialize<'de> for Path {
|
||||||
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||||
|
where
|
||||||
|
D: Deserializer<'de>,
|
||||||
|
{
|
||||||
|
struct PathVisitor;
|
||||||
|
|
||||||
impl<'de> Visitor<'de> for PathDeserializer {
|
impl<'de> Visitor<'de> for PathVisitor {
|
||||||
type Value = Path;
|
type Value = Path;
|
||||||
|
|
||||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||||
|
|
@ -113,3 +235,7 @@ impl<'de> Visitor<'de> for PathDeserializer {
|
||||||
Ok(Path { kurbo_path })
|
Ok(Path { kurbo_path })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
deserializer.deserialize_seq(PathVisitor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
14
src/lib.rs
14
src/lib.rs
|
|
@ -21,14 +21,28 @@ 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 commands {
|
pub mod commands {
|
||||||
use druid::Selector;
|
use druid::Selector;
|
||||||
|
|
||||||
pub const UPDATE_TOOL: Selector = Selector::new("stiletto_update_tool");
|
pub const UPDATE_TOOL: Selector = Selector::new("stiletto_update_tool");
|
||||||
|
pub const PUSH_ERASER: Selector<()> = Selector::new("push_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_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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
201
src/main.rs
201
src/main.rs
|
|
@ -14,53 +14,67 @@
|
||||||
// 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::path::PathBuf;
|
||||||
|
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
|
|
||||||
use druid::commands;
|
use druid::commands;
|
||||||
use druid::im::vector;
|
use druid::im::vector;
|
||||||
use druid::widget::prelude::*;
|
use druid::widget::prelude::*;
|
||||||
use druid::widget::{
|
use druid::widget::{
|
||||||
Align, Button, CrossAxisAlignment, Flex, List, ListGrowDirection, SizedBox, WidgetExt,
|
Align, Button, Controller, CrossAxisAlignment, Flex, List, SizedBox, WidgetExt,
|
||||||
};
|
};
|
||||||
use druid::{
|
use druid::{
|
||||||
AppDelegate, AppLauncher, Color, Command, Data, DelegateCtx, Env, FileDialogOptions, FileSpec,
|
AppDelegate, AppLauncher, Color, Command, Data, DelegateCtx, Env, FileDialogOptions, FileSpec,
|
||||||
Lens, LocalizedString, Target, WindowDesc,
|
Handled, Lens, Target, WindowDesc,
|
||||||
};
|
};
|
||||||
|
|
||||||
use im::Vector;
|
use im::Vector;
|
||||||
|
|
||||||
use stiletto::history::VersionedCanvas;
|
use stiletto::tool::CanvasToolParams;
|
||||||
use stiletto::tool::{CanvasToolCtx, CanvasToolParams};
|
use stiletto::widget::tool_ctx::{CanvasToolCtx};
|
||||||
use stiletto::widget::{build_simple_tool_widget, CanvasState, CanvasToolIconState, CanvasWidget};
|
use stiletto::widget::{build_simple_tool_widget, CanvasState, CanvasToolIconState, CanvasWidget};
|
||||||
use stiletto::DocumentSnapshot;
|
use stiletto::DocumentSnapshot;
|
||||||
|
|
||||||
pub fn main() {
|
pub fn main() {
|
||||||
let window = WindowDesc::new(build_ui)
|
let window = WindowDesc::new(build_ui)
|
||||||
.window_size((1024.0, 1400.0))
|
.window_size((1024.0, 1400.0))
|
||||||
.title(
|
.title(|data: &StilettoState, _env: &Env| {
|
||||||
LocalizedString::new("custom-widget-demo-window-title").with_placeholder("Stiletto"),
|
let doc_name = if let Some(path) = &data.current_file_path {
|
||||||
);
|
String::from(path.to_string_lossy())
|
||||||
|
} else {
|
||||||
|
String::from("New Document")
|
||||||
|
};
|
||||||
|
format!("Stiletto - {}", doc_name)
|
||||||
|
});
|
||||||
|
|
||||||
let default_pen_params = CanvasToolParams::Pen {
|
let default_pen_params = CanvasToolParams::Pen {
|
||||||
thickness: 2.0,
|
thickness: 2.0,
|
||||||
color: Color::rgb(0, 0, 0),
|
color: Color::rgb(0.0, 0.0, 0.0),
|
||||||
|
};
|
||||||
|
let default_pen_params_2 = CanvasToolParams::Pen {
|
||||||
|
thickness: 2.0,
|
||||||
|
color: Color::rgb(255.0, 0.0, 0.0),
|
||||||
};
|
};
|
||||||
let canvas_data = StilettoState {
|
let canvas_data = StilettoState {
|
||||||
canvas: CanvasState {
|
canvas: CanvasState::new(CanvasToolCtx::new(default_pen_params.clone())),
|
||||||
versioned_canvas: VersionedCanvas::new(vector![]),
|
|
||||||
tool_ctx: CanvasToolCtx::new(default_pen_params.clone()),
|
|
||||||
},
|
|
||||||
tool_icons: vector![
|
tool_icons: vector![
|
||||||
CanvasToolIconState {
|
CanvasToolIconState {
|
||||||
tool_params: default_pen_params,
|
tool_params: default_pen_params,
|
||||||
selected: true,
|
selected: true,
|
||||||
},
|
},
|
||||||
|
CanvasToolIconState {
|
||||||
|
tool_params: default_pen_params_2,
|
||||||
|
selected: false,
|
||||||
|
},
|
||||||
CanvasToolIconState {
|
CanvasToolIconState {
|
||||||
tool_params: CanvasToolParams::Eraser,
|
tool_params: CanvasToolParams::Eraser,
|
||||||
selected: false,
|
selected: false,
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
current_tool: 0,
|
current_tool: 0,
|
||||||
|
eraser_tool_id: 2,
|
||||||
|
current_file_path: None,
|
||||||
};
|
};
|
||||||
AppLauncher::with_window(window)
|
AppLauncher::with_window(window)
|
||||||
.use_simple_logger()
|
.use_simple_logger()
|
||||||
|
|
@ -74,6 +88,22 @@ struct StilettoState {
|
||||||
canvas: CanvasState,
|
canvas: CanvasState,
|
||||||
tool_icons: Vector<CanvasToolIconState>,
|
tool_icons: Vector<CanvasToolIconState>,
|
||||||
current_tool: usize,
|
current_tool: usize,
|
||||||
|
eraser_tool_id: usize,
|
||||||
|
#[data(same_fn = "PartialEq::eq")]
|
||||||
|
current_file_path: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StilettoState {
|
||||||
|
pub fn set_tool(&mut self, new_tool: usize) {
|
||||||
|
let old_tool = self.current_tool;
|
||||||
|
info!("Changing active tool to: tool #{}", new_tool);
|
||||||
|
self.tool_icons.get_mut(old_tool).unwrap().selected = false;
|
||||||
|
self.tool_icons.get_mut(new_tool).unwrap().selected = true;
|
||||||
|
self.current_tool = new_tool;
|
||||||
|
self.canvas.set_tool_ctx(CanvasToolCtx::new(
|
||||||
|
self.tool_icons.get(new_tool).unwrap().tool_params.clone(),
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_ui() -> impl Widget<StilettoState> {
|
fn build_ui() -> impl Widget<StilettoState> {
|
||||||
|
|
@ -90,27 +120,37 @@ fn build_ui() -> impl Widget<StilettoState> {
|
||||||
let save_dialog_options = FileDialogOptions::new()
|
let save_dialog_options = FileDialogOptions::new()
|
||||||
.allowed_types(vec![stlt])
|
.allowed_types(vec![stlt])
|
||||||
.default_type(stlt);
|
.default_type(stlt);
|
||||||
|
let save_dialog_options_clone = save_dialog_options.clone();
|
||||||
let open_dialog_options = save_dialog_options.clone();
|
let open_dialog_options = save_dialog_options.clone();
|
||||||
|
|
||||||
let save_buttons = Flex::row()
|
let save_buttons = Flex::row()
|
||||||
.cross_axis_alignment(CrossAxisAlignment::Center)
|
.cross_axis_alignment(CrossAxisAlignment::Center)
|
||||||
.with_child(Button::new("Open").on_click(move |ctx, _, _| {
|
.with_child(
|
||||||
ctx.submit_command(
|
Button::new("Save").on_click(move |ctx, data: &mut StilettoState, _| {
|
||||||
Command::new(
|
if data.current_file_path.is_some() {
|
||||||
druid::commands::SHOW_OPEN_PANEL,
|
ctx.submit_command(Command::new(commands::SAVE_FILE, (), Target::Auto));
|
||||||
open_dialog_options.clone(),
|
} else {
|
||||||
),
|
ctx.submit_command(Command::new(
|
||||||
None,
|
druid::commands::SHOW_SAVE_PANEL,
|
||||||
|
save_dialog_options_clone.clone(),
|
||||||
|
Target::Auto,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
}))
|
.with_child(Button::new("Save As").on_click(move |ctx, _, _| {
|
||||||
.with_child(Button::new("Save").on_click(move |ctx, _, _| {
|
ctx.submit_command(Command::new(
|
||||||
ctx.submit_command(
|
|
||||||
Command::new(
|
|
||||||
druid::commands::SHOW_SAVE_PANEL,
|
druid::commands::SHOW_SAVE_PANEL,
|
||||||
save_dialog_options.clone(),
|
save_dialog_options.clone(),
|
||||||
),
|
Target::Auto,
|
||||||
None,
|
))
|
||||||
)
|
}))
|
||||||
|
.with_child(Button::new("Open").on_click(move |ctx, _, _| {
|
||||||
|
ctx.submit_command(Command::new(
|
||||||
|
druid::commands::SHOW_OPEN_PANEL,
|
||||||
|
open_dialog_options.clone(),
|
||||||
|
Target::Auto,
|
||||||
|
))
|
||||||
}));
|
}));
|
||||||
|
|
||||||
let tool_buttons = Flex::row()
|
let tool_buttons = Flex::row()
|
||||||
|
|
@ -121,10 +161,10 @@ fn build_ui() -> impl Widget<StilettoState> {
|
||||||
.padding((8.0, 0.0))
|
.padding((8.0, 0.0))
|
||||||
.on_click(|ctx, tool_state, _| {
|
.on_click(|ctx, tool_state, _| {
|
||||||
tool_state.selected = true;
|
tool_state.selected = true;
|
||||||
ctx.submit_command(stiletto::commands::UPDATE_TOOL, None);
|
ctx.submit_notification(stiletto::commands::UPDATE_TOOL);
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.grow(ListGrowDirection::Right)
|
.horizontal()
|
||||||
.lens(StilettoState::tool_icons),
|
.lens(StilettoState::tool_icons),
|
||||||
1.0,
|
1.0,
|
||||||
);
|
);
|
||||||
|
|
@ -143,7 +183,57 @@ fn build_ui() -> impl Widget<StilettoState> {
|
||||||
.cross_axis_alignment(CrossAxisAlignment::Center)
|
.cross_axis_alignment(CrossAxisAlignment::Center)
|
||||||
.must_fill_main_axis(true)
|
.must_fill_main_axis(true)
|
||||||
.with_child(SizedBox::new(Align::left(toolbar)).height(50.0))
|
.with_child(SizedBox::new(Align::left(toolbar)).height(50.0))
|
||||||
.with_flex_child((CanvasWidget {}).lens(StilettoState::canvas), 1.0)
|
.with_flex_child((CanvasWidget).lens(StilettoState::canvas), 1.0)
|
||||||
|
.controller(ToolSwitcher::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ToolSwitcher {
|
||||||
|
saved_tool: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToolSwitcher {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
ToolSwitcher { saved_tool: 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<W: Widget<StilettoState>> Controller<StilettoState, W> for ToolSwitcher {
|
||||||
|
fn event(
|
||||||
|
&mut self,
|
||||||
|
child: &mut W,
|
||||||
|
ctx: &mut EventCtx,
|
||||||
|
event: &Event,
|
||||||
|
data: &mut StilettoState,
|
||||||
|
env: &Env,
|
||||||
|
) {
|
||||||
|
match event {
|
||||||
|
Event::Notification(cmd) => {
|
||||||
|
let new_tool = if cmd.get(stiletto::commands::PUSH_ERASER).is_some() {
|
||||||
|
ctx.set_handled();
|
||||||
|
self.saved_tool = data.current_tool;
|
||||||
|
Some(data.eraser_tool_id)
|
||||||
|
} else if cmd.get(stiletto::commands::POP_ERASER).is_some() {
|
||||||
|
ctx.set_handled();
|
||||||
|
Some(self.saved_tool)
|
||||||
|
} else if cmd.get(stiletto::commands::UPDATE_TOOL).is_some() {
|
||||||
|
ctx.set_handled();
|
||||||
|
let old_tool = data.current_tool;
|
||||||
|
data.tool_icons
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.position(|(pos, x)| pos != old_tool && x.selected)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(new_tool) = new_tool {
|
||||||
|
data.set_tool(new_tool);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
child.event(ctx, event, data, env);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Delegate;
|
struct Delegate;
|
||||||
|
|
@ -156,53 +246,50 @@ impl AppDelegate<StilettoState> for Delegate {
|
||||||
cmd: &Command,
|
cmd: &Command,
|
||||||
data: &mut StilettoState,
|
data: &mut StilettoState,
|
||||||
_env: &Env,
|
_env: &Env,
|
||||||
) -> bool {
|
) -> Handled {
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
|
|
||||||
if let Some(Some(file_info)) = cmd.get(commands::SAVE_FILE) {
|
if cmd.get(commands::SAVE_FILE_AS).is_some() || cmd.get(commands::SAVE_FILE).is_some() {
|
||||||
let res_file = File::create(file_info.path());
|
let mut path_buf = cmd
|
||||||
|
.get(commands::SAVE_FILE_AS)
|
||||||
|
.map(|file_info| file_info.path().to_path_buf())
|
||||||
|
.or_else(|| data.current_file_path.as_ref().cloned())
|
||||||
|
.unwrap();
|
||||||
|
path_buf.set_extension("stlt");
|
||||||
|
|
||||||
|
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 {
|
||||||
info!("Written to file: {}", file_info.path().display());
|
info!("Written to file: {}", &path_buf.display());
|
||||||
|
data.current_file_path = Some(path_buf);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
warn!("Cannot create file: {:?}", res_file.err());
|
warn!("Cannot create file: {:?}", res_file.err());
|
||||||
}
|
}
|
||||||
return true;
|
return Handled::Yes;
|
||||||
}
|
}
|
||||||
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());
|
||||||
info!("Loaded file {}", file_info.path().display());
|
info!("Loaded file {}", file_info.path().display());
|
||||||
} else {
|
} else {
|
||||||
warn!("didn't work: {:?}", res_snapshot.err());
|
warn!(
|
||||||
|
"Error while loading {}: {:?}",
|
||||||
|
file_info.path().display(),
|
||||||
|
res_snapshot.err()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return Handled::Yes;
|
||||||
}
|
}
|
||||||
if cmd.get(stiletto::commands::UPDATE_TOOL).is_some() {
|
Handled::No
|
||||||
let old_tool = data.current_tool;
|
|
||||||
if let Some(new_tool) = data
|
|
||||||
.tool_icons
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.position(|(pos, x)| pos != old_tool && x.selected)
|
|
||||||
{
|
|
||||||
info!("Changing active tool to: tool #{}", new_tool);
|
|
||||||
data.tool_icons.get_mut(old_tool).unwrap().selected = false;
|
|
||||||
data.current_tool = new_tool;
|
|
||||||
data.canvas.set_tool_ctx(CanvasToolCtx::new(
|
|
||||||
data.tool_icons.get(new_tool).unwrap().tool_params.clone(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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)
|
||||||
|
}
|
||||||
|
|
||||||
102
src/tool.rs
102
src/tool.rs
|
|
@ -14,12 +14,7 @@
|
||||||
// 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 druid::kurbo::BezPath;
|
use druid::{Color, Data};
|
||||||
use druid::{Color, Data, Env, Event, EventCtx, PaintCtx};
|
|
||||||
|
|
||||||
use crate::canvas;
|
|
||||||
use crate::canvas::{Canvas, CanvasElement};
|
|
||||||
use crate::history::VersionedCanvas;
|
|
||||||
|
|
||||||
#[derive(Clone, Data)]
|
#[derive(Clone, Data)]
|
||||||
pub enum CanvasToolParams {
|
pub enum CanvasToolParams {
|
||||||
|
|
@ -33,98 +28,3 @@ pub enum CanvasToolType {
|
||||||
Eraser,
|
Eraser,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Data)]
|
|
||||||
pub enum CanvasToolState {
|
|
||||||
Idle,
|
|
||||||
DrawingFreehand { current_path: CanvasElement },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Data)]
|
|
||||||
pub struct CanvasToolCtx {
|
|
||||||
initial_params: CanvasToolParams,
|
|
||||||
state: CanvasToolState,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CanvasToolParams {
|
|
||||||
pub fn tool_type(&self) -> CanvasToolType {
|
|
||||||
match self {
|
|
||||||
CanvasToolParams::Pen { .. } => CanvasToolType::Pen,
|
|
||||||
CanvasToolParams::Eraser => CanvasToolType::Eraser,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CanvasToolCtx {
|
|
||||||
pub fn new(params: CanvasToolParams) -> Self {
|
|
||||||
CanvasToolCtx {
|
|
||||||
initial_params: params,
|
|
||||||
state: CanvasToolState::Idle,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn handle_event(
|
|
||||||
&mut self,
|
|
||||||
ctx: &EventCtx,
|
|
||||||
event: &Event,
|
|
||||||
mut vcanvas: &mut VersionedCanvas,
|
|
||||||
env: &Env,
|
|
||||||
) {
|
|
||||||
match self.initial_params.tool_type() {
|
|
||||||
CanvasToolType::Pen => self.handle_pen_event(&ctx, &event, &mut vcanvas, &env),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn handle_pen_event(
|
|
||||||
&mut self,
|
|
||||||
_ctx: &EventCtx,
|
|
||||||
event: &Event,
|
|
||||||
vcanvas: &mut VersionedCanvas,
|
|
||||||
_env: &Env,
|
|
||||||
) {
|
|
||||||
match (&mut self.state, event) {
|
|
||||||
(CanvasToolState::Idle, Event::MouseDown(mouse_event)) => {
|
|
||||||
let mut kurbo_path = BezPath::new();
|
|
||||||
kurbo_path.move_to((mouse_event.pos.x, mouse_event.pos.y));
|
|
||||||
self.state = CanvasToolState::DrawingFreehand {
|
|
||||||
current_path: CanvasElement::Freehand {
|
|
||||||
path: canvas::Path { kurbo_path },
|
|
||||||
thickness: 2.0,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
(
|
|
||||||
CanvasToolState::DrawingFreehand {
|
|
||||||
ref mut current_path,
|
|
||||||
},
|
|
||||||
Event::MouseMove(mouse_event),
|
|
||||||
) => {
|
|
||||||
current_path
|
|
||||||
.get_path_mut()
|
|
||||||
.unwrap()
|
|
||||||
.kurbo_path
|
|
||||||
.line_to((mouse_event.pos.x, mouse_event.pos.y));
|
|
||||||
}
|
|
||||||
(CanvasToolState::DrawingFreehand { .. }, Event::MouseUp(_)) => {
|
|
||||||
vcanvas.update(move |canvas: &mut Canvas| {
|
|
||||||
let current_state = std::mem::replace(&mut self.state, CanvasToolState::Idle);
|
|
||||||
if let CanvasToolState::DrawingFreehand { current_path } = current_state {
|
|
||||||
canvas.push_back(current_path);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn needs_repaint(&self) -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn paint(&self, ctx: &mut PaintCtx, _env: &Env) {
|
|
||||||
match &self.state {
|
|
||||||
CanvasToolState::DrawingFreehand { current_path } => current_path.draw(ctx),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -16,20 +16,29 @@
|
||||||
|
|
||||||
use im::Vector;
|
use im::Vector;
|
||||||
|
|
||||||
|
use super::tool_ctx::{CanvasToolCtx};
|
||||||
|
use crate::canvas::Canvas;
|
||||||
use crate::history::VersionedCanvas;
|
use crate::history::VersionedCanvas;
|
||||||
use crate::tool::CanvasToolCtx;
|
|
||||||
use crate::DocumentSnapshot;
|
use crate::DocumentSnapshot;
|
||||||
|
|
||||||
use druid::widget::prelude::*;
|
use druid::widget::prelude::*;
|
||||||
use druid::{Color, Data, Env, Event};
|
use druid::{Color, Data, Env, Event, PointerType};
|
||||||
|
|
||||||
#[derive(Clone, Data)]
|
#[derive(Clone, Data)]
|
||||||
pub struct CanvasState {
|
pub struct CanvasState {
|
||||||
pub versioned_canvas: VersionedCanvas,
|
versioned_canvas: VersionedCanvas,
|
||||||
pub tool_ctx: CanvasToolCtx,
|
tool_ctx: CanvasToolCtx,
|
||||||
|
temporary_erasing: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CanvasState {
|
impl CanvasState {
|
||||||
|
pub fn new(tool_ctx: CanvasToolCtx) -> Self {
|
||||||
|
CanvasState {
|
||||||
|
versioned_canvas: VersionedCanvas::new(Canvas::new()),
|
||||||
|
tool_ctx: tool_ctx,
|
||||||
|
temporary_erasing: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
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();
|
||||||
|
|
@ -44,25 +53,75 @@ impl CanvasState {
|
||||||
|
|
||||||
pub fn get_document_snapshot(&self) -> DocumentSnapshot {
|
pub fn get_document_snapshot(&self) -> DocumentSnapshot {
|
||||||
DocumentSnapshot {
|
DocumentSnapshot {
|
||||||
canvas_elements: self.versioned_canvas.get().iter().cloned().collect(),
|
format_version_major: 0,
|
||||||
|
format_version_minor: 1,
|
||||||
|
canvas_elements: self
|
||||||
|
.versioned_canvas
|
||||||
|
.get()
|
||||||
|
.elements()
|
||||||
|
.iter()
|
||||||
|
.cloned()
|
||||||
|
.collect(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_from_snapshot(&mut self, snapshot: DocumentSnapshot) {
|
pub fn set_from_snapshot(&mut self, snapshot: DocumentSnapshot) {
|
||||||
self.versioned_canvas = VersionedCanvas::new(Vector::from(snapshot.canvas_elements));
|
self.versioned_canvas = VersionedCanvas::new(Canvas::new_with_elements(Vector::from(
|
||||||
|
snapshot.canvas_elements,
|
||||||
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn get_tool_ctx(&self) -> &CanvasToolCtx {
|
||||||
|
&self.tool_ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_tool_ctx_mut(&mut self) -> &mut CanvasToolCtx {
|
||||||
|
&mut self.tool_ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_event(&mut self, mut ctx: &mut EventCtx, event: &Event, env: &Env) {
|
||||||
|
self.tool_ctx
|
||||||
|
.handle_event(ctx, event, &mut self.versioned_canvas, env);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct CanvasWidget;
|
pub struct CanvasWidget;
|
||||||
|
|
||||||
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) {
|
||||||
data.tool_ctx
|
ctx.request_focus();
|
||||||
.handle_event(ctx, event, &mut data.versioned_canvas, env);
|
let mut toggle_eraser_event = false;
|
||||||
|
let mut enable_temporary_erasing = false;
|
||||||
|
match event {
|
||||||
|
Event::MouseDown(mouse_event) => {
|
||||||
|
toggle_eraser_event = true;
|
||||||
|
enable_temporary_erasing = mouse_event.pointer_type == PointerType::Eraser;
|
||||||
|
}
|
||||||
|
Event::MouseMove(mouse_event) => {
|
||||||
|
toggle_eraser_event = true;
|
||||||
|
enable_temporary_erasing = mouse_event.pointer_type == PointerType::Eraser;
|
||||||
|
}
|
||||||
|
Event::MouseUp(mouse_event) => {
|
||||||
|
toggle_eraser_event = true;
|
||||||
|
enable_temporary_erasing = mouse_event.pointer_type == PointerType::Eraser;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
// TODO: the first eraser toggle is not handled
|
||||||
|
if toggle_eraser_event && data.temporary_erasing != enable_temporary_erasing {
|
||||||
|
if enable_temporary_erasing {
|
||||||
|
ctx.submit_notification(crate::commands::PUSH_ERASER);
|
||||||
|
} else {
|
||||||
|
ctx.submit_notification(crate::commands::POP_ERASER);
|
||||||
|
}
|
||||||
|
data.temporary_erasing = enable_temporary_erasing;
|
||||||
|
} else {
|
||||||
|
data.handle_event(ctx, event, env);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lifecycle(
|
fn lifecycle(
|
||||||
|
|
@ -117,11 +176,9 @@ impl Widget<CanvasState> for CanvasWidget {
|
||||||
// (ctx.size() returns the size of the layout rect we're painting in)
|
// (ctx.size() returns the size of the layout rect we're painting in)
|
||||||
let size = ctx.size();
|
let size = ctx.size();
|
||||||
let rect = size.to_rect();
|
let rect = size.to_rect();
|
||||||
// Note: ctx also has a `clear` method, but that clears the whole context,
|
|
||||||
// and we only want to clear this widget's area.
|
|
||||||
ctx.fill(rect, &Color::WHITE);
|
|
||||||
|
|
||||||
for element in data.versioned_canvas.get().iter() {
|
ctx.fill(rect, &Color::WHITE);
|
||||||
|
for element in data.versioned_canvas.get().elements().iter() {
|
||||||
element.draw(ctx);
|
element.draw(ctx);
|
||||||
}
|
}
|
||||||
if data.tool_ctx.needs_repaint() {
|
if data.tool_ctx.needs_repaint() {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
pub mod canvas;
|
pub mod canvas;
|
||||||
pub mod tool_icon;
|
pub mod tool_icon;
|
||||||
|
pub mod tool_ctx;
|
||||||
|
|
||||||
pub use canvas::*;
|
pub use canvas::*;
|
||||||
pub use tool_icon::*;
|
pub use tool_icon::*;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,179 @@
|
||||||
|
// 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::tool::{CanvasToolParams, CanvasToolType};
|
||||||
|
use crate::canvas::{Canvas, CanvasElement};
|
||||||
|
use crate::history::VersionedCanvas;
|
||||||
|
|
||||||
|
use druid::kurbo::BezPath;
|
||||||
|
use druid::{Data, Env, Event, EventCtx, MouseButton, MouseEvent, PaintCtx};
|
||||||
|
|
||||||
|
#[derive(Clone, Data)]
|
||||||
|
pub enum CanvasToolState {
|
||||||
|
Idle,
|
||||||
|
DrawingFreehand {
|
||||||
|
pen_params: CanvasToolParams,
|
||||||
|
current_path: CanvasElement,
|
||||||
|
},
|
||||||
|
Erasing,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Data)]
|
||||||
|
pub struct CanvasToolCtx {
|
||||||
|
initial_params: CanvasToolParams,
|
||||||
|
state: CanvasToolState,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CanvasToolParams {
|
||||||
|
pub fn tool_type(&self) -> CanvasToolType {
|
||||||
|
match self {
|
||||||
|
CanvasToolParams::Pen { .. } => CanvasToolType::Pen,
|
||||||
|
CanvasToolParams::Eraser => CanvasToolType::Eraser,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pressed(mouse_event: &MouseEvent) -> bool {
|
||||||
|
mouse_event.buttons.contains(MouseButton::Left)
|
||||||
|
|| mouse_event.button == MouseButton::Left
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CanvasToolCtx {
|
||||||
|
pub fn new(params: CanvasToolParams) -> Self {
|
||||||
|
CanvasToolCtx {
|
||||||
|
initial_params: params,
|
||||||
|
state: CanvasToolState::Idle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_event(
|
||||||
|
&mut self,
|
||||||
|
ctx: &EventCtx,
|
||||||
|
event: &Event,
|
||||||
|
mut vcanvas: &mut VersionedCanvas,
|
||||||
|
env: &Env,
|
||||||
|
) {
|
||||||
|
match self.initial_params.tool_type() {
|
||||||
|
CanvasToolType::Pen => self.handle_pen_event(&ctx, &event, &mut vcanvas, &env),
|
||||||
|
CanvasToolType::Eraser => self.handle_erase_event(&ctx, &event, &mut vcanvas, &env),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_erase_event(
|
||||||
|
&mut self,
|
||||||
|
_ctx: &EventCtx,
|
||||||
|
event: &Event,
|
||||||
|
vcanvas: &mut VersionedCanvas,
|
||||||
|
_env: &Env,
|
||||||
|
) {
|
||||||
|
match (&mut self.state, event) {
|
||||||
|
(CanvasToolState::Idle, Event::MouseDown(mouse_event)) if pressed(mouse_event) => {
|
||||||
|
self.state = CanvasToolState::Erasing;
|
||||||
|
}
|
||||||
|
(CanvasToolState::Erasing, Event::MouseMove(mouse_event)) if pressed(mouse_event) => {
|
||||||
|
let eraser_rect = druid::Rect::from_center_size(mouse_event.pos, (5.0, 5.0));
|
||||||
|
let old_elements = vcanvas.get().elements();
|
||||||
|
let mut new_elements = old_elements.clone();
|
||||||
|
new_elements.retain(|elem| {
|
||||||
|
// Check if the element intersects the eraser rect
|
||||||
|
if elem.bounding_box().intersect(eraser_rect).area() > 0.0 {
|
||||||
|
if elem.intersects_rect(eraser_rect) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
if new_elements.len() != old_elements.len() {
|
||||||
|
vcanvas.update(|canvas: &mut Canvas| {
|
||||||
|
*canvas = Canvas::new_with_elements(new_elements);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(CanvasToolState::Erasing, Event::MouseUp(mouse_event)) if pressed(mouse_event) => {
|
||||||
|
self.state = CanvasToolState::Idle;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_pen_event(
|
||||||
|
&mut self,
|
||||||
|
_ctx: &EventCtx,
|
||||||
|
event: &Event,
|
||||||
|
vcanvas: &mut VersionedCanvas,
|
||||||
|
_env: &Env,
|
||||||
|
) {
|
||||||
|
match (&mut self.state, event) {
|
||||||
|
(CanvasToolState::Idle, Event::MouseDown(mouse_event)) if pressed(mouse_event) => {
|
||||||
|
let mut kurbo_path = BezPath::new();
|
||||||
|
kurbo_path.move_to((mouse_event.pos.x, mouse_event.pos.y));
|
||||||
|
if let CanvasToolParams::Pen { thickness, color } = &self.initial_params {
|
||||||
|
self.state = CanvasToolState::DrawingFreehand {
|
||||||
|
pen_params: self.initial_params.clone(),
|
||||||
|
current_path: CanvasElement::Freehand {
|
||||||
|
path: crate::canvas::Path { kurbo_path },
|
||||||
|
thickness: *thickness,
|
||||||
|
stroke_color: color.clone(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(
|
||||||
|
CanvasToolState::DrawingFreehand {
|
||||||
|
ref mut current_path,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
Event::MouseMove(mouse_event),
|
||||||
|
) => if pressed(mouse_event) {
|
||||||
|
if let CanvasElement::Freehand { ref mut path, .. } = current_path {
|
||||||
|
path.kurbo_path
|
||||||
|
.line_to((mouse_event.pos.x, mouse_event.pos.y));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(CanvasToolState::DrawingFreehand { .. }, Event::MouseUp(mouse_event)) if pressed(mouse_event) => {
|
||||||
|
vcanvas.update(move |canvas: &mut Canvas| {
|
||||||
|
let current_state = std::mem::replace(&mut self.state, CanvasToolState::Idle);
|
||||||
|
if let CanvasToolState::DrawingFreehand { current_path, .. } = current_state {
|
||||||
|
if let CanvasElement::Freehand {
|
||||||
|
mut path,
|
||||||
|
mut thickness,
|
||||||
|
stroke_color,
|
||||||
|
} = current_path
|
||||||
|
{
|
||||||
|
canvas.add_element(CanvasElement::Freehand {
|
||||||
|
path,
|
||||||
|
thickness,
|
||||||
|
stroke_color,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn needs_repaint(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn paint(&self, ctx: &mut PaintCtx, _env: &Env) {
|
||||||
|
match &self.state {
|
||||||
|
CanvasToolState::DrawingFreehand { current_path, .. } => current_path.draw(ctx),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -17,7 +17,7 @@
|
||||||
use druid::widget::{Container, SizedBox, Svg, SvgData, ViewSwitcher, WidgetExt};
|
use druid::widget::{Container, SizedBox, Svg, SvgData, ViewSwitcher, WidgetExt};
|
||||||
use druid::{Color, Data, UnitPoint};
|
use druid::{Color, Data, UnitPoint};
|
||||||
|
|
||||||
use crate::tool::{CanvasToolParams, CanvasToolType};
|
use crate::tool::CanvasToolParams;
|
||||||
|
|
||||||
#[derive(Clone, Data)]
|
#[derive(Clone, Data)]
|
||||||
pub struct CanvasToolIconState {
|
pub struct CanvasToolIconState {
|
||||||
|
|
@ -26,10 +26,6 @@ pub struct CanvasToolIconState {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CanvasToolIconState {
|
impl CanvasToolIconState {
|
||||||
fn tool_type(&self) -> CanvasToolType {
|
|
||||||
self.tool_params.tool_type()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn svg_data(&self) -> SvgData {
|
fn svg_data(&self) -> SvgData {
|
||||||
match self.tool_params {
|
match self.tool_params {
|
||||||
CanvasToolParams::Pen { .. } => include_str!("../../icons/pen.svg")
|
CanvasToolParams::Pen { .. } => include_str!("../../icons/pen.svg")
|
||||||
|
|
@ -46,9 +42,9 @@ pub fn build_simple_tool_widget(
|
||||||
width: f64,
|
width: f64,
|
||||||
height: f64,
|
height: f64,
|
||||||
padding: f64,
|
padding: f64,
|
||||||
) -> ViewSwitcher<CanvasToolIconState, (CanvasToolType, bool)> {
|
) -> ViewSwitcher<CanvasToolIconState, CanvasToolIconState> {
|
||||||
ViewSwitcher::<CanvasToolIconState, (CanvasToolType, bool)>::new(
|
ViewSwitcher::<CanvasToolIconState, CanvasToolIconState>::new(
|
||||||
|tool_state, _| (tool_state.tool_type(), tool_state.selected),
|
|tool_state, _| tool_state.clone(),
|
||||||
move |_, tool_state, _| {
|
move |_, tool_state, _| {
|
||||||
Box::new(
|
Box::new(
|
||||||
Container::new(
|
Container::new(
|
||||||
|
|
@ -62,7 +58,7 @@ pub fn build_simple_tool_widget(
|
||||||
)
|
)
|
||||||
.border(
|
.border(
|
||||||
if tool_state.selected {
|
if tool_state.selected {
|
||||||
Color::rgb(10, 10, 10)
|
Color::rgb(10.0, 10.0, 10.0)
|
||||||
} else {
|
} else {
|
||||||
Color::BLACK
|
Color::BLACK
|
||||||
},
|
},
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue