Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
40 changes: 32 additions & 8 deletions src/canvas/grid/mod.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -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)
Expand All @@ -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.
Expand Down
32 changes: 32 additions & 0 deletions src/canvas/grid/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
28 changes: 24 additions & 4 deletions src/canvas/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -103,25 +101,47 @@ 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 {
pub grid_lines: bool,
/// 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 {
fn default() -> Self {
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<S: Serializer>(color: &Color, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(color)
}

pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Color, D::Error> {
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 {
Expand Down Expand Up @@ -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)
Expand Down
11 changes: 6 additions & 5 deletions src/canvas/paint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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.
Expand Down
18 changes: 18 additions & 0 deletions src/canvas/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
Expand Down
74 changes: 63 additions & 11 deletions src/color_picker/mod.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -40,6 +40,8 @@ struct Dialog<T> {
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,
Expand Down Expand Up @@ -69,19 +71,41 @@ impl<T> ColorPicker<T> {
title: impl Into<String>,
color: Option<Color>,
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<String>, color: Color) {
self.open_dialog(target, title.into(), Some(color), false, true);
}

fn open_dialog(
&mut self,
target: T,
title: String,
color: Option<Color>,
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.
Expand Down Expand Up @@ -115,8 +139,17 @@ impl<T> Dialog<T> {
(!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;
}

Expand All @@ -139,10 +172,17 @@ impl<T> Dialog<T> {
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);
Expand Down Expand Up @@ -211,12 +251,15 @@ impl<T> Dialog<T> {
});
}

/// 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)
Expand Down Expand Up @@ -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<Color>) -> 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<Color>, outline: Stroke) {
match color {
Expand Down
Loading
Loading