Compare commits

...

1 Commits

Author SHA1 Message Date
Enrico Lumetti bf63d5880f Add Viewport up/down scroll and some misc improvements 2021-02-28 15:31:59 +01:00
4 changed files with 197 additions and 49 deletions

View File

@ -16,7 +16,7 @@
use std::vec::Vec;
use im::Vector;
use im::{vector, Vector};
use serde::de::{Deserializer, SeqAccess, Visitor};
use serde::ser::Serializer;
@ -128,20 +128,48 @@ impl CanvasElement {
}
}
}
pub fn get_path_mut(&mut self) -> Option<&mut Path> {
match self {
CanvasElement::Freehand { path, .. } => Some(path),
}
}
}
#[derive(Clone, druid::Data)]
pub struct Canvas {
pub elements: Vector<CanvasElement>,
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 remove_element_at(&mut self, index: usize) {
// TODO(enrico): content size should be recomputed
self.elements.remove(index);
}
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();
@ -157,6 +185,10 @@ impl Canvas {
found_elements
}
pub fn content_size(&self) -> druid::Size {
self.content_size
}
}
impl Serialize for Path {

View File

@ -14,6 +14,8 @@
// 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::path::PathBuf;
use log::{info, warn};
use druid::commands;
@ -22,23 +24,28 @@ use druid::widget::prelude::*;
use druid::widget::{Align, Button, CrossAxisAlignment, Flex, List, SizedBox, WidgetExt};
use druid::{
AppDelegate, AppLauncher, Color, Command, Data, DelegateCtx, Env, FileDialogOptions, FileSpec,
Handled, Lens, LocalizedString, Target, WindowDesc,
Handled, Lens, LocalizedString, Target, WidgetId, WindowDesc,
};
use im::Vector;
use stiletto::canvas::Canvas;
use stiletto::history::VersionedCanvas;
use stiletto::tool::{CanvasToolCtx, CanvasToolParams};
use stiletto::widget::{build_simple_tool_widget, CanvasState, CanvasToolIconState, CanvasWidget};
use stiletto::widget::{
build_simple_tool_widget, CanvasState, CanvasToolIconState, CanvasWidget, SCROLL,
};
use stiletto::DocumentSnapshot;
pub fn main() {
let window = WindowDesc::new(build_ui)
.window_size((1024.0, 1400.0))
.title(
LocalizedString::new("custom-widget-demo-window-title").with_placeholder("Stiletto"),
);
.title(|data: &StilettoState, _env: &Env| {
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 {
thickness: 2.0,
@ -49,12 +56,7 @@ pub fn main() {
color: Color::rgb(255.0, 0.0, 0.0),
};
let canvas_data = StilettoState {
canvas: CanvasState {
versioned_canvas: VersionedCanvas::new(Canvas {
elements: vector![],
}),
tool_ctx: CanvasToolCtx::new(default_pen_params.clone()),
},
canvas: CanvasState::new(CanvasToolCtx::new(default_pen_params.clone())),
tool_icons: vector![
CanvasToolIconState {
tool_params: default_pen_params,
@ -70,6 +72,7 @@ pub fn main() {
},
],
current_tool: 0,
current_file_path: None,
};
AppLauncher::with_window(window)
.use_simple_logger()
@ -83,9 +86,13 @@ struct StilettoState {
canvas: CanvasState,
tool_icons: Vector<CanvasToolIconState>,
current_tool: usize,
#[data(same_fn = "PartialEq::eq")]
current_file_path: Option<PathBuf>,
}
fn build_ui() -> impl Widget<StilettoState> {
let canvas_id = WidgetId::next();
let history_buttons = Flex::row()
.cross_axis_alignment(CrossAxisAlignment::Center)
.with_child(Button::new("Undo").on_click(
@ -103,6 +110,16 @@ fn build_ui() -> impl Widget<StilettoState> {
let save_buttons = Flex::row()
.cross_axis_alignment(CrossAxisAlignment::Center)
.with_child(Button::new("Up").on_click(
move |ctx: &mut EventCtx, _data: &mut StilettoState, _env: &Env| {
ctx.submit_command(Command::new(SCROLL, -30.0, canvas_id));
},
))
.with_child(Button::new("Down").on_click(
move |ctx: &mut EventCtx, _data: &mut StilettoState, _env: &Env| {
ctx.submit_command(Command::new(SCROLL, 30.0, canvas_id));
},
))
.with_child(Button::new("Open").on_click(move |ctx, _, _| {
ctx.submit_command(Command::new(
druid::commands::SHOW_OPEN_PANEL,
@ -148,7 +165,12 @@ fn build_ui() -> impl Widget<StilettoState> {
.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)
.with_flex_child(
CanvasWidget::new()
.lens(StilettoState::canvas)
.with_id(canvas_id),
1.0,
)
}
struct Delegate;
@ -164,6 +186,10 @@ impl AppDelegate<StilettoState> for Delegate {
) -> Handled {
use std::fs::File;
if cmd.get(commands::SAVE_FILE).is_some() {
//let path = data.current_file_path.as_ref().unwrap();
// TODO
}
if let Some(file_info) = cmd.get(commands::SAVE_FILE_AS) {
let res_file = File::create(file_info.path());
if let Ok(f) = res_file {
@ -172,6 +198,7 @@ impl AppDelegate<StilettoState> for Delegate {
if write_res.is_err() {
warn!("Error while saving: {:?}", write_res.err());
} else {
data.current_file_path = Some(file_info.path().to_path_buf());
info!("Written to file: {}", file_info.path().display());
}
} else {
@ -185,9 +212,14 @@ impl AppDelegate<StilettoState> for Delegate {
serde_json::from_reader(f);
if let Ok(document_snapshot) = res_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());
} else {
warn!("Error while loading {}: {:?}", file_info.path().display(), res_snapshot.err());
warn!(
"Error while loading {}: {:?}",
file_info.path().display(),
res_snapshot.err()
);
}
}
return Handled::Yes;

View File

@ -15,7 +15,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use druid::kurbo::BezPath;
use druid::{Color, Data, Env, Event, EventCtx, PaintCtx};
use druid::{Affine, Color, Data, Env, Event, EventCtx, PaintCtx};
use crate::canvas;
use crate::canvas::{Canvas, CanvasElement};
@ -71,11 +71,16 @@ impl CanvasToolCtx {
ctx: &EventCtx,
event: &Event,
mut vcanvas: &mut VersionedCanvas,
transform: Affine,
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),
CanvasToolType::Pen => {
self.handle_pen_event(&ctx, &event, &mut vcanvas, transform, &env)
}
CanvasToolType::Eraser => {
self.handle_erase_event(&ctx, &event, &mut vcanvas, transform, &env)
}
}
}
@ -84,6 +89,7 @@ impl CanvasToolCtx {
_ctx: &EventCtx,
event: &Event,
vcanvas: &mut VersionedCanvas,
transform: Affine,
_env: &Env,
) {
match (&mut self.state, event) {
@ -91,13 +97,14 @@ impl CanvasToolCtx {
self.state = CanvasToolState::Erasing;
}
(CanvasToolState::Erasing, Event::MouseMove(mouse_event)) => {
let eraser_rect = druid::Rect::from_center_size(mouse_event.pos, (5.0, 5.0));
let eraser_rect =
druid::Rect::from_center_size(transform * mouse_event.pos, (5.0, 5.0));
let elements = vcanvas.get().find_intersections(eraser_rect);
if !elements.is_empty() {
vcanvas.update(|canvas: &mut Canvas| {
for i in elements {
canvas.elements.remove(i);
canvas.remove_element_at(i);
}
});
}
@ -114,6 +121,7 @@ impl CanvasToolCtx {
_ctx: &EventCtx,
event: &Event,
vcanvas: &mut VersionedCanvas,
transform: Affine,
_env: &Env,
) {
match (&mut self.state, event) {
@ -138,17 +146,28 @@ impl CanvasToolCtx {
},
Event::MouseMove(mouse_event),
) => {
current_path
.get_path_mut()
.unwrap()
.kurbo_path
.line_to((mouse_event.pos.x, mouse_event.pos.y));
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(_)) => {
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.elements.push_back(current_path);
if let CanvasElement::Freehand {
mut path,
mut thickness,
stroke_color,
} = current_path
{
path.kurbo_path.apply_affine(transform);
canvas.add_element(CanvasElement::Freehand {
path,
thickness,
stroke_color,
});
}
}
});
}

View File

@ -21,8 +21,13 @@ use crate::history::VersionedCanvas;
use crate::tool::CanvasToolCtx;
use crate::DocumentSnapshot;
use druid::scroll_component::ScrollComponent;
use druid::widget::prelude::*;
use druid::{Color, Data, Env, Event};
use druid::widget::Viewport;
use druid::{Affine, Color, Data, Env, Event};
use druid::{Command, Selector, Target};
pub const SCROLL: Selector<f64> = Selector::new("scroll_canvas");
#[derive(Clone, Data)]
pub struct CanvasState {
@ -31,6 +36,12 @@ pub struct CanvasState {
}
impl CanvasState {
pub fn new(tool_ctx: CanvasToolCtx) -> Self {
CanvasState {
versioned_canvas: VersionedCanvas::new(Canvas::new()),
tool_ctx,
}
}
pub fn perform_undo(&mut self) {
//if !self.is_drawing() {
self.versioned_canvas.undo();
@ -50,7 +61,7 @@ impl CanvasState {
canvas_elements: self
.versioned_canvas
.get()
.elements
.elements()
.iter()
.cloned()
.collect(),
@ -58,9 +69,9 @@ impl CanvasState {
}
pub fn set_from_snapshot(&mut self, snapshot: DocumentSnapshot) {
self.versioned_canvas = VersionedCanvas::new(Canvas {
elements: 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) {
@ -68,21 +79,62 @@ impl CanvasState {
}
}
pub struct CanvasWidget;
pub struct CanvasWidget {
viewport: Viewport,
scroll_component: ScrollComponent,
}
impl CanvasWidget {
pub fn new() -> Self {
CanvasWidget {
viewport: Viewport {
content_size: Size::new(0.0, 0.0),
rect: druid::Rect::new(0.0, 0.0, 0.0, 0.0),
},
scroll_component: ScrollComponent::new(),
}
}
}
impl Widget<CanvasState> for CanvasWidget {
fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut CanvasState, env: &Env) {
data.tool_ctx
.handle_event(ctx, event, &mut data.versioned_canvas, env);
ctx.request_focus();
let mut needs_update = false;
match event {
Event::Command(cmd) => {
if let Some(value) = cmd.get(SCROLL) {
self.viewport.rect.y0 += value;
needs_update = true;
}
}
Event::KeyDown(key_event) => {
if key_event.code == druid::Code::ArrowDown {
self.viewport.rect.y0 += 30.0;
needs_update = true;
} else if key_event.code == druid::Code::ArrowUp {
self.viewport.rect.y0 = 0.0_f64.max(self.viewport.rect.y0 - 30.0);
needs_update = true;
}
}
_ => {
let transform = Affine::translate((self.viewport.rect.x0, self.viewport.rect.y0));
data.tool_ctx
.handle_event(ctx, event, &mut data.versioned_canvas, transform, env);
}
}
if needs_update {
ctx.request_paint();
}
}
fn lifecycle(
&mut self,
_ctx: &mut LifeCycleCtx,
_event: &LifeCycle,
ctx: &mut LifeCycleCtx,
event: &LifeCycle,
_data: &CanvasState,
_env: &Env,
env: &Env,
) {
self.scroll_component.lifecycle(ctx, event, env);
}
fn update(
@ -101,6 +153,7 @@ impl Widget<CanvasState> for CanvasWidget {
// ctx.request_paint_rect(e.bounding_box());
// }
//} else {
ctx.request_paint();
//}
}
@ -128,15 +181,27 @@ impl Widget<CanvasState> for CanvasWidget {
// (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.versioned_canvas.get().elements.iter() {
let page_content_size = data.versioned_canvas.get().content_size();
ctx.fill(rect, &Color::WHITE);
self.viewport.rect = self.viewport.rect.with_size(size);
self.viewport.content_size = druid::Size::new(
self.viewport.rect.x1.max(page_content_size.width),
self.viewport.rect.y1.max(page_content_size.height),
);
ctx.save().unwrap();
ctx.transform(Affine::translate((
-self.viewport.rect.x0,
-self.viewport.rect.y0,
)));
for element in data.versioned_canvas.get().elements().iter() {
element.draw(ctx);
}
ctx.restore().unwrap();
if data.tool_ctx.needs_repaint() {
data.tool_ctx.paint(ctx, env);
}
self.scroll_component.draw_bars(ctx, &self.viewport, env);
}
}