diff --git a/README.md b/README.md index 3d10baa..c8e7118 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,8 @@ This binds **Shift+Print** to `kirie capture`, so your desktop's own screenshot `kirie capture` freezes every screen. Drag to cut out a region, or click to take the window under the pointer (on GNOME with the extension, COSMIC, KDE Plasma, sway and Hyprland). **Take this screen** in the hint at the bottom takes the whole screen; where Kirie cannot see -windows, a click does. +windows, a click does. With several screens, **Take all screens** takes them together, as Ctrl+A +does. A loupe beside the pointer shows the pixels around it, magnified, with its position and color, so edges land on the exact pixel. Then mark it up with the toolbar under the selection. diff --git a/crates/kirie-annotate/src/tools.rs b/crates/kirie-annotate/src/tools.rs index d6134cb..dadbbf6 100644 --- a/crates/kirie-annotate/src/tools.rs +++ b/crates/kirie-annotate/src/tools.rs @@ -332,6 +332,11 @@ impl Draft { /// The mark as it would be if released now, to show while drawing. pub fn preview(&self) -> Option { match self { + Draft::Span { tool, start, end } + if *tool != Tool::Bubble && start.distance(*end) < MIN_DRAG => + { + None + } Draft::Span { tool, start, end } => span_kind(*tool, *start, *end), Draft::Stroke { tool, points } => match tool { Tool::Highlighter => Some(Kind::Highlighter { @@ -369,7 +374,6 @@ impl Draft { /// The edit the draft makes when released, if it made anything. pub fn finish(self, paint: Paint) -> Option { match self { - Draft::Span { start, end, .. } if start.distance(end) < MIN_DRAG => None, Draft::Marquee { .. } | Draft::Span { tool: Tool::Bubble, .. @@ -533,6 +537,31 @@ mod tests { ); } + #[test] + fn a_press_without_a_drag_shows_nothing_until_it_would_make_something() { + for tool in [Tool::Arrow, Tool::Line, Tool::Rectangle, Tool::Blur] { + let Press::Draft(draft) = press( + tool, + Point::ORIGIN, + &doc(), + Paint::default(), + 4.0, + &[], + false, + ) else { + panic!("{tool:?} started no draft"); + }; + let pressed = draft.drag(Point::new(1.0, 1.0), false); + assert_eq!(pressed.preview(), None, "{tool:?}"); + assert!( + pressed + .drag(Point::new(40.0, 30.0), false) + .preview() + .is_some() + ); + } + } + #[test] fn shift_snaps() { let draft = Draft::Span { diff --git a/crates/kirie-ui/src/checker.rs b/crates/kirie-ui/src/checker.rs new file mode 100644 index 0000000..163c62e --- /dev/null +++ b/crates/kirie-ui/src/checker.rs @@ -0,0 +1,185 @@ +//! Light and dark squares, which show through what is translucent. + +use iced::widget::canvas::{self, Frame, Geometry, Path}; +use iced::{Color, Point, Rectangle, Renderer, Size}; + +const LIGHT: Color = crate::rgb(0xf2, 0xf2, 0xf2); +const DARK: Color = crate::rgb(0xc8, 0xc8, 0xc8); +const SEGMENTS: u16 = 48; + +/// Fills `area`, which spans `size` from the origin, with squares `cell` wide. +pub fn rectangle(frame: &mut Frame, area: &Path, size: Size, cell: f32) { + frame.fill(area, LIGHT); + let bounds = Rectangle::new(Point::ORIGIN, size); + let dark = Path::new(|path| { + for square in dark_squares(bounds, cell) { + path.rectangle(square.position(), square.size()); + } + }); + frame.fill(&dark, DARK); +} + +/// Fills the disc at `center` with squares `cell` wide. +pub fn disc(frame: &mut Frame, center: Point, radius: f32, cell: f32) { + frame.fill(&Path::circle(center, radius), LIGHT); + let outline: Vec = (0..SEGMENTS) + .map(|step| { + let angle = f32::from(step) / f32::from(SEGMENTS) * std::f32::consts::TAU; + Point::new( + center.x + radius * angle.cos(), + center.y + radius * angle.sin(), + ) + }) + .collect(); + let bounds = Rectangle::new( + Point::new(center.x - radius, center.y - radius), + Size::new(2.0 * radius, 2.0 * radius), + ); + let dark = Path::new(|path| { + for square in dark_squares(bounds, cell) { + let piece = clip(&outline, square); + if let Some((&first, rest)) = piece.split_first() { + path.move_to(first); + for &point in rest { + path.line_to(point); + } + path.close(); + } + } + }); + frame.fill(&dark, DARK); +} + +/// A disc of squares filling its bounds, to lay under a translucent dot. +#[derive(Debug, Clone, Copy)] +pub struct Disc; + +impl canvas::Program for Disc { + type State = (); + + fn draw( + &self, + (): &(), + renderer: &Renderer, + _: &iced::Theme, + bounds: Rectangle, + _: iced::mouse::Cursor, + ) -> Vec { + let mut frame = Frame::new(renderer, bounds.size()); + let side = bounds.width.min(bounds.height); + let center = frame.center(); + disc(&mut frame, center, side / 2.0 - 0.5, side / 4.0); + vec![frame.into_geometry()] + } +} + +/// Every other square of a grid of `cell` over `bounds`, cut to it. +fn dark_squares(bounds: Rectangle, cell: f32) -> impl Iterator { + let right = bounds.x + bounds.width; + let bottom = bounds.y + bounds.height; + let steps = move |from: f32, to: f32| { + std::iter::successors(Some(from), move |at| Some(at + cell)) + .take_while(move |at| *at < to) + .enumerate() + }; + steps(bounds.x, right).flat_map(move |(column, x)| { + steps(bounds.y, bottom) + .filter(move |(row, _)| (column + row).is_multiple_of(2)) + .map(move |(_, y)| { + Rectangle::new( + Point::new(x, y), + Size::new(cell.min(right - x), cell.min(bottom - y)), + ) + }) + }) +} + +#[derive(Clone, Copy)] +enum Axis { + X, + Y, +} + +/// The part of the convex `polygon` inside `rect`. +fn clip(polygon: &[Point], rect: Rectangle) -> Vec { + [ + (Axis::X, rect.x, true), + (Axis::X, rect.x + rect.width, false), + (Axis::Y, rect.y, true), + (Axis::Y, rect.y + rect.height, false), + ] + .into_iter() + .fold(polygon.to_vec(), |points, (axis, bound, above)| { + clip_to(&points, axis, bound, above) + }) +} + +/// The part of `points` on one side of the line where `axis` is `bound`. +fn clip_to(points: &[Point], axis: Axis, bound: f32, above: bool) -> Vec { + let coordinate = |point: Point| match axis { + Axis::X => point.x, + Axis::Y => point.y, + }; + let inside = |point: Point| { + if above { + coordinate(point) >= bound + } else { + coordinate(point) <= bound + } + }; + let crossing = |from: Point, to: Point| { + let t = (bound - coordinate(from)) / (coordinate(to) - coordinate(from)); + Point::new(from.x + t * (to.x - from.x), from.y + t * (to.y - from.y)) + }; + let previous = points.iter().cycle().skip(points.len().saturating_sub(1)); + points + .iter() + .zip(previous) + .flat_map( + |(¤t, &previous)| match (inside(previous), inside(current)) { + (true, true) => vec![current], + (true, false) => vec![crossing(previous, current)], + (false, true) => vec![crossing(previous, current), current], + (false, false) => vec![], + }, + ) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clipping_keeps_what_is_inside() { + let square = [ + Point::new(0.0, 0.0), + Point::new(4.0, 0.0), + Point::new(4.0, 4.0), + Point::new(0.0, 4.0), + ]; + let half = clip(&square, Rectangle::new(Point::ORIGIN, Size::new(2.0, 10.0))); + let xs: Vec = half.iter().map(|point| point.x).collect(); + assert!(xs.iter().all(|&x| (0.0..=2.0).contains(&x))); + assert_eq!(half.len(), 4); + assert!( + clip( + &square, + Rectangle::new(Point::new(5.0, 5.0), Size::new(1.0, 1.0)) + ) + .is_empty() + ); + } + + #[test] + fn squares_alternate_and_stay_inside() { + let bounds = Rectangle::new(Point::ORIGIN, Size::new(10.0, 10.0)); + let squares: Vec = dark_squares(bounds, 4.0).collect(); + assert_eq!(squares.len(), 5); + assert!( + squares.iter().all(|square| { + square.x + square.width <= 10.0 && square.y + square.height <= 10.0 + }) + ); + } +} diff --git a/crates/kirie-ui/src/lib.rs b/crates/kirie-ui/src/lib.rs index e4996b0..ea7428e 100644 --- a/crates/kirie-ui/src/lib.rs +++ b/crates/kirie-ui/src/lib.rs @@ -1,6 +1,7 @@ //! Kirie's design language: a calm, flat dark or light surface with one vermilion accent, on a //! 4 px grid with soft radii. The overlay and the editor both draw from these tokens. +pub mod checker; pub mod icon; pub mod widget; diff --git a/crates/kirie-ui/src/widget.rs b/crates/kirie-ui/src/widget.rs index 2b4b55b..4fc9917 100644 --- a/crates/kirie-ui/src/widget.rs +++ b/crates/kirie-ui/src/widget.rs @@ -2,9 +2,10 @@ //! they sit on. use iced::overlay::menu; -use iced::widget::{button, container, pick_list, row, slider, svg, text, tooltip}; +use iced::widget::{Canvas, button, container, pick_list, row, slider, stack, svg, text, tooltip}; use iced::{Background, Border, Color, Element, Length, Shadow, Vector}; +use crate::checker; use crate::icon::Icon; use crate::{Palette, radius, space}; @@ -186,19 +187,7 @@ pub fn swatch<'a, Message: Clone + 'a>( palette: Palette, on_press: Message, ) -> Element<'a, Message> { - let dot = container(text("")) - .width(18) - .height(18) - .style(move |_| container::Style { - background: Some(Background::Color(color)), - border: Border { - color: Color::WHITE.scale_alpha(0.35), - width: 1.0, - radius: radius::PILL.into(), - }, - ..container::Style::default() - }); - button(container(dot).center(Length::Fill)) + button(container(color_dot(color, 18.0)).center(Length::Fill)) .width(28) .height(28) .padding(0) @@ -223,6 +212,27 @@ pub fn swatch<'a, Message: Clone + 'a>( .into() } +/// A round dot of `color`, `side` wide, over light and dark squares when it is translucent. +pub fn color_dot<'a, Message: 'a>(color: Color, side: f32) -> Element<'a, Message> { + let dot = container(text("")) + .width(side) + .height(side) + .style(move |_| container::Style { + background: Some(Background::Color(color)), + border: Border { + color: Color::WHITE.scale_alpha(0.35), + width: 1.0, + radius: radius::PILL.into(), + }, + ..container::Style::default() + }); + if color.a < 1.0 { + stack![Canvas::new(checker::Disc).width(side).height(side), dot].into() + } else { + dot.into() + } +} + /// A round button the size of a swatch, with an icon. pub fn swatch_button<'a, Message: Clone + 'a>( icon: Icon, diff --git a/crates/kirie/src/annotate/picker.rs b/crates/kirie/src/annotate/picker.rs index 2b510da..6d1f314 100644 --- a/crates/kirie/src/annotate/picker.rs +++ b/crates/kirie/src/annotate/picker.rs @@ -3,11 +3,12 @@ use iced::mouse::{self, Interaction}; use iced::widget::canvas::{self, Action, Frame, Geometry, Path, Stroke, gradient}; -use iced::widget::{column, container, row, text, text_input}; +use iced::widget::{column, row, text, text_input}; use iced::{Alignment, Background, Border, Color, Element, Length, Point, Rectangle, Renderer}; use kirie_annotate::{Rgba, StyleId}; +use kirie_ui::checker; use kirie_ui::icon::Icon; -use kirie_ui::widget::{icon_button, pill}; +use kirie_ui::widget::{color_dot, icon_button, pill}; use kirie_ui::{Palette, radius, space}; use crate::annotate::paint::color_of; @@ -232,18 +233,7 @@ pub fn view(picker: &Picker, palette: Palette) -> Element<'_, Event> { Target::Change(Slot::Default(_)) => "Change this color", Target::Change(Slot::Custom(_)) => "Change your color", }; - let preview = container(text("")).width(26).height(26).style({ - let color = color_of(picker.color()); - move |_| container::Style { - background: Some(Background::Color(color)), - border: Border { - color: Color::WHITE.scale_alpha(0.35), - width: 1.0, - radius: radius::PILL.into(), - }, - ..container::Style::default() - } - }); + let preview = color_dot(color_of(picker.color()), 26.0); let hex = text_input("#rrggbb", &picker.hex) .on_input(Event::Hex) .on_submit(Event::Apply) @@ -444,7 +434,7 @@ impl canvas::Program for Field { ring(&mut frame, &knob(x, size.height)); } Area::Alpha(alpha) => { - checker(&mut frame, size); + checker::rectangle(&mut frame, &area, size, 7.0); let solid = color_of(self.hsv.to_rgba()); let fade = gradient::Linear::new(Point::ORIGIN, Point::new(size.width, 0.0)) .add_stop(0.0, solid.scale_alpha(0.0)) @@ -480,32 +470,6 @@ fn knob(x: f32, height: f32) -> Path { ) } -/// Light and dark squares, which show through what is translucent. -fn checker(frame: &mut Frame, size: iced::Size) { - const CELL: f32 = 7.0; - frame.fill( - &Path::rounded_rectangle(Point::ORIGIN, size, radius::CONTROL.into()), - Color::from_rgb8(0xf2, 0xf2, 0xf2), - ); - let dark = Path::new(|path| { - let mut x = 0.0; - let mut column = 0u32; - while x < size.width { - let mut y = if column.is_multiple_of(2) { 0.0 } else { CELL }; - while y < size.height { - path.rectangle( - Point::new(x, y), - iced::Size::new(CELL.min(size.width - x), CELL.min(size.height - y)), - ); - y += 2.0 * CELL; - } - x += CELL; - column += 1; - } - }); - frame.fill(&dark, Color::from_rgb8(0xc8, 0xc8, 0xc8)); -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/kirie/src/editor/canvas.rs b/crates/kirie/src/editor/canvas.rs index 5ae0f2d..7e8c7bd 100644 --- a/crates/kirie/src/editor/canvas.rs +++ b/crates/kirie/src/editor/canvas.rs @@ -153,8 +153,10 @@ impl canvas::Program for Board<'_> { let clip = editor .crop() .map_or(kept, |_| Rectangle::with_size(bounds.size())); - let picked = frame.with_clip(clip, |frame| { - self.draw_marks(frame, image, transform, layer) + let picked = within(clip, bounds.size()).map_or_else(Vec::new, |clip| { + frame.with_clip(clip, |frame| { + self.draw_marks(frame, image, transform, layer) + }) }); if layer.is_some() { return vec![frame.into_geometry()]; @@ -344,11 +346,13 @@ impl canvas::Program for Backdrop<'_> { }; let kept = to_rectangle(transform.transform_rect_bbox(shown)); // Without a frame the picture stands alone: anything drawn around it would look like - // part of it, though it is never saved. - if shown != canvas { - let on_screen = area + // part of it, though it is never saved. What fills the frame shows through a + // see-through picture, as in the saved image. + if shown != canvas || editor.see_through { + let filled = under(area, kept); + let on_screen = filled .intersection(&Rectangle::with_size(bounds.size())) - .unwrap_or(area); + .unwrap_or(filled); match document.frame.background { Some(color) => { frame.fill_rectangle(on_screen.position(), on_screen.size(), color_of(color)); @@ -370,16 +374,45 @@ impl canvas::Program for Backdrop<'_> { } else { iced::widget::image::FilterMethod::Linear }; - frame.with_clip(kept, |frame| { - frame.draw_image( - picture, - canvas::Image::new(handle.clone()).filter_method(filter), - ); - }); + if let Some(kept) = within(kept, bounds.size()) { + frame.with_clip(kept, |frame| { + frame.draw_image( + picture, + canvas::Image::new(handle.clone()).filter_method(filter), + ); + }); + } vec![frame.into_geometry()] } } +/// `area` less a pixel on each side where `picture` reaches its edge: there the picture's own +/// edge ends what shows, else the fill's soft edge peeks out past it as a hairline the saved +/// image does not have. +fn under(area: Rectangle, picture: Rectangle) -> Rectangle { + let meets = |edge: f32, picture: f32| { + if (edge - picture).abs() < 0.5 { + 1.0 + } else { + 0.0 + } + }; + let left = area.x + meets(area.x, picture.x); + let top = area.y + meets(area.y, picture.y); + let right = area.x + area.width - meets(area.x + area.width, picture.x + picture.width); + let bottom = area.y + area.height - meets(area.y + area.height, picture.y + picture.height); + Rectangle::new( + Point::new(left, top), + Size::new((right - left).max(0.0), (bottom - top).max(0.0)), + ) +} + +/// The part of `clip` on a canvas of `size`: a clipped frame replaces the canvas bounds as its +/// clip rather than narrowing them, so an unbounded one would draw over the panels around it. +fn within(clip: Rectangle, size: Size) -> Option { + clip.intersection(&Rectangle::with_size(size)) +} + fn scale(editor: &Editor, canvas: Size) -> f32 { editor.viewport.scale(editor.content(), canvas) } @@ -488,3 +521,22 @@ fn transform_point(transform: kurbo::Affine, point: kurbo::Point) -> Point { let point = transform * point; Point::new(point.x as f32, point.y as f32) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_fill_stops_short_of_the_edges_the_picture_reaches() { + let picture = Rectangle::new(Point::new(10.25, 20.0), Size::new(100.0, 50.0)); + assert_eq!( + under(picture, picture), + Rectangle::new(Point::new(11.25, 21.0), Size::new(98.0, 48.0)) + ); + let grown_left = Rectangle::new(Point::new(0.0, 20.0), Size::new(110.25, 50.25)); + assert_eq!( + under(grown_left, picture), + Rectangle::new(Point::new(0.0, 21.0), Size::new(109.25, 48.25)) + ); + } +} diff --git a/crates/kirie/src/editor/mod.rs b/crates/kirie/src/editor/mod.rs index f09f3dd..e180560 100644 --- a/crates/kirie/src/editor/mod.rs +++ b/crates/kirie/src/editor/mod.rs @@ -138,6 +138,9 @@ pub struct Editor { placement: window::Placement, palette: Palette, image: Option<(RgbaImage, image::Handle)>, + /// Some of the image lets what is under it show, such as the gaps between screens of + /// different sizes. + see_through: bool, path: Option, annotator: Annotator, /// The document as last opened, saved or copied, to tell unsaved changes. @@ -200,6 +203,7 @@ impl Editor { placement, palette: Palette::DARK, image: None, + see_through: false, path: None, annotator: Annotator::new(blank.clone(), paint, swatches), kept: blank, @@ -263,6 +267,7 @@ impl Editor { self.kept = document.clone(); self.annotator.history = History::new(document); self.annotator.follow_style(drawing.style); + self.see_through = loaded.image.pixels().any(|pixel| pixel[3] < u8::MAX); self.image = Some((loaded.image, handle)); self.path = loaded.path; self.viewport = Viewport::fitted(); diff --git a/crates/kirie/src/overlay/region.rs b/crates/kirie/src/overlay/region.rs index 4d82517..6d3c23f 100644 --- a/crates/kirie/src/overlay/region.rs +++ b/crates/kirie/src/overlay/region.rs @@ -10,7 +10,7 @@ use crate::annotate::selection::{Hit, Release, Selection}; const FILE: &str = "region.ron"; /// Picking the region by keys and buttons. -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, PartialEq)] pub enum Event { /// Moves the region by whole logical pixels. Nudge(Vector), diff --git a/crates/kirie/src/overlay/view.rs b/crates/kirie/src/overlay/view.rs index 921b96c..659fa57 100644 --- a/crates/kirie/src/overlay/view.rs +++ b/crates/kirie/src/overlay/view.rs @@ -117,16 +117,23 @@ impl Overlay { "M to show the magnifier" }; let words = format!("Drag to cut a region · {click} · {magnifier} · Esc to cancel"); - let mut content = row![text(words).size(13)] - .spacing(space::M) - .align_y(iced::Alignment::Center); - if !self.windows.is_empty() { - content = content.push(secondary_button( - "Take this screen", - self.palette, - Message::Region(region::Event::SelectScreen(screen)), - )); - } + let buttons = whole_screens( + screen, + !self.windows.is_empty(), + self.screens.len() > 1 && !self.covers_one_of_many(), + ); + let content = buttons.into_iter().fold( + row![text(words).size(13)] + .spacing(space::M) + .align_y(iced::Alignment::Center), + |content, (label, event)| { + content.push(secondary_button( + label, + self.palette, + Message::Region(event), + )) + }, + ); let mut card = column![content].spacing(space::XS); if self.covers_one_of_many() { card = card.push( @@ -459,6 +466,19 @@ impl Overlay { } } +/// The buttons in the hint that take whole screens: `screen` where a click takes a window, and +/// all of them where every screen shows. +fn whole_screens( + screen: usize, + clicks_take_windows: bool, + every_screen_shows: bool, +) -> Vec<(&'static str, region::Event)> { + let this = + clicks_take_windows.then_some(("Take this screen", region::Event::SelectScreen(screen))); + let all = every_screen_shows.then_some(("Take all screens", region::Event::SelectAll)); + this.into_iter().chain(all).collect() +} + /// A key cap that says Enter does what the button before it does. fn enter_key<'a>(palette: kirie_ui::Palette) -> Element<'a, Message> { container(text("Enter").size(11).color(palette.muted)) @@ -530,6 +550,26 @@ mod tests { const SIZE: Size = Size::new(400.0, 90.0); + #[test] + fn the_hint_offers_this_screen_and_every_screen_when_a_click_cannot() { + let labels = |clicks_take_windows, every_screen_shows| { + whole_screens(1, clicks_take_windows, every_screen_shows) + .into_iter() + .map(|(label, _)| label) + .collect::>() + }; + assert!(labels(false, false).is_empty()); + assert_eq!(labels(true, false), ["Take this screen"]); + assert_eq!(labels(false, true), ["Take all screens"]); + assert_eq!( + whole_screens(1, true, true), + [ + ("Take this screen", region::Event::SelectScreen(1)), + ("Take all screens", region::Event::SelectAll), + ] + ); + } + fn screens() -> [Rectangle; 2] { [ Rectangle::new(Point::ORIGIN, Size::new(1920.0, 1080.0)),