Compare commits
19 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
32740f3b22 | |
|
|
6a2460c42f | |
|
|
721ad1eecf | |
|
|
0fdc73b9e4 | |
|
|
a2cf104697 | |
|
|
a1f813631b | |
|
|
f330760c1c | |
|
|
022377cb48 | |
|
|
3b048896e0 | |
|
|
390de72aa2 | |
|
|
57ef9e5e0e | |
|
|
56ed3b7c01 | |
|
|
827d8d6a1c | |
|
|
0b74394042 | |
|
|
3c6f161a54 | |
|
|
c72ac1cde3 | |
|
|
f42db5fb69 | |
|
|
7925cfb2d8 | |
|
|
7f5aae2714 |
File diff suppressed because it is too large
Load Diff
27
Cargo.toml
27
Cargo.toml
|
|
@ -3,27 +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"] }
|
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"] }
|
version = "0.9.2"
|
||||||
#druid = { path = "../druid/druid", features = ["im"] }
|
|
||||||
|
|
||||||
[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 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 122.88 103.38" style="enable-background:new 0 0 122.88 103.38" xml:space="preserve"><style type="text/css">.st0{fill-rule:evenodd;clip-rule:evenodd;fill:#f0f0f0;}</style><g><path class="st0" stroke="#f0f0f0" d="M27.66,93.53h32.49l9.1-9.08c1.4-1.4,1.41-3.7,0.01-5.1l-27.02-27.1c-1.4-1.4-3.7-1.41-5.1-0.01L14.3,75.03 c-1.41,1.4-1.41,3.7-0.01,5.1L27.66,93.53L27.66,93.53z M71.03,93.53h51.84v9.85H61.16H50.28h-12.8H25.7h-0.35L1.05,79.01 c-1.4-1.4-1.4-3.7,0.01-5.1L74.11,1.05c1.41-1.4,3.7-1.4,5.1,0.01l39.62,39.72c1.4,1.4,1.4,3.7-0.01,5.1L71.03,93.53L71.03,93.53z"/></g></svg>
|
||||||
|
After Width: | Height: | Size: 749 B |
|
|
@ -0,0 +1 @@
|
||||||
|
<svg height="21" viewBox="0 0 21 21" width="21" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd" stroke="#f0f0f0" stroke-linecap="round" stroke-linejoin="round" transform="translate(2 2)"><path d="m8.24920737-.79402796c1.17157287 0 2.12132033.94974747 2.12132033 2.12132034v13.43502882l-2.12132033 3.5355339-2.08147546-3.495689-.03442539-13.47488064c-.00298547-1.16857977.94191541-2.11832105 2.11049518-2.12130651.00180188-.00000461.00360378-.00000691.00540567-.00000691z" transform="matrix(.70710678 .70710678 -.70710678 .70710678 8.605553 -3.271644)"/><path d="m13.5 4.5 1 1"/></g></svg>
|
||||||
|
After Width: | Height: | Size: 611 B |
|
|
@ -1,122 +0,0 @@
|
||||||
// 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 log::{info, warn};
|
|
||||||
|
|
||||||
use druid::im::{vector, Vector};
|
|
||||||
use druid::widget::prelude::*;
|
|
||||||
use druid::widget::{Align, Label, Button, CrossAxisAlignment, Flex, List, ListGrowDirection, WidgetExt, SizedBox, ViewSwitcher};
|
|
||||||
use druid::{AppLauncher, Color, Data, LocalizedString, WindowDesc, Lens, UnitPoint};
|
|
||||||
|
|
||||||
#[derive(Clone, Data)]
|
|
||||||
enum CanvasToolState {
|
|
||||||
Pen { thickness: f64, color: Color },
|
|
||||||
Eraser,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, PartialEq)]
|
|
||||||
enum CanvasToolType {
|
|
||||||
Pen,
|
|
||||||
Eraser,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CanvasToolState {
|
|
||||||
fn tool_type(&self) -> CanvasToolType {
|
|
||||||
match self {
|
|
||||||
CanvasToolState::Pen { .. } => CanvasToolType::Pen,
|
|
||||||
CanvasToolState::Eraser => CanvasToolType::Eraser,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_simple_tool_widget(tool_state: &CanvasToolState) -> Box<dyn Widget<CanvasToolState>> {
|
|
||||||
let (label_text, bg_color) = match tool_state {
|
|
||||||
CanvasToolState::Pen { thickness, color } =>
|
|
||||||
(format!("pen {}", thickness), color.clone()),
|
|
||||||
CanvasToolState::Eraser =>
|
|
||||||
(String::from("eraser"), Color::rgb(200, 200, 200))
|
|
||||||
};
|
|
||||||
|
|
||||||
Box::new(
|
|
||||||
SizedBox::new(
|
|
||||||
Label::new(label_text)
|
|
||||||
.align_horizontal(UnitPoint::CENTER)
|
|
||||||
.background(bg_color)
|
|
||||||
.fix_width(100.0)
|
|
||||||
.fix_height(100.0)
|
|
||||||
)
|
|
||||||
.padding((10.0, 0.0)))
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone, Data, Lens)]
|
|
||||||
struct AppState {
|
|
||||||
tools: Vector<CanvasToolState>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_ui() -> impl Widget<AppState> {
|
|
||||||
let list_buttons = Flex::row()
|
|
||||||
.cross_axis_alignment(CrossAxisAlignment::Center)
|
|
||||||
.with_child(Button::new("Add"))
|
|
||||||
.with_child(Button::new("Remove"));
|
|
||||||
|
|
||||||
let number_list = Flex::row()
|
|
||||||
.cross_axis_alignment(CrossAxisAlignment::Center)
|
|
||||||
.with_flex_child(
|
|
||||||
List::new(|| {
|
|
||||||
ViewSwitcher::<CanvasToolState, CanvasToolType>::new(
|
|
||||||
|tool_state, _| tool_state.tool_type(),
|
|
||||||
|_, tool_state, _| {
|
|
||||||
build_simple_tool_widget(&tool_state)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.grow(ListGrowDirection::Right)
|
|
||||||
.lens(AppState::tools)
|
|
||||||
, 1.0);
|
|
||||||
|
|
||||||
let toolbar = Flex::row()
|
|
||||||
.cross_axis_alignment(CrossAxisAlignment::Center)
|
|
||||||
.with_spacer(30.0)
|
|
||||||
.with_child(Align::left(list_buttons))
|
|
||||||
.with_spacer(30.0)
|
|
||||||
.with_flex_child(Align::left(number_list), 1.0);
|
|
||||||
|
|
||||||
Flex::column()
|
|
||||||
.cross_axis_alignment(CrossAxisAlignment::Center)
|
|
||||||
.with_child(
|
|
||||||
SizedBox::new(toolbar)
|
|
||||||
.height(100.0)
|
|
||||||
.expand_width()
|
|
||||||
.align_horizontal(UnitPoint::TOP)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn main() {
|
|
||||||
let window = WindowDesc::new(build_ui)
|
|
||||||
.window_size((1000.0, 400.00))
|
|
||||||
.title(
|
|
||||||
LocalizedString::new("custom-widget-demo-window-title").with_placeholder("Tools"),
|
|
||||||
);
|
|
||||||
let app_state = AppState {
|
|
||||||
tools: vector![CanvasToolState::Eraser, CanvasToolState::Pen { thickness: 3.3, color: Color::rgb(30.0, 0.4, 0.4) }]
|
|
||||||
};
|
|
||||||
|
|
||||||
AppLauncher::with_window(window)
|
|
||||||
.use_simple_logger()
|
|
||||||
.launch(app_state)
|
|
||||||
.expect("launch failed");
|
|
||||||
}
|
|
||||||
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,241 @@
|
||||||
|
// 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 std::vec::Vec;
|
||||||
|
|
||||||
|
use im::{vector, Vector};
|
||||||
|
|
||||||
|
use serde::de::{Deserializer, SeqAccess, Visitor};
|
||||||
|
use serde::ser::Serializer;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, druid::Data)]
|
||||||
|
pub struct Path {
|
||||||
|
pub kurbo_path: druid::kurbo::BezPath,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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)]
|
||||||
|
pub enum CanvasElement {
|
||||||
|
Freehand {
|
||||||
|
path: Path,
|
||||||
|
thickness: f64,
|
||||||
|
#[serde(with = "ColorDef")]
|
||||||
|
stroke_color: druid::Color,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CanvasElement {
|
||||||
|
pub fn bounding_box(&self) -> druid::Rect {
|
||||||
|
match self {
|
||||||
|
CanvasElement::Freehand {
|
||||||
|
path, thickness, ..
|
||||||
|
} => {
|
||||||
|
use druid::kurbo::Shape;
|
||||||
|
path.kurbo_path
|
||||||
|
.bounding_box()
|
||||||
|
.inflate(*thickness, *thickness)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
match self {
|
||||||
|
CanvasElement::Freehand {
|
||||||
|
path,
|
||||||
|
thickness,
|
||||||
|
stroke_color,
|
||||||
|
} => {
|
||||||
|
use druid::RenderContext;
|
||||||
|
ctx.stroke(&path.kurbo_path, &*stroke_color, *thickness);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, druid::Data)]
|
||||||
|
pub struct Canvas {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
found_elements
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn content_size(&self) -> druid::Size {
|
||||||
|
self.content_size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Serialize for Path {
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
|
where
|
||||||
|
S: Serializer,
|
||||||
|
{
|
||||||
|
use druid::kurbo::PathEl;
|
||||||
|
|
||||||
|
serializer.collect_seq(self.kurbo_path.iter().filter_map(|path_el| match path_el {
|
||||||
|
PathEl::MoveTo(pt) => Some(Into::<(f64, f64)>::into(pt)),
|
||||||
|
PathEl::LineTo(pt) => Some(Into::<(f64, f64)>::into(pt)),
|
||||||
|
_ => None,
|
||||||
|
}).collect::<Vec<(f64, f64)>>())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 PathVisitor {
|
||||||
|
type Value = Path;
|
||||||
|
|
||||||
|
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||||
|
write!(formatter, "A sequence of 2D points")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
|
||||||
|
where
|
||||||
|
A: SeqAccess<'de>,
|
||||||
|
{
|
||||||
|
use druid::kurbo::BezPath;
|
||||||
|
|
||||||
|
let mut kurbo_path = BezPath::new();
|
||||||
|
let mut first_element = true;
|
||||||
|
while let Some(point) = seq.next_element::<(f64, f64)>()? {
|
||||||
|
if first_element {
|
||||||
|
kurbo_path.move_to(point);
|
||||||
|
first_element = false;
|
||||||
|
} else {
|
||||||
|
kurbo_path.line_to(point);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Path { kurbo_path })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
deserializer.deserialize_seq(PathVisitor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,92 @@
|
||||||
|
// 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 super::canvas::Canvas;
|
||||||
|
use im::Vector;
|
||||||
|
|
||||||
|
#[derive(Clone, druid::Data)]
|
||||||
|
pub struct VersionedCanvas {
|
||||||
|
// We internally guarantee that this vector
|
||||||
|
// is never empty
|
||||||
|
versions: Vector<Canvas>,
|
||||||
|
curr_version: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VersionedCanvas {
|
||||||
|
pub fn new(canvas: Canvas) -> VersionedCanvas {
|
||||||
|
VersionedCanvas {
|
||||||
|
versions: im::vector![canvas],
|
||||||
|
curr_version: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get current canvas version
|
||||||
|
pub fn get(&self) -> &Canvas {
|
||||||
|
self.versions.get(self.curr_version).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_newer_versions(&self) -> bool {
|
||||||
|
self.curr_version + 1 < self.versions.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_older_versions(&self) -> bool {
|
||||||
|
self.curr_version > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn undo(&mut self) {
|
||||||
|
if self.has_older_versions() {
|
||||||
|
self.curr_version -= 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn redo(&mut self) {
|
||||||
|
if self.has_newer_versions() {
|
||||||
|
self.curr_version += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
// 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
|
||||||
|
// and creates a new future.
|
||||||
|
if self.has_newer_versions() {
|
||||||
|
self.versions = self.versions.take(self.curr_version + 1);
|
||||||
|
}
|
||||||
|
self.versions.push_back(new_version);
|
||||||
|
self.curr_version += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do inplace update, which will be irreversible
|
||||||
|
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,
|
||||||
|
// 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
|
||||||
|
// and creates a new future.
|
||||||
|
if self.has_newer_versions() {
|
||||||
|
self.versions = self.versions.take(self.curr_version + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
202
src/lib.rs
202
src/lib.rs
|
|
@ -12,189 +12,37 @@
|
||||||
// GNU Affero General Public License for more details.
|
// GNU Affero General Public License for more details.
|
||||||
//
|
//
|
||||||
// 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/>.use serde::{Serialize, Deserialize};
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use im::Vector;
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::vec::Vec;
|
||||||
|
|
||||||
use serde::{Serialize, Deserialize};
|
pub mod canvas;
|
||||||
use serde::ser::{Serializer};
|
pub mod history;
|
||||||
use serde::de::{Deserializer, Visitor, SeqAccess};
|
pub mod tool;
|
||||||
use std::vec::{Vec};
|
pub mod widget;
|
||||||
|
pub mod migration;
|
||||||
|
|
||||||
#[derive(Debug, Clone, druid::Data)]
|
pub mod commands {
|
||||||
pub struct Path {
|
use druid::Selector;
|
||||||
pub kurbo_path: druid::kurbo::BezPath,
|
|
||||||
|
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");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, druid::Data, Serialize, Deserialize)]
|
pub const STILETTO_FORMAT_MAJOR: u16 = 0;
|
||||||
pub enum CanvasElement {
|
pub const STILETTO_FORMAT_MINOR: u16 = 2;
|
||||||
Freehand { path: Path, thickness: f64 },
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CanvasElement {
|
|
||||||
pub fn bounding_box(&self) -> druid::Rect {
|
|
||||||
match self {
|
|
||||||
CanvasElement::Freehand { path, thickness } => {
|
|
||||||
use druid::kurbo::Shape;
|
|
||||||
path.kurbo_path
|
|
||||||
.bounding_box()
|
|
||||||
.inflate(*thickness, *thickness)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn draw(&self, ctx: &mut druid::PaintCtx) {
|
|
||||||
match self {
|
|
||||||
CanvasElement::Freehand { path, thickness } => {
|
|
||||||
use druid::RenderContext;
|
|
||||||
let stroke_color = druid::Color::rgb8(0, 128, 0);
|
|
||||||
ctx.stroke(&path.kurbo_path, &stroke_color, *thickness);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_path_mut(&mut self) -> Option<&mut Path> {
|
|
||||||
match self {
|
|
||||||
CanvasElement::Freehand { path, .. } => Some(path),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A canvas contains all elements to be drawn
|
|
||||||
pub type Canvas = Vector<CanvasElement>;
|
|
||||||
|
|
||||||
#[derive(Clone, druid::Data)]
|
|
||||||
pub struct VersionedCanvas {
|
|
||||||
// We internally guarantee that this vector
|
|
||||||
// is never empty
|
|
||||||
versions: Vector<Canvas>,
|
|
||||||
curr_version: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VersionedCanvas {
|
|
||||||
pub fn new(canvas: Canvas) -> VersionedCanvas {
|
|
||||||
VersionedCanvas {
|
|
||||||
versions: im::vector![canvas],
|
|
||||||
curr_version: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get current canvas version
|
|
||||||
pub fn get(&self) -> &Canvas {
|
|
||||||
self.versions.get(self.curr_version).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn has_newer_versions(&self) -> bool {
|
|
||||||
self.curr_version + 1 < self.versions.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn has_older_versions(&self) -> bool {
|
|
||||||
self.curr_version > 0
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn undo(&mut self) {
|
|
||||||
if self.has_older_versions() {
|
|
||||||
self.curr_version = self.curr_version - 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn redo(&mut self) {
|
|
||||||
if self.has_newer_versions() {
|
|
||||||
self.curr_version = self.curr_version + 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
|
||||||
// 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
|
|
||||||
// and creates a new future.
|
|
||||||
if self.has_newer_versions() {
|
|
||||||
self.versions = self.versions.take(self.curr_version + 1);
|
|
||||||
}
|
|
||||||
self.versions.push_back(new_version);
|
|
||||||
self.curr_version = self.curr_version + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do inplace update, which will be irreversible
|
|
||||||
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,
|
|
||||||
// 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
|
|
||||||
// and creates a new future.
|
|
||||||
if self.has_newer_versions() {
|
|
||||||
self.versions = self.versions.take(self.curr_version + 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct PathDeserializer;
|
|
||||||
|
|
||||||
impl<'de> Visitor<'de> for PathDeserializer {
|
|
||||||
type Value = Path;
|
|
||||||
|
|
||||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
|
||||||
write!(formatter, "A sequence of 2D points")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
|
|
||||||
where
|
|
||||||
A: SeqAccess<'de>
|
|
||||||
{
|
|
||||||
use druid::kurbo::BezPath;
|
|
||||||
|
|
||||||
let mut kurbo_path = BezPath::new();
|
|
||||||
let mut first_element = true;
|
|
||||||
while let Some(point) = seq.next_element::<(f64, f64)>()? {
|
|
||||||
if first_element {
|
|
||||||
kurbo_path.move_to(point);
|
|
||||||
first_element = false;
|
|
||||||
} else {
|
|
||||||
kurbo_path.line_to(point);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Path{ kurbo_path })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for Path {
|
|
||||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
|
||||||
where
|
|
||||||
D: Deserializer<'de>
|
|
||||||
{
|
|
||||||
deserializer.deserialize_seq(PathDeserializer)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Serialize for Path {
|
|
||||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
|
||||||
where
|
|
||||||
S: Serializer,
|
|
||||||
{
|
|
||||||
use druid::kurbo::{PathEl};
|
|
||||||
|
|
||||||
serializer.collect_seq(
|
|
||||||
self.kurbo_path.iter()
|
|
||||||
.filter_map(|path_el| {
|
|
||||||
match path_el {
|
|
||||||
PathEl::MoveTo(pt) => Some(Into::<(f64, f64)>::into(pt)),
|
|
||||||
PathEl::LineTo(pt) => Some(Into::<(f64, f64)>::into(pt)),
|
|
||||||
_ => None
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct DocumentSnapshot {
|
pub struct DocumentSnapshot {
|
||||||
pub canvas_elements: Vec<CanvasElement>,
|
pub format_version_major: u16,
|
||||||
|
pub format_version_minor: u16,
|
||||||
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
454
src/main.rs
454
src/main.rs
|
|
@ -14,221 +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::im::{vector, Vector};
|
|
||||||
use druid::kurbo::BezPath;
|
|
||||||
use druid::widget::prelude::*;
|
|
||||||
use druid::{AppLauncher, Color, Data, Event, LocalizedString, WindowDesc, AppDelegate, Target, Env, DelegateCtx, FileDialogOptions, FileSpec, Command};
|
|
||||||
use druid::commands;
|
use druid::commands;
|
||||||
|
use druid::im::vector;
|
||||||
|
use druid::widget::prelude::*;
|
||||||
|
use druid::widget::{
|
||||||
|
Align, Button, Controller, CrossAxisAlignment, Flex, List, SizedBox, WidgetExt,
|
||||||
|
};
|
||||||
|
use druid::{
|
||||||
|
AppDelegate, AppLauncher, Color, Command, Data, DelegateCtx, Env, FileDialogOptions, FileSpec,
|
||||||
|
Handled, Lens, Target, WindowDesc,
|
||||||
|
};
|
||||||
|
|
||||||
use stiletto::{CanvasElement, VersionedCanvas, Canvas, DocumentSnapshot};
|
use im::Vector;
|
||||||
|
|
||||||
struct Delegate;
|
use stiletto::tool::CanvasToolParams;
|
||||||
|
use stiletto::widget::tool_ctx::{CanvasToolCtx};
|
||||||
#[derive(Clone, Data)]
|
use stiletto::widget::{build_simple_tool_widget, CanvasState, CanvasToolIconState, CanvasWidget};
|
||||||
struct CanvasData {
|
use stiletto::DocumentSnapshot;
|
||||||
current_element: Option<CanvasElement>,
|
|
||||||
elements: VersionedCanvas,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CanvasData {
|
|
||||||
fn is_drawing(&self) -> bool {
|
|
||||||
self.current_element.is_some()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn perform_undo(&mut self) {
|
|
||||||
if !self.is_drawing() {
|
|
||||||
self.elements.undo();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn perform_redo(&mut self) {
|
|
||||||
if !self.is_drawing() {
|
|
||||||
self.elements.redo();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_document_snapshot(&self) -> DocumentSnapshot {
|
|
||||||
DocumentSnapshot {
|
|
||||||
canvas_elements: self.elements.get().iter().cloned().collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_from_snapshot(&mut self, snapshot: DocumentSnapshot) {
|
|
||||||
self.current_element = None;
|
|
||||||
self.elements = VersionedCanvas::new(Vector::from(snapshot.canvas_elements));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct CanvasWidget;
|
|
||||||
|
|
||||||
impl Widget<CanvasData> for CanvasWidget {
|
|
||||||
fn event(&mut self, _ctx: &mut EventCtx, event: &Event, data: &mut CanvasData, _env: &Env) {
|
|
||||||
match event {
|
|
||||||
Event::MouseDown(mouse_event) => {
|
|
||||||
let mut kurbo_path = BezPath::new();
|
|
||||||
kurbo_path.move_to((mouse_event.pos.x, mouse_event.pos.y));
|
|
||||||
data.current_element = Some(CanvasElement::Freehand {
|
|
||||||
path: stiletto::Path { kurbo_path },
|
|
||||||
thickness: 2.0,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Event::MouseMove(mouse_event) => {
|
|
||||||
if data.is_drawing() {
|
|
||||||
if let Some(current_element) = data.current_element.as_mut() {
|
|
||||||
current_element
|
|
||||||
.get_path_mut()
|
|
||||||
.unwrap()
|
|
||||||
.kurbo_path
|
|
||||||
.line_to((mouse_event.pos.x, mouse_event.pos.y));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Event::MouseUp(_) => {
|
|
||||||
if data.is_drawing() {
|
|
||||||
if let Some(current_element) = data.current_element.take() {
|
|
||||||
|
|
||||||
data.elements.update(move |canvas: &mut Canvas| {
|
|
||||||
canvas.push_back(current_element);
|
|
||||||
});
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lifecycle(
|
|
||||||
&mut self,
|
|
||||||
_ctx: &mut LifeCycleCtx,
|
|
||||||
_event: &LifeCycle,
|
|
||||||
_data: &CanvasData,
|
|
||||||
_env: &Env,
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
|
|
||||||
fn update(
|
|
||||||
&mut self,
|
|
||||||
ctx: &mut UpdateCtx,
|
|
||||||
old_data: &CanvasData,
|
|
||||||
data: &CanvasData,
|
|
||||||
_env: &Env,
|
|
||||||
) {
|
|
||||||
// the current_element is moved to the elements array, no need to repaint
|
|
||||||
if old_data.is_drawing() && !data.is_drawing() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if data.is_drawing() {
|
|
||||||
if let Some(e) = data.current_element.as_ref() {
|
|
||||||
ctx.request_paint_rect(e.bounding_box());
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ctx.request_paint();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn layout(
|
|
||||||
&mut self,
|
|
||||||
_layout_ctx: &mut LayoutCtx,
|
|
||||||
bc: &BoxConstraints,
|
|
||||||
_data: &CanvasData,
|
|
||||||
_env: &Env,
|
|
||||||
) -> Size {
|
|
||||||
// BoxConstraints are passed by the parent widget.
|
|
||||||
// This method can return any Size within those constraints:
|
|
||||||
// bc.constrain(my_size)
|
|
||||||
//
|
|
||||||
// To check if a dimension is infinite or not (e.g. scrolling):
|
|
||||||
// bc.is_width_bounded() / bc.is_height_bounded()
|
|
||||||
bc.max()
|
|
||||||
}
|
|
||||||
|
|
||||||
// The paint method gets called last, after an event flow.
|
|
||||||
// It goes event -> update -> layout -> paint, and each method can influence the next.
|
|
||||||
// Basically, anything that changes the appearance of a widget causes a paint.
|
|
||||||
fn paint(&mut self, ctx: &mut PaintCtx, data: &CanvasData, _env: &Env) {
|
|
||||||
// (ctx.size() returns the size of the layout rect we're painting in)
|
|
||||||
let size = ctx.size();
|
|
||||||
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.elements.get().iter() {
|
|
||||||
element.draw(ctx);
|
|
||||||
}
|
|
||||||
if let Some(element) = &data.current_element {
|
|
||||||
element.draw(ctx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_ui() -> impl Widget<CanvasData> {
|
|
||||||
use druid::widget::{Align, Button, CrossAxisAlignment, Flex, SizedBox};
|
|
||||||
let history_buttons = Flex::row()
|
|
||||||
.cross_axis_alignment(CrossAxisAlignment::Center)
|
|
||||||
.with_child(
|
|
||||||
Button::new("Undo").on_click(|_ctx: &mut EventCtx, data: &mut CanvasData, _env: &Env| data.perform_undo())
|
|
||||||
)
|
|
||||||
.with_child(Button::new("Redo").on_click(|_ctx: &mut EventCtx, data: &mut CanvasData, _env: &Env| data.perform_redo()));
|
|
||||||
|
|
||||||
let stlt = FileSpec::new("Stiletto notebook", &["stlt"]);
|
|
||||||
let save_dialog_options = FileDialogOptions::new()
|
|
||||||
.allowed_types(vec![stlt])
|
|
||||||
.default_type(stlt);
|
|
||||||
let open_dialog_options = save_dialog_options.clone();
|
|
||||||
|
|
||||||
let save_buttons = Flex::row()
|
|
||||||
.cross_axis_alignment(CrossAxisAlignment::Center)
|
|
||||||
.with_child(
|
|
||||||
Button::new("Open")
|
|
||||||
.on_click(move |ctx, _, _| {
|
|
||||||
ctx.submit_command(
|
|
||||||
Command::new(
|
|
||||||
druid::commands::SHOW_OPEN_PANEL,
|
|
||||||
open_dialog_options.clone(),
|
|
||||||
),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}))
|
|
||||||
.with_child(
|
|
||||||
Button::new("Save")
|
|
||||||
.on_click(move |ctx, _, _| {
|
|
||||||
ctx.submit_command(
|
|
||||||
Command::new(
|
|
||||||
druid::commands::SHOW_SAVE_PANEL,
|
|
||||||
save_dialog_options.clone(),
|
|
||||||
),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}));
|
|
||||||
|
|
||||||
|
|
||||||
let toolbar = Flex::row()
|
|
||||||
.cross_axis_alignment(CrossAxisAlignment::Center)
|
|
||||||
.with_spacer(30.0)
|
|
||||||
.with_flex_child(Align::left(history_buttons), 1.0)
|
|
||||||
.with_flex_child(Align::right(save_buttons), 1.0)
|
|
||||||
.with_spacer(30.0);
|
|
||||||
|
|
||||||
Flex::column()
|
|
||||||
.cross_axis_alignment(CrossAxisAlignment::Center)
|
|
||||||
.must_fill_main_axis(true)
|
|
||||||
.with_child(SizedBox::new(Align::left(toolbar)).height(50.0))
|
|
||||||
.with_flex_child(CanvasWidget {}, 1.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
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())
|
||||||
let canvas_data = CanvasData {
|
} else {
|
||||||
current_element: None,
|
String::from("New Document")
|
||||||
elements: VersionedCanvas::new(vector![]),
|
};
|
||||||
|
format!("Stiletto - {}", doc_name)
|
||||||
|
});
|
||||||
|
|
||||||
|
let default_pen_params = CanvasToolParams::Pen {
|
||||||
|
thickness: 2.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 {
|
||||||
|
canvas: CanvasState::new(CanvasToolCtx::new(default_pen_params.clone())),
|
||||||
|
tool_icons: vector![
|
||||||
|
CanvasToolIconState {
|
||||||
|
tool_params: default_pen_params,
|
||||||
|
selected: true,
|
||||||
|
},
|
||||||
|
CanvasToolIconState {
|
||||||
|
tool_params: default_pen_params_2,
|
||||||
|
selected: false,
|
||||||
|
},
|
||||||
|
CanvasToolIconState {
|
||||||
|
tool_params: CanvasToolParams::Eraser,
|
||||||
|
selected: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
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()
|
||||||
|
|
@ -237,43 +83,213 @@ pub fn main() {
|
||||||
.expect("launch failed");
|
.expect("launch failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppDelegate<CanvasData> for Delegate {
|
#[derive(Clone, Data, Lens)]
|
||||||
|
struct StilettoState {
|
||||||
|
canvas: CanvasState,
|
||||||
|
tool_icons: Vector<CanvasToolIconState>,
|
||||||
|
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> {
|
||||||
|
let history_buttons = Flex::row()
|
||||||
|
.cross_axis_alignment(CrossAxisAlignment::Center)
|
||||||
|
.with_child(Button::new("Undo").on_click(
|
||||||
|
|_ctx: &mut EventCtx, data: &mut StilettoState, _env: &Env| data.canvas.perform_undo(),
|
||||||
|
))
|
||||||
|
.with_child(Button::new("Redo").on_click(
|
||||||
|
|_ctx: &mut EventCtx, data: &mut StilettoState, _env: &Env| data.canvas.perform_redo(),
|
||||||
|
));
|
||||||
|
|
||||||
|
let stlt = FileSpec::new("Stiletto notebook", &["stlt"]);
|
||||||
|
let save_dialog_options = FileDialogOptions::new()
|
||||||
|
.allowed_types(vec![stlt])
|
||||||
|
.default_type(stlt);
|
||||||
|
let save_dialog_options_clone = save_dialog_options.clone();
|
||||||
|
let open_dialog_options = save_dialog_options.clone();
|
||||||
|
|
||||||
|
let save_buttons = Flex::row()
|
||||||
|
.cross_axis_alignment(CrossAxisAlignment::Center)
|
||||||
|
.with_child(
|
||||||
|
Button::new("Save").on_click(move |ctx, data: &mut StilettoState, _| {
|
||||||
|
if data.current_file_path.is_some() {
|
||||||
|
ctx.submit_command(Command::new(commands::SAVE_FILE, (), Target::Auto));
|
||||||
|
} else {
|
||||||
|
ctx.submit_command(Command::new(
|
||||||
|
druid::commands::SHOW_SAVE_PANEL,
|
||||||
|
save_dialog_options_clone.clone(),
|
||||||
|
Target::Auto,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.with_child(Button::new("Save As").on_click(move |ctx, _, _| {
|
||||||
|
ctx.submit_command(Command::new(
|
||||||
|
druid::commands::SHOW_SAVE_PANEL,
|
||||||
|
save_dialog_options.clone(),
|
||||||
|
Target::Auto,
|
||||||
|
))
|
||||||
|
}))
|
||||||
|
.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()
|
||||||
|
.cross_axis_alignment(CrossAxisAlignment::Center)
|
||||||
|
.with_flex_child(
|
||||||
|
List::new(|| {
|
||||||
|
build_simple_tool_widget(30.0, 30.0, 5.0)
|
||||||
|
.padding((8.0, 0.0))
|
||||||
|
.on_click(|ctx, tool_state, _| {
|
||||||
|
tool_state.selected = true;
|
||||||
|
ctx.submit_notification(stiletto::commands::UPDATE_TOOL);
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.horizontal()
|
||||||
|
.lens(StilettoState::tool_icons),
|
||||||
|
1.0,
|
||||||
|
);
|
||||||
|
|
||||||
|
let toolbar = Flex::row()
|
||||||
|
.cross_axis_alignment(CrossAxisAlignment::Center)
|
||||||
|
.with_spacer(30.0)
|
||||||
|
.with_flex_child(Align::left(history_buttons), 1.0)
|
||||||
|
.with_spacer(10.0)
|
||||||
|
.with_flex_child(Align::left(tool_buttons), 2.0)
|
||||||
|
.with_spacer(20.0)
|
||||||
|
.with_flex_child(Align::right(save_buttons), 1.0)
|
||||||
|
.with_spacer(30.0);
|
||||||
|
|
||||||
|
Flex::column()
|
||||||
|
.cross_axis_alignment(CrossAxisAlignment::Center)
|
||||||
|
.must_fill_main_axis(true)
|
||||||
|
.with_child(SizedBox::new(Align::left(toolbar)).height(50.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;
|
||||||
|
|
||||||
|
impl AppDelegate<StilettoState> for Delegate {
|
||||||
fn command(
|
fn command(
|
||||||
&mut self,
|
&mut self,
|
||||||
_ctx: &mut DelegateCtx,
|
_ctx: &mut DelegateCtx,
|
||||||
_target: Target,
|
_target: Target,
|
||||||
cmd: &Command,
|
cmd: &Command,
|
||||||
data: &mut CanvasData,
|
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 = serde_json::to_writer_pretty(f, &data.get_document_snapshot());
|
let write_res =
|
||||||
|
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> = serde_json::from_reader(f);
|
let res_snapshot: Result<DocumentSnapshot, serde_bare::Error> =
|
||||||
|
serde_bare::from_reader(f);
|
||||||
if let Ok(document_snapshot) = res_snapshot {
|
if let Ok(document_snapshot) = res_snapshot {
|
||||||
data.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;
|
||||||
}
|
}
|
||||||
false
|
Handled::No
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -0,0 +1,30 @@
|
||||||
|
// 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 druid::{Color, Data};
|
||||||
|
|
||||||
|
#[derive(Clone, Data)]
|
||||||
|
pub enum CanvasToolParams {
|
||||||
|
Pen { thickness: f64, color: Color },
|
||||||
|
Eraser,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq)]
|
||||||
|
pub enum CanvasToolType {
|
||||||
|
Pen,
|
||||||
|
Eraser,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -0,0 +1,188 @@
|
||||||
|
// 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 im::Vector;
|
||||||
|
|
||||||
|
use super::tool_ctx::{CanvasToolCtx};
|
||||||
|
use crate::canvas::Canvas;
|
||||||
|
use crate::history::VersionedCanvas;
|
||||||
|
use crate::DocumentSnapshot;
|
||||||
|
|
||||||
|
use druid::widget::prelude::*;
|
||||||
|
use druid::{Color, Data, Env, Event, PointerType};
|
||||||
|
|
||||||
|
#[derive(Clone, Data)]
|
||||||
|
pub struct CanvasState {
|
||||||
|
versioned_canvas: VersionedCanvas,
|
||||||
|
tool_ctx: CanvasToolCtx,
|
||||||
|
temporary_erasing: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
//if !self.is_drawing() {
|
||||||
|
self.versioned_canvas.undo();
|
||||||
|
//}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn perform_redo(&mut self) {
|
||||||
|
//if !self.is_drawing() {
|
||||||
|
self.versioned_canvas.redo();
|
||||||
|
//}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_document_snapshot(&self) -> DocumentSnapshot {
|
||||||
|
DocumentSnapshot {
|
||||||
|
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) {
|
||||||
|
self.versioned_canvas = VersionedCanvas::new(Canvas::new_with_elements(Vector::from(
|
||||||
|
snapshot.canvas_elements,
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_tool_ctx(&mut self, ctx: CanvasToolCtx) {
|
||||||
|
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;
|
||||||
|
|
||||||
|
impl Widget<CanvasState> for CanvasWidget {
|
||||||
|
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut CanvasState, env: &Env) {
|
||||||
|
ctx.request_focus();
|
||||||
|
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(
|
||||||
|
&mut self,
|
||||||
|
_ctx: &mut LifeCycleCtx,
|
||||||
|
_event: &LifeCycle,
|
||||||
|
_data: &CanvasState,
|
||||||
|
_env: &Env,
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut UpdateCtx,
|
||||||
|
_old_data: &CanvasState,
|
||||||
|
_data: &CanvasState,
|
||||||
|
_env: &Env,
|
||||||
|
) {
|
||||||
|
// the current_element is moved to the versioned_canvas array, no need to repaint
|
||||||
|
//if old_data.is_drawing() && !data.is_drawing() {
|
||||||
|
// return;
|
||||||
|
//}
|
||||||
|
//if data.is_drawing() {
|
||||||
|
// if let Some(e) = data.current_element.as_ref() {
|
||||||
|
// ctx.request_paint_rect(e.bounding_box());
|
||||||
|
// }
|
||||||
|
//} else {
|
||||||
|
ctx.request_paint();
|
||||||
|
//}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layout(
|
||||||
|
&mut self,
|
||||||
|
_layout_ctx: &mut LayoutCtx,
|
||||||
|
bc: &BoxConstraints,
|
||||||
|
_data: &CanvasState,
|
||||||
|
_env: &Env,
|
||||||
|
) -> Size {
|
||||||
|
// BoxConstraints are passed by the parent widget.
|
||||||
|
// This method can return any Size within those constraints:
|
||||||
|
// bc.constrain(my_size)
|
||||||
|
//
|
||||||
|
// To check if a dimension is infinite or not (e.g. scrolling):
|
||||||
|
// bc.is_width_bounded() / bc.is_height_bounded()
|
||||||
|
bc.max()
|
||||||
|
}
|
||||||
|
|
||||||
|
// The paint method gets called last, after an event flow.
|
||||||
|
// It goes event -> update -> layout -> paint, and each method can influence the next.
|
||||||
|
// Basically, anything that changes the appearance of a widget causes a paint.
|
||||||
|
fn paint(&mut self, ctx: &mut PaintCtx, data: &CanvasState, env: &Env) {
|
||||||
|
// (ctx.size() returns the size of the layout rect we're painting in)
|
||||||
|
let size = ctx.size();
|
||||||
|
let rect = size.to_rect();
|
||||||
|
|
||||||
|
ctx.fill(rect, &Color::WHITE);
|
||||||
|
for element in data.versioned_canvas.get().elements().iter() {
|
||||||
|
element.draw(ctx);
|
||||||
|
}
|
||||||
|
if data.tool_ctx.needs_repaint() {
|
||||||
|
data.tool_ctx.paint(ctx, env);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
pub mod canvas;
|
||||||
|
pub mod tool_icon;
|
||||||
|
pub mod tool_ctx;
|
||||||
|
|
||||||
|
pub use canvas::*;
|
||||||
|
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),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,70 @@
|
||||||
|
// 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 druid::widget::{Container, SizedBox, Svg, SvgData, ViewSwitcher, WidgetExt};
|
||||||
|
use druid::{Color, Data, UnitPoint};
|
||||||
|
|
||||||
|
use crate::tool::CanvasToolParams;
|
||||||
|
|
||||||
|
#[derive(Clone, Data)]
|
||||||
|
pub struct CanvasToolIconState {
|
||||||
|
pub tool_params: CanvasToolParams,
|
||||||
|
pub selected: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CanvasToolIconState {
|
||||||
|
fn svg_data(&self) -> SvgData {
|
||||||
|
match self.tool_params {
|
||||||
|
CanvasToolParams::Pen { .. } => include_str!("../../icons/pen.svg")
|
||||||
|
.parse::<SvgData>()
|
||||||
|
.unwrap(),
|
||||||
|
CanvasToolParams::Eraser => include_str!("../../icons/eraser.svg")
|
||||||
|
.parse::<SvgData>()
|
||||||
|
.unwrap(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_simple_tool_widget(
|
||||||
|
width: f64,
|
||||||
|
height: f64,
|
||||||
|
padding: f64,
|
||||||
|
) -> ViewSwitcher<CanvasToolIconState, CanvasToolIconState> {
|
||||||
|
ViewSwitcher::<CanvasToolIconState, CanvasToolIconState>::new(
|
||||||
|
|tool_state, _| tool_state.clone(),
|
||||||
|
move |_, tool_state, _| {
|
||||||
|
Box::new(
|
||||||
|
Container::new(
|
||||||
|
SizedBox::new(
|
||||||
|
Svg::new(tool_state.svg_data())
|
||||||
|
.align_horizontal(UnitPoint::CENTER)
|
||||||
|
.fix_width(width)
|
||||||
|
.fix_height(height),
|
||||||
|
)
|
||||||
|
.padding(padding),
|
||||||
|
)
|
||||||
|
.border(
|
||||||
|
if tool_state.selected {
|
||||||
|
Color::rgb(10.0, 10.0, 10.0)
|
||||||
|
} else {
|
||||||
|
Color::BLACK
|
||||||
|
},
|
||||||
|
1.0,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue