From bf63d5880f55bc9298a5b586777b71287d248976 Mon Sep 17 00:00:00 2001 From: Enrico Lumetti Date: Sun, 28 Feb 2021 15:31:59 +0100 Subject: [PATCH] Add Viewport up/down scroll and some misc improvements --- src/canvas.rs | 48 ++++++++++++++++++---- src/main.rs | 62 ++++++++++++++++++++++------- src/tool.rs | 41 ++++++++++++++----- src/widget/canvas.rs | 95 +++++++++++++++++++++++++++++++++++++------- 4 files changed, 197 insertions(+), 49 deletions(-) diff --git a/src/canvas.rs b/src/canvas.rs index 0c9ea65..1559f39 100644 --- a/src/canvas.rs +++ b/src/canvas.rs @@ -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, + elements: Vector, + 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) -> 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 { + &self.elements + } + /// Find all CanvasElement that intersect with rect pub fn find_intersections(&self, rect: druid::Rect) -> Vec { let mut found_elements = Vec::::new(); @@ -157,6 +185,10 @@ impl Canvas { found_elements } + + pub fn content_size(&self) -> druid::Size { + self.content_size + } } impl Serialize for Path { diff --git a/src/main.rs b/src/main.rs index bc5a27d..dde2bd7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . +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, current_tool: usize, + #[data(same_fn = "PartialEq::eq")] + current_file_path: Option, } fn build_ui() -> impl Widget { + 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 { 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 { .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 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 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 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; diff --git a/src/tool.rs b/src/tool.rs index d22870e..7f3cedd 100644 --- a/src/tool.rs +++ b/src/tool.rs @@ -15,7 +15,7 @@ // along with this program. If not, see . 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, + }); + } } }); } diff --git a/src/widget/canvas.rs b/src/widget/canvas.rs index 67b06e0..083d8dc 100644 --- a/src/widget/canvas.rs +++ b/src/widget/canvas.rs @@ -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 = 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 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 for CanvasWidget { // ctx.request_paint_rect(e.bounding_box()); // } //} else { + ctx.request_paint(); //} } @@ -128,15 +181,27 @@ impl Widget 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); } }