diff --git a/src/action.rs b/src/action.rs index 7dcec4d..47bd8b5 100644 --- a/src/action.rs +++ b/src/action.rs @@ -50,6 +50,10 @@ pub enum Action { ToggleGridLines, /// Turns snapping to other nodes' sides and middles on or off. ToggleSnapLines, + /// Opens the color picker on the canvas's background color. + EditCanvasBackground, + /// Sets the canvas's background color, made opaque. + SetCanvasBackground(Color), /// Moves the selected bend, or else everything selected, right and down /// by these distances, in points; see [`crate::document::move_items`]. MoveBy(f64, f64), diff --git a/src/canvas/grid/mod.rs b/src/canvas/grid/mod.rs index 81dfb51..c5b46e7 100644 --- a/src/canvas/grid/mod.rs +++ b/src/canvas/grid/mod.rs @@ -1,7 +1,7 @@ //! The canvas's grid lines, spaced to suit the zoom. use egui::emath::TSTransform; -use egui::{Color32, Mesh, Painter, Rangef, Rect}; +use egui::{Color32, Mesh, Painter, Rangef, Rect, Rgba}; use super::paint::pixel; @@ -16,13 +16,14 @@ const MIN_GAP: f32 = 5.0; const FAINT_GAP: f32 = 10.0; /// ...and lines this far apart, or more, as dark as [`DARK`]. const DARK_GAP: f32 = 100.0; -/// How dark lines are drawn, from 0 (white) to 1 (black). +/// How dark lines are drawn, from 0 (the background) to 1 (black), or how +/// light on a dark background. const FAINT: f32 = 0.065; const DARK: f32 = 0.17; /// Paints grid lines across the canvas at `rect`, which `to_screen` takes -/// graph coordinates to. They're a pixel wide at any zoom. -pub fn paint(painter: &Painter, rect: Rect, to_screen: TSTransform) { +/// graph coordinates to, over `background`. They're a pixel wide at any zoom. +pub fn paint(painter: &Painter, rect: Rect, to_screen: TSTransform, background: Color32) { let pixel = |at: f32| pixel(at, painter.pixels_per_point()); let (origin, zoom) = (to_screen.translation, to_screen.scaling); let across = lines(rect.x_range(), origin.x, zoom) @@ -32,19 +33,42 @@ pub fn paint(painter: &Painter, rect: Rect, to_screen: TSTransform) { .into_iter() .map(|(y, darkness)| (darkness, Rect::from_x_y_ranges(rect.x_range(), pixel(y)))); let mut lines: Vec<_> = across.chain(down).collect(); - // The darker over the fainter, where they cross. + // The stronger over the fainter, where they cross. lines.sort_by(|(a, _), (b, _)| a.total_cmp(b)); + let ink = ink(background); let mut mesh = Mesh::default(); for (darkness, line) in lines { - let gray = (255.0 * (1.0 - darkness)).round() as u8; + let color = mix(background, ink, darkness); // Those just fading in show nothing yet. - if gray < 255 { - mesh.add_colored_rect(line, Color32::from_gray(gray)); + if color != background { + mesh.add_colored_rect(line, color); } } painter.add(mesh); } +/// What lines are drawn toward from `background`: black, or white if that +/// stands out more, as WCAG measures contrast. +fn ink(background: Color32) -> Color32 { + let linear = Rgba::from(background); + let luminance = 0.2126 * linear.r() + 0.7152 * linear.g() + 0.0722 * linear.b(); + // Where black and white stand out as much. + if luminance > 0.179 { + Color32::BLACK + } else { + Color32::WHITE + } +} + +/// The opaque color `amount` of the way from `from` to `to`. +fn mix(from: Color32, to: Color32, amount: f32) -> Color32 { + let channel = |from: u8, to: u8| { + (f32::from(from) * (1.0 - amount) + f32::from(to) * amount).round() as u8 + }; + let [r, g, b] = [0, 1, 2].map(|i| channel(from[i], to[i])); + Color32::from_rgb(r, g, b) +} + /// Where lines cross `range` on screen along an axis, on which graph point 0 /// is at `origin` and `zoom` screen points make a graph point, with how dark /// each is drawn: the darker, the wider the spacing it's a multiple of shows. diff --git a/src/canvas/grid/tests.rs b/src/canvas/grid/tests.rs index 9500bf6..8740c32 100644 --- a/src/canvas/grid/tests.rs +++ b/src/canvas/grid/tests.rs @@ -50,3 +50,35 @@ fn rounder_lines_are_darker() { assert_eq!(dark(100.0), dark(200.0)); assert_eq!(dark(100.0), DARK); } + +#[test] +fn lines_on_white_are_grays_as_dark_as_they_are_drawn() { + for darkness in [FAINT, 0.1, DARK] { + let gray = (255.0 * (1.0 - darkness)).round() as u8; + let line = mix(Color32::WHITE, ink(Color32::WHITE), darkness); + assert_eq!(line, Color32::from_gray(gray), "{darkness}"); + } +} + +#[test] +fn lines_go_toward_black_or_white_whichever_stands_out_more() { + for (background, ink_color) in [ + (Color32::WHITE, Color32::BLACK), + (Color32::from_rgb(0xFF, 0xFF, 0xCC), Color32::BLACK), + // WCAG's crossover falls between these grays. + (Color32::from_gray(0x76), Color32::BLACK), + (Color32::from_gray(0x75), Color32::WHITE), + (Color32::from_rgb(0x00, 0x00, 0x99), Color32::WHITE), + (Color32::BLACK, Color32::WHITE), + ] { + assert_eq!(ink(background), ink_color, "{background:?}"); + } +} + +#[test] +fn lines_on_dark_backgrounds_are_as_much_lighter() { + let navy = Color32::from_rgb(0x00, 0x00, 0x66); + let line = mix(navy, ink(navy), DARK); + // 17% of the way to white. + assert_eq!(line, Color32::from_rgb(0x2B, 0x2B, 0x80)); +} diff --git a/src/canvas/mod.rs b/src/canvas/mod.rs index f264109..6201a94 100644 --- a/src/canvas/mod.rs +++ b/src/canvas/mod.rs @@ -36,8 +36,6 @@ pub use shown::Outline; use shown::{Anchor, EdgeLook, Shown, egui_pos, yed_point}; use textures::Textures; -/// White like paper, even in the dark theme. -const BACKGROUND: Color32 = Color32::WHITE; /// New nodes' fill, CSS's `lightblue`. const NEW_NODE_FILL: yed::Color = yed::Color::rgb(0xAD, 0xD8, 0xE6); @@ -103,7 +101,7 @@ const MAX_TEXT_SCALE: f32 = 1.25; const EDITOR_MARGIN: Margin = Margin::symmetric(4, 2); const EDITOR_MIN_WIDTH: f32 = 60.0; -/// What the View menu turns on for the canvas. +/// What the View menu sets for the canvas. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct Options { @@ -111,6 +109,9 @@ pub struct Options { /// Whether drags snap onto the sides and middles of other nodes, with /// guides showing what lines up, unless Alt is held. pub snap_lines: bool, + /// Behind the drawing, always opaque. + #[serde(with = "opaque_color")] + pub background: yed::Color, } impl Default for Options { @@ -118,10 +119,29 @@ impl Default for Options { Options { grid_lines: false, snap_lines: true, + // Like paper, even in the dark theme. + background: yed::Color::WHITE, } } } +/// A color as `#RRGGBB`, read as opaque, and as the default background if +/// it can't be read. +mod opaque_color { + use graphml::yed::Color; + use serde::{Deserialize, Deserializer, Serializer}; + + pub fn serialize(color: &Color, serializer: S) -> Result { + serializer.collect_str(color) + } + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let color = Color::from_hex(&String::deserialize(deserializer)?); + let default = super::Options::default().background; + Ok(color.map_or(default, |color| Color { a: 255, ..color })) + } +} + /// The drawing canvas, which shows the graph zoomed and panned. #[derive(Default)] pub struct Canvas { @@ -580,7 +600,7 @@ impl Canvas { let id = Id::unique("label_editor"); let output = ui .scope_builder(UiBuilder::new().max_rect(rect), |ui| { - // White like the canvas, even in the dark theme. + // A white field with dark text, whatever the theme or canvas. ui.style_mut().visuals = Visuals::light(); text_field::label_edit(&mut editor.text) .id(id) diff --git a/src/canvas/paint.rs b/src/canvas/paint.rs index de6429f..c16d626 100644 --- a/src/canvas/paint.rs +++ b/src/canvas/paint.rs @@ -24,9 +24,9 @@ use crate::svg_image::SvgImage; use super::shown::{Anchor, EdgeLook, Outline, Shown, egui_rect, shape}; use super::textures::Textures; use super::{ - ARROWHEAD, BACKGROUND, Canvas, DIMENSION_OFFSET, EdgeDrag, EdgePart, GUIDE, GUIDE_OVERHANG, - HALO, HANDLE_SIZE, LABEL_PADDING, MAX_TEXT_PIXELS, Owner, Preview, SELECTION, - SELECTION_BOX_FILL, SELECTION_GAP, edge, grid, + ARROWHEAD, Canvas, DIMENSION_OFFSET, EdgeDrag, EdgePart, GUIDE, GUIDE_OVERHANG, HALO, + HANDLE_SIZE, LABEL_PADDING, MAX_TEXT_PIXELS, Owner, Preview, SELECTION, SELECTION_BOX_FILL, + SELECTION_GAP, edge, grid, }; impl Canvas { @@ -48,9 +48,10 @@ impl Canvas { boxed, } = preview; let (scene, painter) = (shown.scene, shown.painter); - painter.rect_filled(rect, 0.0, BACKGROUND); + let background = color32(self.options.background); + painter.rect_filled(rect, 0.0, background); if self.options.grid_lines { - grid::paint(painter, rect, shown.to_screen); + grid::paint(painter, rect, shown.to_screen, background); } let editing = self.editor.as_ref().map(|editor| &editor.label); // The label being edited shows in its editor instead. diff --git a/src/canvas/tests.rs b/src/canvas/tests.rs index b455105..f6c3d4c 100644 --- a/src/canvas/tests.rs +++ b/src/canvas/tests.rs @@ -14,6 +14,8 @@ use crate::testing::{self, CTRL, button, middle_button}; /// The light blue new boxes get. const BOX_FILL: Color32 = Color32::from_rgb(0xAD, 0xD8, 0xE6); +/// The canvas's background, unless the options set another. +const BACKGROUND: Color32 = Color32::WHITE; /// Drives a canvas filling an 800×600 window, one frame at a time. struct Harness { @@ -2368,6 +2370,22 @@ fn grid_lines_space_out_and_fill_in_with_the_zoom() { assert_eq!(first_grid_lines(&mut harness), [0.0, 20.0, 40.0]); } +#[test] +fn the_canvas_is_painted_in_its_background_with_lines_that_stand_out() { + let mut harness = Harness::new(Tool::Cursor); + let canvas = filled_rects(&harness.frame(vec![]), BACKGROUND)[0]; + harness.options.background = yed::Color::rgb(0x33, 0x33, 0x33); + harness.options.grid_lines = true; + let shapes = harness.frame(vec![]); + assert_eq!(filled_rects(&shapes, Color32::from_gray(0x33)), [canvas]); + assert_eq!(filled_rects(&shapes, BACKGROUND), []); + let lines = grid_lines(&shapes); + assert!(!lines.is_empty()); + for (line, color) in lines { + assert!(color.r() > 0x33, "{line:?} is {color:?}"); + } +} + #[test] fn labels_keep_their_layout_while_the_zoom_changes() { let mut harness = Harness::new(Tool::Cursor); diff --git a/src/color_picker/mod.rs b/src/color_picker/mod.rs index 29a7db2..5148ac0 100644 --- a/src/color_picker/mod.rs +++ b/src/color_picker/mod.rs @@ -1,7 +1,7 @@ use egui::color_picker; use egui::{ - Color32, Context, DragValue, Key, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, - TextEdit, Ui, Vec2, WidgetInfo, vec2, + Atom, Color32, Context, DragValue, Key, Painter, Rect, Response, Role, Sense, Stroke, + StrokeKind, TextEdit, TextStyle, Ui, Vec2, WidgetInfo, vec2, }; use graphml::yed::Color; @@ -40,6 +40,8 @@ struct Dialog { title: String, /// Whether "No color" is offered. optional: bool, + /// Whether the color can't be see-through, so has no alpha field. + opaque: bool, no_color: bool, color: Color, hex: String, @@ -69,19 +71,41 @@ impl ColorPicker { title: impl Into, color: Option, optional: bool, + ) { + self.open_dialog(target, title.into(), color, optional, false); + } + + /// Opens the dialog with `color` picked, unless it's open already, for a + /// color that can't be "No color" or see-through. + pub fn open_opaque(&mut self, target: T, title: impl Into, color: Color) { + self.open_dialog(target, title.into(), Some(color), false, true); + } + + fn open_dialog( + &mut self, + target: T, + title: String, + color: Option, + optional: bool, + opaque: bool, ) { if self.is_open() { return; } - self.dialog = Some(Dialog { + let mut dialog = Dialog { target, - title: title.into(), + title, optional, + opaque, no_color: optional && color.is_none(), - color: color.unwrap_or(Color::WHITE), + color: Color::WHITE, hex: String::new(), focus_hex: true, - }); + }; + if let Some(color) = color { + dialog.pick(color); + } + self.dialog = Some(dialog); } /// Closes the dialog without picking anything. @@ -115,8 +139,17 @@ impl Dialog { (!self.no_color).then_some(self.color) } + /// `color` as the dialog would pick it: opaque if its color must be. + fn pickable(&self, color: Color) -> Color { + if self.opaque { + Color { a: 255, ..color } + } else { + color + } + } + fn pick(&mut self, picked: Color) { - self.color = picked; + self.color = self.pickable(picked); self.no_color = false; } @@ -139,10 +172,17 @@ impl Dialog { self.hex_field(ui); ui.add_enabled_ui(!self.no_color, |ui| self.channel_fields(ui)); ui.label("Recent colors"); - if recent.is_empty() { + // As they'd be picked, once each. + let mut shown = Vec::new(); + for color in recent.iter().map(|&color| self.pickable(color)) { + if !shown.contains(&color) { + shown.push(color); + } + } + if shown.is_empty() { ui.weak("None yet"); } - ok |= self.swatches(ui, recent, RECENT / 2); + ok |= self.swatches(ui, &shown, RECENT / 2); }); }); ok |= dialog::ok_cancel(ui, None); @@ -211,12 +251,15 @@ impl Dialog { }); } - /// Shows a field each for the red, green, blue and alpha of the color. + /// Shows a field each for the red, green, blue and, unless it's opaque, + /// alpha of the color. fn channel_fields(&mut self, ui: &mut Ui) { let size = vec2(field_width(ui), ui.spacing().interact_size.y); + let shown = if self.opaque { 3 } else { 4 }; let Color { r, g, b, a } = &mut self.color; ui.horizontal(|ui| { - for (prefix, value) in [("R ", r), ("G ", g), ("B ", b), ("A ", a)] { + let channels = [("R ", r), ("G ", g), ("B ", b), ("A ", a)]; + for (prefix, value) in channels.into_iter().take(shown) { ui.add( DragValue::new(value) .prefix(prefix) @@ -262,6 +305,15 @@ fn swatch_button(ui: &mut Ui, color: Color, current: bool) -> Response { response.on_hover_text(hex) } +/// A swatch of `color` a line of text high, as in a button's text. +pub fn swatch<'a>(ui: &Ui, color: Option) -> Atom<'a> { + let height = ui.text_style_height(&TextStyle::Body); + Atom::paint(Vec2::splat(height), move |ui, args| { + let outline = Stroke::new(1.0, args.fallback_text_color); + paint_swatch(ui.painter(), args.rect, color, outline); + }) +} + /// Paints `color` in `rect` with an outline, or strikes `rect` out if `None`. pub fn paint_swatch(painter: &Painter, rect: Rect, color: Option, outline: Stroke) { match color { diff --git a/src/color_picker/tests.rs b/src/color_picker/tests.rs index c21afdc..998705a 100644 --- a/src/color_picker/tests.rs +++ b/src/color_picker/tests.rs @@ -221,6 +221,58 @@ fn colors_that_are_not_optional_cannot_be_none() { assert_eq!(harness.picked, [("text", Some(Color::WHITE))]); } +#[test] +fn opaque_colors_have_neither_alpha_nor_no_color() { + let mut harness = Harness::new(); + let see_through = Color { a: 0x80, ..ORANGE }; + let title = "Canvas background color"; + harness.picker.open_opaque("background", title, see_through); + harness.frame(vec![]); + harness.frame(vec![]); + let widgets = harness.driver.widgets.iter(); + let labels: Vec<_> = widgets.filter_map(|w| w.label()).collect(); + for absent in ["No color", "A"] { + assert!(!labels.contains(&absent), "{labels:?}"); + } + assert!(labels.contains(&"B"), "{labels:?}"); + assert_eq!(harness.hex(), "#FFCC00"); + + harness.type_text("#12345678"); + harness.press(Key::Enter); + let picked = Color::rgb(0x12, 0x34, 0x56); + assert_eq!(harness.picked, [("background", Some(picked))]); +} + +#[test] +fn recent_colors_show_as_they_would_be_picked_where_colors_must_be_opaque() { + let mut harness = Harness::new(); + for hex in ["#33669940", "#336699", "#12E3D000"] { + harness.pick(hex); + } + harness.open(Some(ORANGE)); + assert_eq!(harness.recent(), ["#12E3D000", "#336699", "#33669940"]); + harness.press(Key::Escape); + + harness + .picker + .open_opaque("background", "Background", Color::WHITE); + harness.frame(vec![]); + harness.frame(vec![]); + assert_eq!(harness.recent(), ["#12E3D0", "#336699"]); + let teal = Color32::from_rgb(0x12, 0xE3, 0xD0); + let mut shapes = harness.driver.shapes.iter(); + assert!(shapes.any(|shape| matches!(shape, Shape::Rect(rect) if rect.fill == teal))); + harness.click_recent(0, 1); + let marked: Vec<_> = (harness.driver.widgets.iter()) + .filter(|widget| widget.toggled() == Some(Toggled::True)) + .filter_map(|widget| widget.label()) + .collect(); + assert_eq!(marked, ["#12E3D0"]); + harness.click("OK"); + let picked = harness.picked.last().unwrap(); + assert_eq!(*picked, ("background", Some(Color::rgb(0x12, 0xE3, 0xD0)))); +} + #[test] fn no_color_picks_none() { let mut harness = Harness::new(); diff --git a/src/config/tests.rs b/src/config/tests.rs index 4509483..da710c9 100644 --- a/src/config/tests.rs +++ b/src/config/tests.rs @@ -31,11 +31,12 @@ fn changed_settings() -> Settings { view: canvas::Options { grid_lines: true, snap_lines: false, + background: Color::rgb(0x33, 0x66, 0x99), }, export: export::Settings { format: export::Format::Svg, margin: 20, - transparent: true, + background: export::Background::Canvas, scale: 200, outlines: true, }, @@ -68,11 +69,12 @@ fn the_settings_file_is_toml_in_sections() { let text = r##"[view] grid_lines = true snap_lines = false +background = "#336699" [export] format = "svg" margin = 20 -transparent = true +background = "canvas" scale = 200 outlines = true @@ -112,11 +114,12 @@ fn styles_never_set_are_left_out() { let text = "[view] grid_lines = true snap_lines = true +background = \"#FFFFFF\" [export] format = \"png\" margin = 10 -transparent = false +background = \"white\" scale = 100 outlines = false "; @@ -138,7 +141,7 @@ fn settings_missing_from_the_file_keep_their_defaults() { let settings = load_settings(&dir, "[view]\ngrid_lines = true\n"); let expected = canvas::Options { grid_lines: true, - snap_lines: true, + ..canvas::Options::default() }; assert_eq!(settings.view, expected); assert_eq!(settings.export, export::Settings::default()); @@ -177,6 +180,36 @@ width = 3.0 assert_eq!(settings.style, style); } +#[test] +fn backgrounds_this_version_cant_read_are_white() { + let dir = ScratchDir::new("config-unknown-backgrounds"); + let text = "[view]\nbackground = \"blue\"\n\n[export]\nbackground = \"paper\"\n"; + let settings = load_settings(&dir, text); + assert_eq!(settings.view.background, Color::WHITE); + assert_eq!(settings.export.background, export::Background::White); +} + +#[test] +fn the_canvas_background_reads_as_opaque() { + let dir = ScratchDir::new("config-opaque-background"); + let settings = load_settings(&dir, "[view]\nbackground = \"#33669980\"\n"); + assert_eq!(settings.view.background, Color::rgb(0x33, 0x66, 0x99)); +} + +#[test] +fn transparent_as_older_versions_wrote_it_reads_as_the_background() { + let dir = ScratchDir::new("config-old-transparent"); + for (transparent, background) in [ + (true, export::Background::Transparent), + (false, export::Background::White), + ] { + let text = format!("[export]\nmargin = 5\ntransparent = {transparent}\n"); + let export = load_settings(&dir, &text).export; + assert_eq!(export.background, background, "{transparent}"); + assert_eq!(export.margin, 5); + } +} + #[test] fn a_settings_file_that_isnt_toml_gives_the_defaults() { let dir = ScratchDir::new("config-not-toml"); diff --git a/src/export/mod.rs b/src/export/mod.rs index b80c626..12f9713 100644 --- a/src/export/mod.rs +++ b/src/export/mod.rs @@ -8,6 +8,7 @@ use std::fmt; use egui::Rect; use graphml::yed::Color; use resvg::{tiny_skia, usvg}; +use serde::de::{self, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::canvas::Drawing; @@ -56,6 +57,86 @@ impl<'de> Deserialize<'de> for Format { } } +/// What's behind an exported drawing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Background { + #[default] + White, + /// The canvas's background color. + Canvas, + Transparent, +} + +impl Background { + pub const ALL: [Background; 3] = [ + Background::White, + Background::Canvas, + Background::Transparent, + ]; + + pub fn name(self) -> &'static str { + match self { + Background::White => "White", + Background::Canvas => "Canvas color", + Background::Transparent => "Transparent", + } + } + + fn keyword(self) -> &'static str { + match self { + Background::White => "white", + Background::Canvas => "canvas", + Background::Transparent => "transparent", + } + } + + /// Its color, with `canvas` the canvas's, or `None` if it's transparent. + pub fn color(self, canvas: Color) -> Option { + match self { + Background::White => Some(Color::WHITE), + Background::Canvas => Some(canvas), + Background::Transparent => None, + } + } +} + +/// Written as its keyword. One this version doesn't know reads as white. +impl Serialize for Background { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.keyword()) + } +} + +/// Also read from the `transparent = true` or `false` older versions wrote. +impl<'de> Deserialize<'de> for Background { + fn deserialize>(deserializer: D) -> Result { + struct Read; + + impl Visitor<'_> for Read { + type Value = Background; + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a background or whether it's transparent") + } + + fn visit_str(self, keyword: &str) -> Result { + let known = Background::ALL.into_iter().find(|b| b.keyword() == keyword); + Ok(known.unwrap_or_default()) + } + + fn visit_bool(self, transparent: bool) -> Result { + Ok(if transparent { + Background::Transparent + } else { + Background::White + }) + } + } + + deserializer.deserialize_any(Read) + } +} + /// How drawings are exported. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -63,8 +144,8 @@ pub struct Settings { pub format: Format, /// Around the drawing, in points. pub margin: u32, - /// Whether the background is left transparent, rather than white. - pub transparent: bool, + #[serde(alias = "transparent")] + pub background: Background, /// A PNG's pixels per hundred points. pub scale: u32, /// Whether an SVG has its text as the outlines of the glyphs, rather than @@ -77,7 +158,7 @@ impl Default for Settings { Settings { format: Format::Png, margin: 10, - transparent: false, + background: Background::White, scale: 100, outlines: false, } @@ -124,10 +205,16 @@ pub fn too_large([width, height]: [u32; 2]) -> bool { u64::from(width) * u64::from(height) > MAX_PIXELS } -/// The file `drawing` exports to with `settings`, its text drawn in `fonts`. -pub fn export(drawing: &Drawing, settings: &Settings, fonts: &Fonts) -> Result, Error> { +/// The file `drawing` exports to with `settings`, `canvas` being the canvas's +/// background color, its text drawn in `fonts`. +pub fn export( + drawing: &Drawing, + settings: &Settings, + canvas: Color, + fonts: &Fonts, +) -> Result, Error> { let page = page(drawing.bounds, settings.margin).ok_or(Error::Empty)?; - let background = (!settings.transparent).then_some(Color::WHITE); + let background = settings.background.color(canvas); match settings.format { Format::Svg => { let svg = svg::write(drawing, page, background, settings.outlines, fonts); diff --git a/src/export/tests.rs b/src/export/tests.rs index 7bc2807..b098b24 100644 --- a/src/export/tests.rs +++ b/src/export/tests.rs @@ -14,6 +14,8 @@ use crate::selection::Selection; const RED: Color = Color::rgb(0xFF, 0x00, 0x00); const BLUE: Color = Color::rgb(0x00, 0x00, 0xFF); +/// The canvas's background color in these tests. +const CANVAS: Color = Color::rgb(0x33, 0x33, 0x33); /// What the canvas draws of `graphml`, or of the items `only` has, with the /// labels in egui's own fonts. @@ -68,7 +70,7 @@ fn svg(drawing: &Drawing, settings: Settings) -> String { format: Format::Svg, ..settings }; - let bytes = export(drawing, &settings, &Fonts::default()).unwrap(); + let bytes = export(drawing, &settings, CANVAS, &Fonts::default()).unwrap(); String::from_utf8(bytes).unwrap() } @@ -77,7 +79,7 @@ fn png(drawing: &Drawing, settings: Settings) -> Pixmap { format: Format::Png, ..settings }; - let bytes = export(drawing, &settings, &Fonts::default()).unwrap(); + let bytes = export(drawing, &settings, CANVAS, &Fonts::default()).unwrap(); Pixmap::decode_png(&bytes).unwrap() } @@ -307,22 +309,32 @@ fn colors_keep_their_alpha() { } #[test] -fn transparent_exports_have_no_background() { +fn exports_are_on_white_the_canvas_color_or_nothing() { let (graphml, ..) = two_nodes(); let drawing = drawing(&graphml, None); - let transparent = Settings { - transparent: true, - ..Settings::default() - }; - assert_eq!( - elements(&svg(&drawing, transparent.clone()), "rect").len(), - 1 - ); - assert_eq!(pixel(&png(&drawing, transparent), pos2(1.0, 1.0))[3], 0); - assert_eq!( - pixel(&png(&drawing, Settings::default()), pos2(1.0, 1.0)), - [0xFF, 0xFF, 0xFF, 0xFF] - ); + for (background, rect, pixel_color) in [ + (Background::White, Some("#FFFFFF"), [0xFF, 0xFF, 0xFF, 0xFF]), + ( + Background::Canvas, + Some("#333333"), + [0x33, 0x33, 0x33, 0xFF], + ), + (Background::Transparent, None, [0, 0, 0, 0]), + ] { + let settings = Settings { + background, + ..Settings::default() + }; + let svg = svg(&drawing, settings.clone()); + let rects = elements(&svg, "rect"); + // The page's, if any, then the box's. + assert_eq!(rects.len(), 1 + usize::from(rect.is_some()), "{svg}"); + if let Some(fill) = rect { + assert!(rects[0].ends_with(&format!(r#" fill="{fill}"/>"#)), "{svg}"); + } + let png = png(&drawing, settings); + assert_eq!(pixel(&png, pos2(1.0, 1.0)), pixel_color, "{background:?}"); + } } #[test] @@ -548,7 +560,7 @@ fn numbers_have_at_most_two_decimals() { fn an_empty_drawing_has_nothing_to_export() { let drawing = drawing(&yed::new_document(), None); assert!(matches!( - export(&drawing, &Settings::default(), &Fonts::default()), + export(&drawing, &Settings::default(), CANVAS, &Fonts::default()), Err(Error::Empty) )); assert_eq!(page(drawing.bounds, 10), None); @@ -567,14 +579,14 @@ fn pngs_over_the_limit_are_refused() { ); let drawing = drawing(&graphml, None); assert!(matches!( - export(&drawing, &Settings::default(), &Fonts::default()), + export(&drawing, &Settings::default(), CANVAS, &Fonts::default()), Err(Error::TooLarge) )); let svg = Settings { format: Format::Svg, ..Settings::default() }; - assert!(export(&drawing, &svg, &Fonts::default()).is_ok()); + assert!(export(&drawing, &svg, CANVAS, &Fonts::default()).is_ok()); } /// A red disc 20 across on a 40 by 30 canvas, which an SVG node at (100, 50) @@ -626,7 +638,7 @@ fn svg_nodes_embed_their_drawing_showing_what_it_draws() { fn pngs_draw_svg_nodes_stretched_as_on_the_canvas() { let graphml = red_disc(); let transparent = Settings { - transparent: true, + background: Background::Transparent, margin: 0, ..Settings::default() }; diff --git a/src/export_dialog/mod.rs b/src/export_dialog/mod.rs index 34acbe2..276a411 100644 --- a/src/export_dialog/mod.rs +++ b/src/export_dialog/mod.rs @@ -1,18 +1,19 @@ use std::ops::RangeInclusive; -use egui::{Align, Button, Context, DragValue, Layout, Rect, Response, Ui, vec2}; +use egui::{Align, Atoms, Button, Context, DragValue, Layout, Rect, Response, Ui, vec2}; +use graphml::yed::Color; -use crate::dialog; -use crate::export::{self, Format, Settings}; +use crate::export::{self, Background, Format, Settings}; +use crate::{color_picker, dialog}; /// The PNG scales offered, in percent. const SCALES: RangeInclusive = 10..=1000; /// The margins offered, in points. const MARGINS: RangeInclusive = 0..=1000; /// So that the dialog keeps its width as the numbers change. -const MIN_WIDTH: f32 = 280.0; +const MIN_WIDTH: f32 = 295.0; /// Of the labels left of the choices. -const LABEL_WIDTH: f32 = 60.0; +const LABEL_WIDTH: f32 = 75.0; /// A modal dialog asking how to export the drawing: its format, all of it or /// what's selected, and the format's options. @@ -31,6 +32,8 @@ pub struct Accepted { struct Dialog { accepted: Accepted, + /// The canvas's background color. + canvas: Color, /// What the drawing covers, in graph points. everything: Rect, /// What the selected items cover, if any are selected. @@ -45,9 +48,16 @@ impl ExportDialog { } /// Opens the dialog on `settings`, with all of the drawing chosen, for a - /// drawing covering `everything`, of which the selected items cover - /// `selected`, unless none are. Unless it's open already. - pub fn open(&mut self, settings: Settings, everything: Rect, selected: Option) { + /// drawing covering `everything` on a `canvas` background, of which the + /// selected items cover `selected`, unless none are. Unless it's open + /// already. + pub fn open( + &mut self, + settings: Settings, + canvas: Color, + everything: Rect, + selected: Option, + ) { if self.is_open() { return; } @@ -56,6 +66,7 @@ impl ExportDialog { settings, selected_only: false, }, + canvas, everything, selected, focus: true, @@ -127,8 +138,16 @@ impl Dialog { ) }); field.labelled_by(label.id); - row(ui, "", |ui| { - ui.checkbox(&mut settings.transparent, "Transparent background"); + row(ui, "Background", |ui| { + ui.vertical(|ui| { + for background in Background::ALL { + let mut text = Atoms::new(background.name()); + if background == Background::Canvas { + text.push_right(color_picker::swatch(ui, Some(self.canvas))); + } + ui.radio_value(&mut settings.background, background, text); + } + }); }); if !png { row(ui, "", |ui| { diff --git a/src/export_dialog/tests.rs b/src/export_dialog/tests.rs index 9276ce6..684cc06 100644 --- a/src/export_dialog/tests.rs +++ b/src/export_dialog/tests.rs @@ -6,6 +6,7 @@ use egui::{FallbackRequest, FontInsert, Key, Modifiers, pos2, vec2}; use super::*; use crate::testing::{Drive, Driver, center}; +const CANVAS: Color = Color::rgb(0x33, 0x66, 0x99); /// 100×50 points at the origin. const EVERYTHING: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 50.0)); const SELECTED: Rect = Rect::from_min_max(pos2(10.0, 10.0), pos2(30.0, 30.0)); @@ -50,7 +51,7 @@ impl Harness { dialog: ExportDialog::default(), accepted: Vec::new(), }; - harness.dialog.open(settings, everything, selected); + harness.dialog.open(settings, CANVAS, everything, selected); // A new modal is laid out unseen first. harness.frame(vec![]); harness.frame(vec![]); @@ -119,7 +120,7 @@ fn the_options_shown_are_the_formats() { assert!(harness.driver.painted("PNG options")); // Scale and margin. assert_eq!(harness.fields().len(), 2); - assert!(harness.shown("Transparent background")); + assert!(harness.shown("Transparent")); assert!(!harness.shown("Text as outlines")); harness.click("SVG"); @@ -127,7 +128,7 @@ fn the_options_shown_are_the_formats() { assert!(harness.driver.painted("SVG options")); // Margin only. assert_eq!(harness.fields().len(), 1); - assert!(harness.shown("Transparent background")); + assert!(harness.shown("Transparent")); assert!(harness.shown("Text as outlines")); assert!(!harness.driver.painted("120 × 70 px")); } @@ -162,7 +163,7 @@ fn the_size_in_pixels_follows_the_area_scale_and_margin() { fn export_returns_the_options_set() { let mut harness = Harness::open(Settings::default(), false); harness.click("SVG"); - harness.click("Transparent background"); + harness.click("Transparent"); harness.click("Text as outlines"); harness.set_field(0, "4"); harness.click("Export…"); @@ -172,7 +173,7 @@ fn export_returns_the_options_set() { settings: Settings { format: Format::Svg, margin: 4, - transparent: true, + background: Background::Transparent, scale: 100, outlines: true, }, @@ -186,13 +187,14 @@ fn it_opens_on_the_settings_given() { let settings = Settings { format: Format::Svg, margin: 5, - transparent: true, + background: Background::Transparent, scale: 300, outlines: true, }; let mut harness = Harness::open(settings.clone(), false); assert!(harness.checked("SVG")); - assert!(harness.checked("Transparent background")); + assert!(harness.checked("Transparent")); + assert!(!harness.checked("White")); assert!(harness.checked("Text as outlines")); assert_eq!(harness.fields()[0].numeric_value(), Some(5.0)); harness.click("PNG"); @@ -252,7 +254,9 @@ fn pngs_over_the_limit_cant_be_exported() { fn opening_it_again_while_open_keeps_it() { let mut harness = Harness::open(Settings::default(), true); harness.click("Selected area only"); - harness.dialog.open(Settings::default(), EVERYTHING, None); + harness + .dialog + .open(Settings::default(), CANVAS, EVERYTHING, None); harness.repaint(); assert!(harness.checked("Selected area only")); } @@ -286,7 +290,7 @@ fn the_dialog_shows_where_it_stays() { }; harness .dialog - .open(Settings::default(), EVERYTHING, Some(SELECTED)); + .open(Settings::default(), CANVAS, EVERYTHING, Some(SELECTED)); // Laid out unseen first. harness.frame(vec![]); let mut shown = Vec::new(); @@ -296,3 +300,44 @@ fn the_dialog_shows_where_it_stays() { } assert!(shown.iter().all(|&at| at == shown[0]), "{shown:?}"); } + +#[test] +fn the_choices_line_up_beside_their_labels() { + let harness = Harness::open(Settings::default(), true); + let left = |widget: &Node| widget.bounds().unwrap().x0; + let choices = [ + "PNG", + "Entire document", + "White", + "Canvas color", + "Transparent", + ]; + let mut lefts: Vec<_> = choices + .map(|label| left(harness.driver.widget(label))) + .into(); + lefts.extend(harness.fields().into_iter().map(left)); + assert!(lefts.iter().all(|&x| x == lefts[0]), "{lefts:?}"); +} + +#[test] +fn canvas_color_shows_the_canvas_background() { + let mut harness = Harness::open(Settings::default(), false); + assert!(harness.checked("White")); + let fill = color_picker::color32(CANVAS); + let swatch = harness.driver.shapes.iter().find_map(|shape| match shape { + egui::Shape::Rect(rect) if rect.fill == fill => Some(rect.rect), + _ => None, + }); + let swatch = swatch.expect("the canvas color is shown"); + // Inside the choice, so clicking it picks the choice. + let choice = harness.driver.widget("Canvas color").bounds().unwrap(); + let choice = Rect::from_min_max( + pos2(choice.x0 as f32, choice.y0 as f32), + pos2(choice.x1 as f32, choice.y1 as f32), + ); + assert!(choice.contains_rect(swatch), "{swatch:?} in {choice:?}"); + harness.click_at(swatch.center(), 1); + harness.click("Export…"); + let background = harness.accepted[0].settings.background; + assert_eq!(background, Background::Canvas); +} diff --git a/src/main.rs b/src/main.rs index 1802daf..870e8b9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -152,8 +152,7 @@ struct DrwrApp { fonts: Arc, side_panel: SidePanel, file_dialog: FileDialog, - /// Picks the colors of the selected nodes and edges. - color_picker: ColorPicker, + color_picker: ColorPicker, label_dialog: TextDialog, export_dialog: ExportDialog, /// Whether the About dialog is open. @@ -175,6 +174,24 @@ struct DrwrApp { typing: bool, } +/// What the color picker picks a color for. +#[derive(Clone, Copy, Debug, PartialEq)] +enum ColorTarget { + /// A color of the selected nodes and edges. + Selection(ColorProperty), + CanvasBackground, +} + +impl ColorTarget { + /// The action setting it to `color`, if it can be that. + fn set(self, color: Option) -> Option { + match self { + ColorTarget::Selection(property) => Some(Action::SetColor(property, color)), + ColorTarget::CanvasBackground => color.map(Action::SetCanvasBackground), + } + } +} + /// Labels the label dialog edits together, and the text it opened on. struct LabelEdit { labels: Vec, @@ -194,6 +211,8 @@ enum FilePurpose { struct ExportJob { drawing: Drawing, settings: export::Settings, + /// The canvas's background color. + canvas: yed::Color, } /// An export writing the file at `path` on its own thread, which returns why @@ -493,7 +512,8 @@ impl DrwrApp { let everything = Drawing::of(ctx, scene, None).bounds; let selected = (!self.selected.is_empty()) .then(|| Drawing::of(ctx, scene, Some(&self.selected)).bounds); - (self.export_dialog).open(self.settings.export.clone(), everything, selected); + let (settings, canvas) = (self.settings.export.clone(), self.settings.view.background); + (self.export_dialog).open(settings, canvas, everything, selected); } /// Asks where to export the drawing as the export dialog was `accepted`, @@ -520,7 +540,12 @@ impl DrwrApp { name: format!("{stem}.{}", format.extension()), folder: file.and_then(Path::parent).map(Path::to_path_buf), }; - let job = Arc::new(ExportJob { drawing, settings }); + let canvas = self.settings.view.background; + let job = Arc::new(ExportJob { + drawing, + settings, + canvas, + }); (self.file_dialog).open(FilePurpose::Export(job), request, ctx, frame); } @@ -545,7 +570,7 @@ impl DrwrApp { let thread = std::thread::Builder::new() .name("export".to_owned()) .spawn(move || { - let written = export::export(&job.drawing, &job.settings, &fonts) + let written = export::export(&job.drawing, &job.settings, job.canvas, &fonts) .map_err(|err| err.to_string()) .and_then(|bytes| { atomic_file::write(&to, |file| file.write_all(&bytes)) @@ -754,6 +779,14 @@ impl DrwrApp { Action::ToggleSnapLines => { self.settings.view.snap_lines = !self.settings.view.snap_lines; } + Action::EditCanvasBackground => { + let color = self.settings.view.background; + let target = ColorTarget::CanvasBackground; + (self.color_picker).open_opaque(target, "Canvas background color", color); + } + Action::SetCanvasBackground(color) => { + self.settings.view.background = yed::Color { a: 255, ..color }; + } Action::MoveBy(dx, dy) => match (self.selected.single(), self.selected.bend()) { (Some(&Item::Edge(index)), Some(bend)) => { document::move_bends(self.doc.graphml_mut(), index, Some(bend), dx, dy); @@ -782,8 +815,8 @@ impl DrwrApp { if let Some(graphics) = first { let title = format!("{} color", property.name()); let color = property.get(graphics.as_ref()); - self.color_picker - .open(property, title, color, property.optional()); + let target = ColorTarget::Selection(property); + (self.color_picker).open(target, title, color, property.optional()); } } Action::SetColor(property, color) => { @@ -968,8 +1001,9 @@ impl eframe::App for DrwrApp { self.perform(action, ui.ctx(), frame); } - if let Some((property, color)) = self.color_picker.show(ui.ctx()) { - self.perform(Action::SetColor(property, color), ui.ctx(), frame); + let picked = self.color_picker.show(ui.ctx()); + if let Some(action) = picked.and_then(|(target, color)| target.set(color)) { + self.perform(action, ui.ctx(), frame); } if let Some((edit, text)) = self.label_dialog.show(ui.ctx()) // Unchanged, it would blank labels that differ. diff --git a/src/menu.rs b/src/menu.rs index b5a802d..c599ab8 100644 --- a/src/menu.rs +++ b/src/menu.rs @@ -88,7 +88,14 @@ pub fn show( ("Snap Lines", Action::ToggleSnapLines, snap), ], ); - clicked = zoom.or(options); + ui.separator(); + let item = ( + "Canvas Background Color…", + Action::EditCanvasBackground, + true, + ); + let background = items(ui, [item]); + clicked = zoom.or(options).or(background); }); }); }); diff --git a/src/side_panel.rs b/src/side_panel.rs index acad3d3..d235c6d 100644 --- a/src/side_panel.rs +++ b/src/side_panel.rs @@ -596,9 +596,7 @@ fn color_button(ui: &mut Ui, color: Option>) -> Response { }); return ui.add(Button::new(swatch)); }; - let swatch = sample(ui, 1.0, move |painter, rect, outline| { - color_picker::paint_swatch(painter, rect, color, outline); - }); + let swatch = color_picker::swatch(ui, color); let text = color.map_or("None".to_owned(), |color| color.to_string()); ui.add(Button::new((swatch, text))) } diff --git a/src/tests/export.rs b/src/tests/export.rs index 17bc68f..520fdd9 100644 --- a/src/tests/export.rs +++ b/src/tests/export.rs @@ -252,15 +252,47 @@ fn selected_area_only_needs_a_selection() { assert!(harness.checked("Entire document")); } +#[test] +fn exports_can_be_on_the_canvas_background_color() { + let dir = ScratchDir::new("export-background"); + let mut harness = fixture_harness(); + let slate = yed::Color::rgb(0x33, 0x66, 0x99); + harness.perform(Action::SetCanvasBackground(slate)); + harness.press(CTRL, Key::E); + // Its swatch, a line of text high, unlike the canvas. + let swatch = harness.run(vec![]).into_iter().any(|shape| match shape { + Shape::Rect(rect) => { + rect.fill == Color32::from_rgb(0x33, 0x66, 0x99) && rect.rect.height() < 20.0 + } + _ => false, + }); + assert!(swatch); + harness.close_export_dialog(None); + harness.export_with(&["SVG"]); + harness.export_to(&dir.path("white.svg")); + harness.export_with(&["Canvas color"]); + harness.export_to(&dir.path("canvas.svg")); + // The page's rect comes first. + let page = |name: &str| { + let svg = read_to_string(&dir.path(name)); + let rect = svg.lines().find(|line| line.starts_with(""##)); + assert!(page("canvas.svg").ends_with(r##" fill="#336699"/>"##)); + let background = harness.app.settings.export.background; + assert_eq!(background, crate::export::Background::Canvas); +} + #[test] fn settings_are_kept_but_the_area_starts_as_entire_document() { let mut harness = fixture_harness(); harness.app.selected = Selection::node("n0"); - harness.export_with(&["SVG", "Transparent background", "Selected area only"]); + harness.export_with(&["SVG", "Transparent", "Selected area only"]); harness.answer(None); harness.press(CTRL, Key::E); assert!(harness.checked("SVG")); - assert!(harness.checked("Transparent background")); + assert!(harness.checked("Transparent")); assert!(harness.checked("Entire document")); // Cancelling keeps none of what was changed. diff --git a/src/tests/files.rs b/src/tests/files.rs index 16e368e..deb4a21 100644 --- a/src/tests/files.rs +++ b/src/tests/files.rs @@ -92,10 +92,12 @@ fn ctrl_n_replaces_the_graph_with_an_empty_unsaved_one() { #[test] fn new_closes_the_dialogs() { let mut harness = fixture_harness(); - harness - .app - .color_picker - .open(ColorProperty::Fill, "Fill", None, true); + harness.app.color_picker.open( + ColorTarget::Selection(ColorProperty::Fill), + "Fill", + None, + true, + ); let edit = LabelEdit { labels: vec![], text: String::new(), @@ -109,8 +111,8 @@ fn new_closes_the_dialogs() { #[test] fn open_closes_the_color_picker() { let mut app = DrwrApp::default(); - app.color_picker - .open(ColorProperty::Fill, "Fill color", None, true); + let fill = ColorTarget::Selection(ColorProperty::Fill); + app.color_picker.open(fill, "Fill color", None, true); app.open(Path::new(FIXTURE)).unwrap(); assert!(!app.color_picker.is_open()); } diff --git a/src/tests/settings.rs b/src/tests/settings.rs index dead3d2..41149f4 100644 --- a/src/tests/settings.rs +++ b/src/tests/settings.rs @@ -32,12 +32,16 @@ fn view_menu_options_outlast_a_restart() { harness.click_widget("Snap Lines"); // Too soon after the grid lines to be written yet. assert!(settings_file(&dir).contains("snap_lines = true")); + let slate = yed::Color::rgb(0x33, 0x66, 0x99); + harness.perform(Action::SetCanvasBackground(slate)); assert!(!harness.close_window()); + assert!(settings_file(&dir).contains("background = \"#336699\"")); let mut harness = start(&dir); let options = canvas::Options { grid_lines: true, snap_lines: false, + background: slate, }; assert_eq!(harness.app.settings.view, options); harness.click_widget("View"); diff --git a/src/tests/view.rs b/src/tests/view.rs index 7ccf622..b454f78 100644 --- a/src/tests/view.rs +++ b/src/tests/view.rs @@ -161,6 +161,7 @@ fn frames_that_change_nothing_read_nothing() { } const GRID_LINES: &str = "Canvas Grid Lines Ctrl+'"; +const BACKGROUND: &str = "Canvas Background Color…"; /// Whether the canvas painted grid lines: quads of gray. fn grid_painted(shapes: &[Shape]) -> bool { @@ -174,7 +175,7 @@ fn grid_painted(shapes: &[Shape]) -> bool { } #[test] -fn the_view_menu_has_the_zoom_commands_then_grid_and_snap_lines() { +fn the_view_menu_has_the_zoom_commands_then_the_canvas_options() { let mut harness = Harness::new(); harness.click_widget("View"); let labels = [ @@ -183,6 +184,7 @@ fn the_view_menu_has_the_zoom_commands_then_grid_and_snap_lines() { "Zoom to 100% Ctrl+0", GRID_LINES, "Snap Lines", + BACKGROUND, ]; let ys: Vec<_> = (labels.iter()) .map(|label| testing::center(&harness.widget(label)).y) @@ -245,18 +247,87 @@ fn canvas_grid_lines_toggle_from_the_view_menu_and_with_ctrl_quote() { } #[test] -fn grid_and_snap_lines_stay_as_set_for_new_and_opened_graphs() { +fn the_canvas_options_stay_as_set_for_new_and_opened_graphs() { let mut harness = Harness::new(); + let canvas = canvas(&harness.run(vec![])); harness.press(CTRL, Key::Quote); harness.perform(Action::ToggleSnapLines); + // Gray, so that the grid lines are too. + let gray = yed::Color::rgb(0xF0, 0xF0, 0xF0); + harness.perform(Action::SetCanvasBackground(gray)); harness.press(CTRL, Key::N); harness.run(vec![]); let options = canvas::Options { grid_lines: true, snap_lines: false, + background: gray, }; assert_eq!(harness.app.settings.view, options); harness.open_fixture(); - assert!(grid_painted(&harness.run(vec![]))); + let shapes = harness.run(vec![]); + assert!(grid_painted(&shapes)); + assert_eq!(canvas_on(&shapes, Color32::from_gray(0xF0)), Some(canvas)); assert_eq!(harness.app.settings.view, options); } + +const SLATE: yed::Color = yed::Color::rgb(0x33, 0x66, 0x99); + +/// Where the canvas is: the largest rect painted in `background`. +fn canvas_on(shapes: &[Shape], background: Color32) -> Option { + let rects = shapes.iter().filter_map(|shape| match shape { + Shape::Rect(rect) if rect.fill == background => Some(rect.rect), + _ => None, + }); + rects.max_by(|a, b| a.area().total_cmp(&b.area())) +} + +#[test] +fn the_canvas_background_color_is_picked_from_the_view_menu() { + let mut harness = fixture_harness(); + let canvas = canvas(&harness.run(vec![])); + harness.click_widget("View"); + harness.click_widget(BACKGROUND); + assert!(!Popup::is_any_open(&harness.ctx)); + assert!(harness.painted("Canvas background color")); + assert!( + harness + .widgets() + .iter() + .all(|w| w.label() != Some("No color")) + ); + // The hex field has the focus. + harness.type_text("336699"); + harness.press(Modifiers::NONE, Key::Enter); + assert!(!harness.app.color_picker.is_open()); + assert_eq!(harness.app.settings.view.background, SLATE); + let slate = Color32::from_rgb(0x33, 0x66, 0x99); + assert_eq!(canvas_on(&harness.run(vec![]), slate), Some(canvas)); + + // A view setting, not a change to the graph. + assert!(!harness.app.check_modified()); + assert!(!harness.app.doc.can_undo()); +} + +#[test] +fn the_canvas_background_color_picker_opens_on_the_color_set() { + let mut harness = Harness::new(); + harness.perform(Action::SetCanvasBackground(SLATE)); + harness.click_widget("View"); + harness.click_widget(BACKGROUND); + // Cancelled, nothing changes. + harness.click_widget("Cancel"); + assert!(!harness.app.color_picker.is_open()); + assert_eq!(harness.app.settings.view.background, SLATE); + harness.click_widget("View"); + harness.click_widget(BACKGROUND); + harness.press(Modifiers::NONE, Key::Enter); + assert_eq!(harness.app.settings.view.background, SLATE); +} + +#[test] +fn the_canvas_background_is_always_opaque() { + let mut harness = Harness::new(); + let see_through = yed::Color { a: 0x80, ..SLATE }; + harness.perform(Action::SetCanvasBackground(see_through)); + assert_eq!(harness.app.settings.view.background, SLATE); +}