pdf-forms-w1: net change of 4 commits

- pdf-forms-w1: finished by an agent
- pdf-forms-w1: finished by an agent
- pdf-forms-w1: review fixes (review-1)
- pdf-forms-w1: drop_veil stories no longer need ShowContainer (lead applied the refused hunk)
This commit is contained in:
Dylan M. Taylor
2026-11-18 08:07:07 -05:00
parent 6a83eb7a0f
commit 031b32dc90
15 changed files with 707 additions and 128 deletions
+5 -3
View File
@@ -99,8 +99,9 @@ below), and `Embed::documents(&["Noto Sans", …])` only the families it names (
`write` returns the embedded `ManifestEntry`s, for build-time checks such as "the interface face
is present". The generated file is a slice expression of `EmbeddedFace { family, style, scripts,
index, bytes, role }` literals; any struct with those fields and that name in scope works too.
`role` is the manifest line's ninth field: `Some("ui")`, `Some("mono")` or `None`; craft-ui's font
stack leads the Monospace family with the `mono` face. `EmbeddedFace` itself has `name()`,
`role` is the manifest line's ninth field: `Some("ui")`, `Some("mono")`, `Some("signature")` or
`None`; craft-ui's font stack leads the Monospace family with the `mono` face and the signature
family (`FontRef::signature()`) with the `signature` face. `EmbeddedFace` itself has `name()`,
`has_script(tag)`, `is_cjk()` and `weight()`.
## Document fonts
@@ -201,5 +202,6 @@ exact only for the catalogs it was cut to. It also reruns the build script when
One face per line, eight or nine fields separated by `" | "`; craft-fonts' `docs/integration.md`
defines them. Lines starting with `#` are comments. A file field ending in `#<n>` names face `n` of
a font collection (`fonts/noto-sans-cjk/NotoSansCJK.ttc#2`); without it the index is 0. The ninth
field, `role`, is `ui` on interface faces, `mono` on the monospace face and absent elsewhere. Fields
field, `role`, is `ui` on interface faces, `mono` on the monospace face, `signature` on the signature
face and absent elsewhere. Fields
after the ninth are ignored.
+2 -1
View File
@@ -81,7 +81,8 @@ pub struct EmbeddedFace {
/// The font file's bytes, from `include_bytes!`.
pub bytes: &'static [u8],
/// The manifest line's `role`: `Some("ui")` for an interface face ([`UI_ROLE`]), `Some("mono")` for the
/// monospace face ([`MONO_ROLE`]), `None` for a line without one.
/// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `None` for a
/// line without one.
pub role: Option<&'static str>,
}
+3 -2
View File
@@ -8,7 +8,8 @@
//! Blank lines and lines starting with `#` are skipped. `file` is relative to the checkout and may
//! end in `#<index>` to pick one face of a font collection (`.ttc`). The optional `role` is `ui` for
//! an interface face: a full Regular TrueType face that an app's build cuts to the characters of its
//! translation catalogs; or `mono` for the monospace face, which leads an app's Monospace family.
//! translation catalogs; `mono` for the monospace face, which leads an app's Monospace family; or
//! `signature` for the handwriting face, which leads the signature family.
//! Fields after the ninth are ignored, so a manifest that gains a field still embeds.
use std::fmt;
@@ -35,7 +36,7 @@ pub struct ManifestEntry {
/// Where the file came from.
pub source: String,
/// The optional ninth field: `Some("ui")` for an interface face, `Some("mono")` for the
/// monospace face, `None` when the line has no role.
/// monospace face, `Some("signature")` for the signature face, `None` when the line has no role.
pub role: Option<String>,
}
+4 -2
View File
@@ -19,11 +19,13 @@ workspace = true
[features]
default = []
# The review widgets (`craft_review::ui`).
ui = ["dep:craft-keymap", "dep:craft-ui", "dep:craft-host", "dep:craft-theme", "dep:egui", "dep:image"]
ui = ["dep:craft-keymap", "dep:craft-ui", "dep:craft-host", "dep:craft-theme", "dep:egui"]
# The stories and the integration tests (`tests/it`).
screen-testing = ["ui", "craft-ui/testing"]
[dependencies]
# Saved signature images are stored as base64 PNG text.
base64 = "0.23"
craft-behavior = { workspace = true }
craft-host = { workspace = true, optional = true, features = ["ui"] }
craft-i18n = { workspace = true }
@@ -31,7 +33,7 @@ craft-keymap = { workspace = true, optional = true }
craft-theme = { workspace = true, optional = true }
craft-ui = { workspace = true, optional = true }
egui = { workspace = true, optional = true }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"], optional = true }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
kurbo = { workspace = true, features = ["serde"] }
serde = { workspace = true }
+99 -14
View File
@@ -1,6 +1,10 @@
//! Saved signatures and initials, and the signature pad's draft (N5.04).
use std::hash::{Hash as _, Hasher as _};
use std::io::Cursor;
use base64::{Engine as _, engine::general_purpose::STANDARD};
use image::ImageEncoder as _;
/// The largest image file the Image tab takes: 4 MiB (PdfCraft's "Choose a PNG or JPEG image
/// (up to 4 MiB)").
@@ -30,7 +34,7 @@ pub const MAX_SIGNATURE_CHARS: usize = 256;
/// into a key the painter caches the texture under; the key is not serialized, and deserializing
/// derives it again.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(from = "RawSignatureImage", into = "RawSignatureImage")]
#[serde(try_from = "RawSignatureImage", into = "RawSignatureImage")]
pub struct SignatureImage {
width: u32,
height: u32,
@@ -38,26 +42,99 @@ pub struct SignatureImage {
key: u64,
}
/// [`SignatureImage`] as stored.
/// The longest stored image text read: the base64 of a [`MAX_IMAGE_BYTES`] PNG. Longer text is refused before it is
/// decoded.
const MAX_STORED_CHARS: usize = MAX_IMAGE_BYTES.div_ceil(3) * 4;
/// [`SignatureImage`] as stored: a base64 PNG.
#[derive(serde::Serialize, serde::Deserialize)]
struct RawSignatureImage {
width: u32,
height: u32,
rgba: Vec<u8>,
png: String,
}
impl From<RawSignatureImage> for SignatureImage {
fn from(raw: RawSignatureImage) -> Self {
Self::new(raw.width, raw.height, raw.rgba)
/// A stored image that was not read: text over [`MAX_STORED_CHARS`], not base64, or not a PNG within the image caps.
#[derive(Debug)]
struct RefusedImage;
impl std::fmt::Display for RefusedImage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("a stored signature image that is too large or unreadable")
}
}
impl TryFrom<RawSignatureImage> for SignatureImage {
type Error = RefusedImage;
fn try_from(raw: RawSignatureImage) -> Result<Self, RefusedImage> {
if raw.png.len() > MAX_STORED_CHARS {
return Err(RefusedImage);
}
let bytes = STANDARD.decode(raw.png.as_bytes()).map_err(|_| RefusedImage)?;
decode_fitted(&bytes).map_err(|_| RefusedImage)
}
}
/// Encodes the image as PNG. An image whose buffer doesn't fit its size can't be encoded (and paints nothing): it is
/// stored as empty text, which the reader refuses, so its slot reads back as `None` instead of failing the whole
/// settings section.
impl From<SignatureImage> for RawSignatureImage {
fn from(image: SignatureImage) -> Self {
Self { width: image.width, height: image.height, rgba: image.rgba }
let mut png = Vec::new();
let encoded =
image::codecs::png::PngEncoder::new(&mut png).write_image(&image.rgba, image.width, image.height, image::ExtendedColorType::Rgba8);
Self { png: if encoded.is_ok() { STANDARD.encode(&png) } else { String::new() } }
}
}
/// Why image bytes were not taken.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PickError {
/// Unreadable, or not a PNG or JPEG.
Unreadable,
/// More than [`MAX_IMAGE_BYTES`] of file or [`MAX_IMAGE_SIDE`] pixels on a side.
TooLarge,
}
/// Decodes a PNG or JPEG of at most [`MAX_IMAGE_BYTES`] and [`MAX_IMAGE_SIDE`] pixels a side into straight RGBA, turned
/// upright by its EXIF orientation and scaled down within [`MAX_SAVED_SIDE`] and [`MAX_SAVED_PIXELS`]. The size limits
/// apply while decoding, so an oversize image is refused before its pixels are allocated.
pub(crate) fn decode_fitted(bytes: &[u8]) -> Result<SignatureImage, PickError> {
use image::ImageDecoder as _;
if bytes.len() > MAX_IMAGE_BYTES {
return Err(PickError::TooLarge);
}
let refused = |error: image::ImageError| if matches!(error, image::ImageError::Limits(_)) { PickError::TooLarge } else { PickError::Unreadable };
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| PickError::Unreadable)?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_IMAGE_SIDE);
limits.max_image_height = Some(MAX_IMAGE_SIDE);
reader.limits(limits);
let mut decoder = reader.into_decoder().map_err(refused)?;
// An unreadable orientation tag leaves the image as stored, as a viewer would.
let orientation = decoder.orientation().unwrap_or(image::metadata::Orientation::NoTransforms);
let mut decoded = image::DynamicImage::from_decoder(decoder).map_err(refused)?;
decoded.apply_orientation(orientation);
let (width, height) = saved_size(decoded.width(), decoded.height());
if (width, height) != (decoded.width(), decoded.height()) {
decoded = decoded.thumbnail(width, height);
}
let rgba = decoded.into_rgba8();
Ok(SignatureImage::new(rgba.width(), rgba.height(), rgba.into_raw()))
}
/// The size a `width` × `height` image is kept at: unchanged within [`MAX_SAVED_SIDE`] and [`MAX_SAVED_PIXELS`], else
/// scaled down keeping its aspect until both hold (8000 × 6000 becomes 2364 × 1773, 4.19 MP).
fn saved_size(width: u32, height: u32) -> (u32, u32) {
let side = f64::from(MAX_SAVED_SIDE) / f64::from(width.max(height).max(1));
let area = (MAX_SAVED_PIXELS as f64 / (f64::from(width) * f64::from(height)).max(1.0)).sqrt();
let scale = side.min(area);
if scale >= 1.0 {
return (width, height);
}
let shrink = |v: u32| ((f64::from(v) * scale).floor() as u32).max(1);
(shrink(width), shrink(height))
}
impl SignatureImage {
/// An image of `width` × `height` pixels in straight RGBA (`rgba` holds 4 bytes a pixel; an
/// image whose length doesn't fit paints nothing).
@@ -84,11 +161,19 @@ impl SignatureImage {
&self.rgba
}
/// The image with paper white made transparent, with a feathered edge of `feather` below `cutoff`.
#[allow(dead_code)] // P3(pdf-forms-w1): FM-PF4
/// The image with paper white made transparent, with a feathered edge of `feather` below `cutoff`: a pixel whose
/// darkest channel is `cutoff` or lighter goes clear, one `feather` or more below it keeps its alpha, and those in
/// between fade. Transparency already there stays.
pub fn remove_white_background(&self, cutoff: u8, feather: u8) -> SignatureImage {
let _ = (cutoff, feather);
todo!("FM-PF4")
let high = f32::from(cutoff);
let span = f32::from(feather.max(1));
let mut rgba = self.rgba.clone();
for pixel in rgba.chunks_exact_mut(4) {
let whiteness = f32::from(pixel[0].min(pixel[1]).min(pixel[2]));
let keep = ((high - whiteness) / span).clamp(0.0, 1.0);
pixel[3] = (f32::from(pixel[3]) * keep).round() as u8;
}
SignatureImage::new(self.width, self.height, rgba)
}
/// The content key computed by [`new`](Self::new); equal images have equal keys.
@@ -102,7 +187,7 @@ impl SignatureImage {
pub enum SavedSignature {
/// Strokes in pad units (0…1 on both axes of the pad's box).
Drawn(Vec<Vec<[f32; 2]>>),
/// Text drawn in the proportional face (the library has no script face).
/// Text drawn in the signature face (craft-ui's `FontRef::signature()`).
Typed(String),
/// A signature image.
Image(SignatureImage),
+94 -60
View File
@@ -1,6 +1,5 @@
//! The signature pad dialog and saved signatures.
use std::io::Cursor;
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, TryRecvError, channel};
@@ -18,6 +17,7 @@ use craft_ui::display::{Shade, Text};
use craft_ui::fonts::FontRef;
use craft_ui::layout_components::Row;
use craft_ui::notices::{Notice, NoticeLayout};
use craft_ui::popover::DropVeil;
use craft_ui::primitives::{DocRun, DocText, Draw, HAlign, PaintShape, StrokeWidth, TextureCache};
use craft_ui::runtime::drag::OsFile;
use craft_ui::runtime::env::Env;
@@ -27,7 +27,10 @@ use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx,
use craft_ui::text::TextField;
use egui::{ColorImage, Pos2, Rect, Vec2};
use crate::signature::{MAX_IMAGE_BYTES, MAX_IMAGE_SIDE, MAX_SIGNATURE_CHARS, SavedSignature, SignatureDraft, SignatureImage, SignatureTab};
use crate::signature::{
MAX_SIGNATURE_CHARS, PAPER_CUTOFF, PAPER_FEATHER, PickError, SavedSignature, SignatureDraft, SignatureImage, SignatureTab,
decode_fitted,
};
#[cfg(feature = "screen-testing")]
mod stories;
@@ -71,22 +74,42 @@ craft_ui::words! {
}
}
/// The saved signature and initials, one settings section shared by every document.
/// The saved signature and initials, one settings section shared by every document. Each slot reads on its own: a
/// stored value that does not read (an oversize or corrupt image) leaves that slot `None` and the other loaded.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct SignatureSettings {
/// The saved signature, if any.
#[serde(default, deserialize_with = "lenient_slot")]
pub signature: Option<SavedSignature>,
/// The saved initials, if any.
#[serde(default, deserialize_with = "lenient_slot")]
pub initials: Option<SavedSignature>,
}
/// A stored slot as read: a saved signature (or none), or anything else.
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum Slot {
Good(Option<SavedSignature>),
Bad(serde::de::IgnoredAny),
}
/// Reads a slot, turning a value that does not read into `None`: `Host::setting` defaults the whole section on any
/// error, so one bad image would otherwise drop both slots.
fn lenient_slot<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<SavedSignature>, D::Error> {
Ok(match <Slot as serde::Deserialize>::deserialize(deserializer)? {
Slot::Good(saved) => saved,
Slot::Bad(_ignored) => None,
})
}
impl craft_host::Section for SignatureSettings {
const KEY: &'static str = "signatures";
}
/// Draws a saved signature into `rect` in `color`: strokes scaled from pad units and fitted keeping the pad's shape
/// (at the theme's medium stroke, whatever the rect's size), typed text in the proportional face centred in the
/// (at the theme's medium stroke, whatever the rect's size), typed text in the signature face centred in the
/// rect, an image fitted keeping its aspect. `ctx` holds the image's texture, cached under the image's key.
pub fn paint_signature(ctx: &egui::Context, draw: &Draw<'_>, rect: Rect, signature: &SavedSignature, color: DataColor) {
match signature {
@@ -135,7 +158,7 @@ fn paint_strokes(rect: Rect, strokes: &[Vec<[f32; 2]>], fit: bool, dot: impl Fn(
}
}
/// `label` in the proportional face, as large as fits `rect`, centred.
/// `label` in the signature face, as large as fits `rect`, centred.
fn paint_typed(ctx: &egui::Context, draw: &Draw<'_>, rect: Rect, label: &str, color: DataColor) {
if label.trim().is_empty() {
return;
@@ -167,15 +190,6 @@ fn paint_image(ctx: &egui::Context, draw: &Draw<'_>, rect: Rect, image: &Signatu
draw.texture(Rect::from_center_size(rect.center(), fitted), texture, uv);
}
/// Why a picked image was not taken.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PickError {
/// Unreadable, or not a PNG or JPEG.
Unreadable,
/// More than [`MAX_IMAGE_BYTES`] of file or [`MAX_IMAGE_SIDE`] pixels on a side.
TooLarge,
}
type Decoded = Result<SignatureImage, PickError>;
/// Where a decode job gets its bytes.
@@ -184,22 +198,15 @@ enum Source {
Path(PathBuf),
}
/// Decodes a PNG or JPEG of at most [`MAX_IMAGE_BYTES`] and [`MAX_IMAGE_SIDE`] pixels a side into straight RGBA. The
/// size limits apply while decoding, so an oversize image is refused before its pixels are allocated.
/// Decodes a picked or dropped PNG or JPEG ([`decode_fitted`]: the size caps, the EXIF orientation, the saved size),
/// then makes its paper transparent, so a photo of a signature on white paper keeps only the ink.
fn decode_image(bytes: &[u8]) -> Decoded {
if bytes.len() > MAX_IMAGE_BYTES {
return Err(PickError::TooLarge);
}
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| PickError::Unreadable)?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_IMAGE_SIDE);
limits.max_image_height = Some(MAX_IMAGE_SIDE);
reader.limits(limits);
let decoded = reader
.decode()
.map_err(|error| if matches!(error, image::ImageError::Limits(_)) { PickError::TooLarge } else { PickError::Unreadable })?
.into_rgba8();
Ok(SignatureImage::new(decoded.width(), decoded.height(), decoded.into_raw()))
decode_fitted(bytes).map(|image| image.remove_white_background(PAPER_CUTOFF, PAPER_FEATHER))
}
/// The first of the files dropped: the pad takes one image.
fn first_file(dropped: Option<&craft_ui::contract::OsFiles>) -> Option<OsFile> {
dropped.and_then(|files| files.files.first().cloned())
}
/// The pixels of `image` for its texture, empty when its buffer does not match its size.
@@ -399,14 +406,16 @@ fn pop_stroke(strokes: &mut Vec<Vec<[f32; 2]>>) -> bool {
/// The Scan tab's content, the app's.
///
/// It is handed the file dropped on the tab this pass.
/// It is handed the file dropped on the window in this pass, and `None` in every other call.
pub type ScanTab = Box<dyn FnMut(&mut egui::Ui, &mut SignatureDraft, Option<OsFile>) + Send>;
/// Acrobat's signature pad on the dialog host: "Create signature" or "Change initials" with the tabs Type (a field over
/// the pad that shows the typed signature), Draw (a pad of strokes, Undo), Image (Browse… a PNG or JPEG up to
/// [`MAX_IMAGE_BYTES`] through `host.files()`, shown fitted to the same pad) and Scan (shown when the app gives a scan hook); Clear; Apply (enabled when [`SignatureDraft::ready`]) and Cancel.
/// Browse… reads and decodes the file on `host.jobs()`; a pick that fails or is too large shows an error under the
/// button.
/// [`MAX_IMAGE_BYTES`](crate::signature::MAX_IMAGE_BYTES) through `host.files()`, or one dropped on the window, shown
/// fitted to the same pad) and Scan (shown when the app gives a scan hook, which is handed a dropped photo); Clear;
/// Apply (enabled when [`SignatureDraft::ready`]) and Cancel. Browse… and a drop read and decode the file on
/// `host.jobs()`, and the paper of the image goes transparent; a file that fails or is too large shows an error under
/// the button.
#[derive(craft_ui::contract::Pattern)]
pub struct SignaturePadDialog {
draft: SignatureDraft,
@@ -455,20 +464,7 @@ impl SignaturePadDialog {
Picked::Paths(paths) => paths.into_iter().next().map(Source::Path),
};
if let Some(source) = source {
let (send, receive) = channel();
let files = host.clone();
host.jobs().spawn(
"signature-image",
Box::new(move || {
let decoded = match source {
Source::Bytes(bytes) => decode_image(&bytes),
Source::Path(path) => files.files().read(&path).map_err(|_| PickError::Unreadable).and_then(|bytes| decode_image(&bytes)),
};
// The dialog may have closed; then nobody reads the answer.
let _ = send.send(decoded);
}),
);
self.decoding = Some(receive);
self.decode(host, source);
}
}
let Some(receive) = &self.decoding else { return };
@@ -490,6 +486,36 @@ impl SignaturePadDialog {
}
}
/// Reads and decodes `source` on `host.jobs()`; [`take_picked`](Self::take_picked) takes the result.
fn decode(&mut self, host: &Host, source: Source) {
let (send, receive) = channel();
let files = host.clone();
host.jobs().spawn(
"signature-image",
Box::new(move || {
let decoded = match source {
Source::Bytes(bytes) => decode_image(&bytes),
Source::Path(path) => files.files().read(&path).map_err(|_| PickError::Unreadable).and_then(|bytes| decode_image(&bytes)),
};
// The dialog may have closed; then nobody reads the answer.
let _ = send.send(decoded);
}),
);
self.decoding = Some(receive);
}
/// Imports a file dropped on the Image tab in place of any pending Browse… pick. A file with neither bytes nor a
/// path (a web drop still being read) is left alone.
fn take_dropped(&mut self, host: &Host, file: OsFile) {
let source = match (file.bytes, file.path) {
(Some(bytes), _) => Source::Bytes(bytes.to_vec()),
(None, Some(path)) => Source::Path(path),
(None, None) => return,
};
self.forget_pick(Some(host));
self.decode(host, source);
}
fn forget_pick(&mut self, host: Option<&Host>) {
self.decoding = None;
if let (Some(ticket), Some(host)) = (self.pick.take(), host) {
@@ -520,6 +546,8 @@ impl StackDialog for SignaturePadDialog {
FooterButton::new(words.cancel.clone(), DialogRole::Cancel),
];
let mut browse = false;
// A file dropped on the Image tab this pass.
let mut dropped: Option<OsFile> = None;
let SignaturePadDialog { draft, scan, open, decoding, error, .. } = self;
let decoding = decoding.is_some();
let shown = Dialog::new(title.clone()).opened(Bind::bound(open)).buttons(buttons).show(ui, |ui, _| {
@@ -544,22 +572,25 @@ impl StackDialog for SignaturePadDialog {
DrawPad::new(words.draw_tab.clone(), Bind::bound(&mut draft.strokes)).show(ui);
}
SignatureTab::Image => {
Text::new(words.image_hint.clone()).shade(Shade::Muted).show(ui);
if clicked(&Button::new(words.browse.clone()).icon(craft_behavior::IconId::new("folder")).loading(decoding).show(ui)) {
browse = true;
}
if let Some(error) = *error {
let word = match error {
PickError::Unreadable => &words.image_failed,
PickError::TooLarge => &words.image_too_large,
};
Notice::new(Tone::Bad, word.clone()).layout(NoticeLayout::Inline).show(ui);
}
DrawPad::image(words.image_tab.clone(), draft.image.as_ref()).show(ui);
let veil = DropVeil::new(words.drop_image.clone()).show(ui, |ui, _| {
Text::new(words.image_hint.clone()).shade(Shade::Muted).show(ui);
if clicked(&Button::new(words.browse.clone()).icon(craft_behavior::IconId::new("folder")).loading(decoding).show(ui)) {
browse = true;
}
if let Some(error) = *error {
let word = match error {
PickError::Unreadable => &words.image_failed,
PickError::TooLarge => &words.image_too_large,
};
Notice::new(Tone::Bad, word.clone()).layout(NoticeLayout::Inline).show(ui);
}
DrawPad::image(words.image_tab.clone(), draft.image.as_ref()).show(ui);
});
dropped = first_file(veil.output.dropped.as_ref());
}
SignatureTab::Scan => {
if let Some(tab) = scan.as_mut() {
tab(ui, draft, None); // P3(pdf-forms-w1): FM-PF3 (the writer hands over the dropped file)
DropVeil::new(words.drop_photo.clone()).show(ui, |ui, files| tab(ui, draft, first_file(files)));
}
}
}
@@ -579,6 +610,9 @@ impl StackDialog for SignaturePadDialog {
PickRequest::open("signature-image").title(words.browse_title.as_str()).filter(words.image_filter.as_str(), &["png", "jpg", "jpeg"]);
self.pick = Some(host.files().pick(request));
}
if let (Some(file), Some(host)) = (dropped, &host) {
self.take_dropped(host, file);
}
let output = shown.output;
match output.picked {
Some(0) => {
+106 -8
View File
@@ -1,9 +1,12 @@
//! Stories of the signature pad.
use super::{DrawPad, SignaturePadDialog};
use crate::signature::SignatureDraft;
use craft_ui::contract::{Bind, Show as _, Validity};
use crate::signature::{SignatureDraft, SignatureImage, SignatureTab};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, OsFile, Show as _, Validity, clicked};
use craft_ui::dialog::StackDialog as _;
use craft_ui::display::Text;
use craft_ui::popover::DropVeil;
use craft_ui::runtime::env::Message;
use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story};
use egui::Ui;
@@ -38,18 +41,113 @@ impl std::fmt::Debug for Held {
}
}
/// The dialog on the Type tab.
fn dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let held =
data.value("pad", Held(std::sync::Arc::new(std::sync::Mutex::new(SignaturePadDialog::new(SignatureDraft::new(false, "Ana Reyes")))))).clone();
/// What a story's dialog starts from.
struct Start {
draft: fn() -> SignatureDraft,
/// Whether the dialog has a Scan tab, with [`scan_stub`] as the app's content.
scan: bool,
}
impl Start {
fn dialog(&self) -> Held {
let pad = SignaturePadDialog::new((self.draft)());
let pad = if self.scan { pad.scan(scan_stub) } else { pad };
Held(std::sync::Arc::new(std::sync::Mutex::new(pad)))
}
}
/// The dialog `start` makes, closed until its opener button is pressed. Apply or Cancel closes it, and the opener then
/// starts a fresh one.
fn dialog(ui: &mut Ui, data: &mut StoryData, start: &Start) -> StoryOutput {
if !*data.value("open", false) {
if clicked(&Button::new("Open signature pad").show(ui)) {
*data.value("pad", None::<Held>) = Some(start.dialog());
*data.value("open", false) = true;
}
return StoryOutput::default();
}
let Some(held) = data.value("pad", None::<Held>).clone() else {
*data.value("open", false) = false;
return StoryOutput::default();
};
let mut stack = craft_ui::dialog::DialogStack::default();
let mut pad = held.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
stack.push(pad.id(), None);
let _ = pad.show(ui, &stack);
if pad.show(ui, &stack).is_some() {
*data.value("open", false) = false;
}
StoryOutput::default()
}
/// The app's Scan tab as a stub: a line of text, and a dropped photo stands in for a cleaned scan.
fn scan_stub(ui: &mut Ui, draft: &mut SignatureDraft, dropped: Option<OsFile>) {
Text::new("The app's scan view: drop a photo of a signature on paper.").show(ui);
if dropped.is_some() {
draft.image = Some(ink_sample());
}
}
/// A picked image: a dark diagonal stroke on clear ground, 120 × 40 pixels.
fn ink_sample() -> SignatureImage {
let (width, height) = (120_u32, 40_u32);
let mut rgba = vec![0_u8; (width * height * 4) as usize];
for x in 0..width {
let y = (x * (height - 1)) / (width - 1);
for dy in 0..3 {
let row = (y + dy).min(height - 1);
let at = ((row * width + x) * 4) as usize;
rgba[at..at + 4].copy_from_slice(&[20, 30, 60, 255]);
}
}
SignatureImage::new(width, height, rgba)
}
#[story(SignaturePadDialog, covers = [], drive = Drive::Never)]
fn signature_pad_type(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
dialog(ui, data)
dialog(ui, data, &Start { draft: || SignatureDraft::new(false, "Ana Reyes"), scan: false })
}
/// A name too wide for the pad at full height shrinks to its width and stays on one line.
#[story(SignaturePadDialog, covers = [], drive = Drive::Never)]
fn signature_pad_typed_long_name(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let draft = || SignatureDraft::new(false, "María de los Ángeles Concepción Fernández-Villaseñor");
dialog(ui, data, &Start { draft, scan: false })
}
#[story(SignaturePadDialog, covers = [], drive = Drive::Never)]
fn signature_pad_draw(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let draft = || SignatureDraft {
tab: SignatureTab::Draw,
strokes: vec![vec![[0.1, 0.6], [0.2, 0.3], [0.3, 0.7], [0.45, 0.35], [0.6, 0.65]], vec![[0.65, 0.5], [0.9, 0.45]]],
..SignatureDraft::default()
};
dialog(ui, data, &Start { draft, scan: false })
}
#[story(SignaturePadDialog, covers = [], drive = Drive::Never)]
fn signature_pad_image(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let draft = || SignatureDraft { tab: SignatureTab::Image, image: Some(ink_sample()), ..SignatureDraft::default() };
dialog(ui, data, &Start { draft, scan: false })
}
#[story(SignaturePadDialog, covers = [], drive = Drive::Never)]
fn signature_pad_scan(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let draft = || SignatureDraft { tab: SignatureTab::Scan, ..SignatureDraft::default() };
dialog(ui, data, &Start { draft, scan: true })
}
/// The Image tab over a window that takes files too: a file dragged in shows the pad's veil, and the pad, not the
/// window, imports it.
#[story(SignaturePadDialog, covers = [], drive = Drive::Never)]
fn signature_pad_drop(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let window = DropVeil::new("Open files").show(ui, |ui, _| {
Text::new("Drag a PNG or JPEG over the window.").show(ui);
});
if window.output.dropped.is_some() {
*data.value("window_took", false) = true;
}
let draft = || SignatureDraft { tab: SignatureTab::Image, ..SignatureDraft::default() };
let shown = dialog(ui, data, &Start { draft, scan: false });
let readout = if *data.value("window_took", false) { "The window took a drop" } else { "The window took no drop" };
shown.readout(readout)
}
+1 -1
View File
@@ -3,4 +3,4 @@
mod annotate;
mod collab;
mod comments;
mod note_popup;
mod signature;
+274
View File
@@ -0,0 +1,274 @@
//! The signature pad: stroke undo, image import by Browse… and by a drop, and the stored form of the settings.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use base64::{Engine as _, engine::general_purpose::STANDARD};
use craft_host::{AppInfo, Host, InlineJobs, Jobs, ManualJobs, MemorySections, Picked, ScriptedFiles, Section};
use craft_review::signature::{MAX_IMAGE_BYTES, SavedSignature, SignatureDraft, SignatureImage, SignatureTab};
use craft_review::ui::{SignaturePadDialog, SignatureSettings};
use craft_ui::contract::Role;
use craft_ui::dialog::{DialogStack, StackDialog as _};
use craft_ui::popover::DropVeil;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::{Fixture, Frames, trial};
use egui::{Key, Modifiers, Pos2, Rect, Ui, vec2};
/// Five pixels of a photographed signature, straight RGBA: white paper, off-white paper, ink, a grey edge and
/// half-transparent ink.
const PHOTO: [u8; 20] = [255, 255, 255, 255, 250, 248, 252, 255, 10, 20, 30, 255, 230, 235, 240, 255, 0, 0, 0, 128];
/// Asserts `rgba` is [`PHOTO`] with its paper made transparent: both papers clear, the ink opaque, the grey edge
/// faded between clear and opaque, the half-transparent ink not raised, and no colour changed.
fn assert_paper_gone(rgba: &[u8]) {
assert_eq!(rgba.len(), PHOTO.len(), "the image keeps its size");
for (was, now) in PHOTO.chunks(4).zip(rgba.chunks(4)) {
assert_eq!(was[..3], now[..3], "the colours stay");
}
let alpha = |pixel: usize| rgba[pixel * 4 + 3];
assert_eq!(alpha(0), 0, "white paper goes clear");
assert_eq!(alpha(1), 0, "off-white paper goes clear");
assert_eq!(alpha(2), 255, "ink stays opaque");
assert!(alpha(3) > 0 && alpha(3) < 255, "the grey edge fades: {}", alpha(3));
assert!(alpha(4) > 0 && alpha(4) <= 128, "half-transparent ink is not raised: {}", alpha(4));
}
/// The dialog under test and the context it last ran in.
struct Pad {
dialog: SignaturePadDialog,
stack: DialogStack,
ctx: Option<egui::Context>,
}
fn pad(draft: SignatureDraft) -> Rc<RefCell<Pad>> {
let dialog = SignaturePadDialog::new(draft);
let mut stack = DialogStack::default();
stack.push(dialog.id(), None);
Rc::new(RefCell::new(Pad { dialog, stack, ctx: None }))
}
/// Shows the dialog in `ui`.
fn show(pad: &RefCell<Pad>, ui: &mut Ui) {
let mut pad = pad.borrow_mut();
let Pad { dialog, stack, ctx } = &mut *pad;
*ctx = Some(ui.ctx().clone());
let _ = dialog.show(ui, stack);
}
/// What Apply would save now; `None` while Apply is disabled.
fn saved(pad: &RefCell<Pad>) -> Option<SavedSignature> {
let mut pad = pad.borrow_mut();
let ctx = pad.ctx.clone().expect("the dialog has run");
pad.dialog.confirm(&ctx).map(|result| result.signature)
}
/// The strokes Apply would save on the Draw tab.
fn strokes(pad: &RefCell<Pad>) -> Vec<Vec<[f32; 2]>> {
match saved(pad) {
Some(SavedSignature::Drawn(strokes)) => strokes,
other => panic!("the Draw tab saves strokes, not {other:?}"),
}
}
fn host(files: ScriptedFiles, jobs: Arc<dyn Jobs>) -> Arc<Host> {
Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).files(Arc::new(files)).jobs(jobs).build())
}
/// `rgba` (`width` × `height`) as a PNG file.
fn png(rgba: &[u8], width: u32, height: u32) -> Vec<u8> {
use image::ImageEncoder as _;
let mut out = Vec::new();
let encoded = image::codecs::png::PngEncoder::new(&mut out).write_image(rgba, width, height, image::ExtendedColorType::Rgba8);
encoded.expect("the trial's image encodes");
out
}
/// A drag of a few points from `from` by `by`: a visible stroke.
fn stroke(fx: &mut Fixture, from: Pos2, by: egui::Vec2) {
fx.drag_at(from, by);
}
/// A press that moves past the drag slop in one step and is released where it stopped: a stroke of one point, a bare
/// dot.
fn dot(fx: &mut Fixture, at: Pos2) {
let to = at + vec2(12.0, 0.0);
fx.frame(vec![moved(at)]).frame(vec![press(at)]).frame(vec![moved(to)]).frame(vec![release(to)]).frame(Vec::new());
}
/// Undo takes back the last visible stroke and the bare dots after it, from the Undo button and from Cmd+Z on the
/// pad alike; the earlier stroke stays.
#[trial]
fn undo_takes_back_one_stroke_and_skips_bare_dots() {
let pad = pad(SignatureDraft { tab: SignatureTab::Draw, ..SignatureDraft::default() });
let shown = Rc::clone(&pad);
let mut fx = Fixture::new(move |ui| show(&shown, ui));
fx.room(vec2(900.0, 900.0)).settle();
let area: Rect = fx
.by_role(Role::IMAGE)
.into_iter()
.map(|target| target.rect)
.max_by(|a, b| a.area().total_cmp(&b.area()))
.expect("the Draw tab shows the pad");
let at = |x: f32, y: f32| Pos2::new(area.left() + area.width() * x, area.top() + area.height() * y);
let along = vec2(area.width() * 0.6, area.height() * 0.1);
stroke(&mut fx, at(0.1, 0.2), along);
let first = strokes(&pad);
assert_eq!(first.len(), 1, "a drag draws one stroke: {first:?}");
assert!(first[0].len() > 1, "the drag's stroke is visible: {first:?}");
stroke(&mut fx, at(0.1, 0.5), along);
dot(&mut fx, at(0.2, 0.8));
let drawn = strokes(&pad);
assert_eq!(drawn.iter().map(Vec::len).filter(|&len| len == 1).count(), 1, "the dot is one point: {drawn:?}");
assert_eq!(drawn.len(), 3, "two strokes and a dot: {drawn:?}");
let undo = fx.by_label("Undo").expect("the Draw tab has Undo");
fx.click(&undo).settle();
assert_eq!(strokes(&pad), first, "the Undo button takes back the dot and the second stroke");
stroke(&mut fx, at(0.15, 0.55), along);
dot(&mut fx, at(0.4, 0.85));
assert_eq!(strokes(&pad).len(), 3, "a stroke and a dot are drawn again");
fx.key(Key::Z, Modifiers::COMMAND).settle();
assert_eq!(strokes(&pad), first, "Cmd+Z on the pad takes back the dot and the stroke before it");
}
/// An image picked with Browse… comes back with its paper transparent and its ink opaque.
#[trial]
fn an_imported_image_loses_its_paper_and_keeps_its_ink() {
let files = ScriptedFiles::answering([Picked::Paths(vec!["ink.png".into()])]).with_file("ink.png", png(&PHOTO, 5, 1));
let pad = pad(SignatureDraft { tab: SignatureTab::Image, ..SignatureDraft::default() });
let shown = Rc::clone(&pad);
let mut fx = Fixture::new(move |ui| show(&shown, ui));
fx.host(host(files, Arc::new(InlineJobs))).room(vec2(900.0, 900.0)).settle();
let browse = fx.by_label("Browse…").expect("the Image tab has Browse…");
fx.click(&browse).settle();
let Some(SavedSignature::Image(image)) = saved(&pad) else { panic!("the picked image is the draft's: {:?}", saved(&pad)) };
assert_eq!((image.width(), image.height()), (5, 1));
assert_paper_gone(image.rgba());
}
/// A file dropped while the Image tab shows is imported by the pad, once, and the window's own veil gets nothing.
/// Every frame runs two passes: the second has no input of its own, so a drop taken again would import twice.
#[trial]
fn a_file_dropped_on_the_pad_is_imported_and_the_window_gets_none() {
let jobs = Arc::new(ManualJobs::new());
let files = ScriptedFiles::new().with_file("photo.png", png(&PHOTO, 5, 1));
let pad = pad(SignatureDraft { tab: SignatureTab::Image, ..SignatureDraft::default() });
let window_drops = Rc::new(Cell::new(0_usize));
let (shown, seen) = (Rc::clone(&pad), Rc::clone(&window_drops));
let mut frame = move |ui: &mut Ui| {
let window = DropVeil::new("Open files").show(ui, |_, _| {});
if window.output.dropped.is_some() {
seen.set(seen.get() + 1);
}
show(&shown, ui);
if ui.ctx().current_pass_index() == 0 {
ui.ctx().request_discard("the trial reruns the pass");
}
};
let mut frames = Frames::new();
frames.screen(vec2(900.0, 900.0));
frames.host(host(files, jobs.clone()));
frames.idle(3, &mut frame);
let over = Pos2::new(450.0, 450.0);
frames.hover_files(&["photo.png"]);
frames.frame(vec![moved(over)], &mut frame);
frames.idle(1, &mut frame);
frames.drop_files(&["photo.png"]);
frames.frame(vec![moved(over)], &mut frame);
frames.idle(1, &mut frame);
assert_eq!(jobs.run_all(), 1, "the dropped file is read once");
frames.idle(2, &mut frame);
assert_eq!(window_drops.get(), 0, "the window's veil gets no drop while the pad takes it");
let Some(SavedSignature::Image(image)) = saved(&pad) else { panic!("the dropped image is the draft's: {:?}", saved(&pad)) };
assert_paper_gone(image.rgba());
}
/// A drop reaches a veil's body in the pass that receives it and in no other: the frame's second pass has no input of
/// its own, and later frames have no drop.
#[trial]
fn a_drop_reaches_the_veils_body_in_the_pass_that_receives_it() {
let seen = Rc::new(RefCell::new(Vec::<usize>::new()));
let log = Rc::clone(&seen);
let mut frame = move |ui: &mut Ui| {
let pass = ui.ctx().current_pass_index();
DropVeil::new("Open files").show(ui, |_, dropped| {
if dropped.is_some() {
log.borrow_mut().push(pass);
}
});
if pass == 0 {
ui.ctx().request_discard("the trial reruns the pass");
}
};
let mut frames = Frames::new();
frames.screen(vec2(900.0, 900.0));
frames.idle(3, &mut frame);
assert!(seen.borrow().is_empty(), "no body sees a drop before one happens");
let over = Pos2::new(450.0, 450.0);
frames.hover_files(&["photo.png"]);
frames.frame(vec![moved(over)], &mut frame);
frames.idle(1, &mut frame);
assert!(seen.borrow().is_empty(), "hovering files are not a drop");
frames.drop_files(&["photo.png"]);
frames.frame(vec![moved(over)], &mut frame);
let at_drop = seen.borrow().clone();
assert!(!at_drop.is_empty(), "the body sees the drop in the pass that receives it");
assert!(at_drop.iter().all(|&pass| pass == 0), "the rerun pass sees no drop: {at_drop:?}");
frames.idle(3, &mut frame);
assert_eq!(*seen.borrow(), at_drop, "later frames see no drop");
}
/// What a settings file can hold under the signatures key: the form [`SignatureSettings`] writes, with any text in it.
#[derive(Default, serde::Serialize, serde::Deserialize)]
struct Stored {
signature: Option<StoredSlot>,
initials: Option<StoredSlot>,
}
#[derive(Clone, serde::Serialize, serde::Deserialize)]
enum StoredSlot {
Typed(String),
Image { png: String },
}
impl Section for Stored {
const KEY: &'static str = <SignatureSettings as Section>::KEY;
}
/// A saved image is stored as base64 PNG text and reads back equal; text over the cap, text that is not a PNG and
/// text that is not base64 each leave the signature `None` while the initials still load.
#[trial]
fn a_saved_image_round_trips_as_png_and_an_oversize_one_is_refused() {
let host = Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).settings(Arc::new(MemorySections::default())).build();
let initials = SavedSignature::Typed("AR".into());
let mut settings = SignatureSettings::default();
settings.signature = Some(SavedSignature::Image(SignatureImage::new(5, 1, PHOTO.to_vec())));
settings.initials = Some(initials.clone());
host.set_setting(&settings);
let stored = host.setting::<Stored>();
assert!(matches!(&stored.initials, Some(StoredSlot::Typed(text)) if text == "AR"), "the initials are stored as text");
let Some(StoredSlot::Image { png }) = stored.signature else { panic!("the image is stored as {{ png }}") };
let bytes = STANDARD.decode(png).expect("the stored text is base64");
assert!(bytes.starts_with(b"\x89PNG\r\n\x1a\n"), "the stored bytes are a PNG");
assert_eq!(host.setting::<SignatureSettings>(), settings, "the settings read back as written");
let over_cap = "A".repeat(MAX_IMAGE_BYTES.div_ceil(3) * 4 + 4);
let cases = [
("text over the cap", over_cap),
("a corrupt PNG", STANDARD.encode(b"\x89PNG\r\n\x1a\nnot a picture")),
("not base64", "*** no ***".to_owned()),
];
for (case, png) in cases {
host.set_setting(&Stored { signature: Some(StoredSlot::Image { png }), initials: Some(StoredSlot::Typed("AR".into())) });
let read = host.setting::<SignatureSettings>();
assert_eq!(read.signature, None, "{case} is refused");
assert_eq!(read.initials, Some(initials.clone()), "{case} leaves the initials loaded");
}
}
+4 -1
View File
@@ -32,6 +32,9 @@ use crate::runtime::frame;
use crate::runtime::layout_memory;
use egui::{Context, FontDefinitions, FontFamily};
/// The egui family name of [`FontRef::signature`]; the stack registers it in every build.
const SIGNATURE_FAMILY: &str = "signature";
/// A font handle: the family a run is set in.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FontRef(FontFamily);
@@ -50,7 +53,7 @@ impl FontRef {
/// The signature face: always a family egui knows. Its chain is the craft-fonts faces of the signature role,
/// then the proportional chain; without one in the build, the proportional chain.
pub fn signature() -> FontRef {
todo!("FM-PF1a")
FontRef::named(SIGNATURE_FAMILY)
}
/// A family registered under `name`.
+14 -6
View File
@@ -21,7 +21,9 @@
//! first face's baseline, scaled down only if a glyph would leave the row ([`CjkRows::Fit`]).
//! Monospace, and every family declared [`Family::monospaced`], always keeps its Latin face first. A
//! craft face with the `mono` role (craft-fonts' monospace face) leads those families when the app
//! embeds it, ahead of egui's Hack.
//! embeds it, ahead of egui's Hack. The same way, a craft face with the `signature` role leads the
//! [`FontRef::signature`] family, which every stack registers and which falls back to the
//! proportional chain; no other family takes that face.
//! On the suite's egui fork, the other craft faces and installed text faces used as fallbacks sit
//! on the row's baseline and rows grow to fit them by themselves; emoji and symbol faces stay
//! centred.
@@ -42,7 +44,7 @@ mod install;
use std::sync::Arc;
use craft_fonts_build::{EmbeddedFace, ServedFace};
use craft_fonts_build::{EmbeddedFace, MONO_ROLE, SIGNATURE_ROLE, ServedFace};
use craft_theme::InterfaceFont;
use egui::{FontData, FontDefinitions, FontFamily, FontProvider};
@@ -71,7 +73,6 @@ pub struct Family {
lead: Option<String>,
monospaced: bool,
/// The craft-fonts face role that leads the family's chain.
#[allow(dead_code)] // P3(pdf-forms-w1): FM-PF1a
lead_role: Option<&'static str>,
}
@@ -88,7 +89,13 @@ impl Family {
/// egui's monospace family, e.g. to set its weight.
pub fn monospace() -> Self {
Self::of(FontRef::monospace(), true)
Self { lead_role: Some(MONO_ROLE), ..Self::of(FontRef::monospace(), true) }
}
/// The family of [`FontRef::signature`], led by craft-fonts' signature face; it orders languages as the
/// proportional family does.
pub(crate) fn signature() -> Self {
Self { lead_role: Some(SIGNATURE_ROLE), ..Self::of(FontRef::signature(), false) }
}
fn of(family: FontRef, monospaced: bool) -> Self {
@@ -110,10 +117,11 @@ impl Family {
}
/// Lay the family out as egui's monospace one, e.g. `Family::named("mono").monospaced()` for
/// an app's own code face: its app face stays first in every UI language, and a family without
/// app faces starts with egui's monospace faces.
/// an app's own code face: its app face stays first in every UI language, a family without
/// app faces starts with egui's monospace faces, and craft-fonts' monospace face leads it.
pub fn monospaced(mut self) -> Self {
self.monospaced = true;
self.lead_role = Some(MONO_ROLE);
self
}
}
+34 -20
View File
@@ -1,6 +1,6 @@
//! Building the chains: for each family, which faces come in which order.
use craft_fonts_build::{EmbeddedFace, MONO_ROLE, ServedFace};
use craft_fonts_build::{EmbeddedFace, SIGNATURE_ROLE, ServedFace};
use craft_i18n::Han;
use craft_theme::InterfaceFont;
use egui::{FontData, FontDefinitions, FontFamily};
@@ -58,6 +58,12 @@ fn han_region(face: &EmbeddedFace) -> Option<Han> {
})
}
/// Whether `face` is craft-fonts' signature face, which draws only in the signature family's lead: as a fallback for a
/// script it would set interface text in handwriting.
fn signature_face(face: &EmbeddedFace) -> bool {
face.role == Some(SIGNATURE_ROLE)
}
/// `0` for the style a family of `weight` wants, `1` for an acceptable stand-in.
fn style_rank(face: &EmbeddedFace, weight: u16) -> Option<u8> {
let regular = face.style.eq_ignore_ascii_case("regular");
@@ -226,9 +232,10 @@ impl UiFonts<'_> {
stack
}
/// Proportional and Monospace, every family an app face names, then the declared families.
/// Proportional, Monospace and the signature family, every family an app face names, then the declared families.
fn family_specs(&self) -> Vec<Family> {
let mut specs = vec![Family::proportional(), Family::monospace()];
// The signature family goes in every build: egui fails on a `FontFamily::Name` it doesn't know.
let mut specs = vec![Family::proportional(), Family::monospace(), Family::signature()];
// With no face of its own for the interface, the app gets the suite's, whose semibold roles draw in Inter SemiBold.
if !self.app_faces.iter().any(|face| face.families.contains(&FontFamily::Proportional)) {
specs.push(Family::named(super::SEMIBOLD).weight(600));
@@ -278,8 +285,13 @@ impl UiFonts<'_> {
others.extend(self.candidates(script, han, weight));
}
}
let mut rest: Vec<(u8, usize)> =
self.craft_faces.iter().enumerate().filter_map(|(i, face)| style_rank(face, weight).map(|rank| (rank, i))).collect();
let mut rest: Vec<(u8, usize)> = self
.craft_faces
.iter()
.enumerate()
.filter(|(_, face)| !signature_face(face))
.filter_map(|(i, face)| style_rank(face, weight).map(|rank| (rank, i)))
.collect();
rest.sort();
others.extend(rest.into_iter().map(|(_, i)| i));
@@ -296,21 +308,23 @@ impl UiFonts<'_> {
.collect();
base.splice(0..0, self.system_ui_slot(&family.family));
// craft-fonts' monospace face leads a monospaced family when the build embeds it; Hack follows as the fallback.
let mono: Vec<usize> = if family.monospaced {
let mut mono: Vec<(u8, usize)> = self
.craft_faces
.iter()
.enumerate()
.filter(|(_, face)| face.role == Some(MONO_ROLE))
.filter_map(|(i, face)| style_rank(face, weight).map(|rank| (rank, i)))
.collect();
mono.sort();
mono.into_iter().map(|(_, i)| i).collect()
} else {
Vec::new()
// The craft-fonts faces of the family's role lead it when the build embeds them (the monospace face ahead of
// Hack, the signature face ahead of the proportional chain).
let role_lead: Vec<usize> = match family.lead_role {
Some(role) => {
let mut led: Vec<(u8, usize)> = self
.craft_faces
.iter()
.enumerate()
.filter(|(_, face)| face.role == Some(role))
.filter_map(|(i, face)| style_rank(face, weight).map(|rank| (rank, i)))
.collect();
led.sort();
led.into_iter().map(|(_, i)| i).collect()
}
None => Vec::new(),
};
let mut configured = craft(mono);
let mut configured = craft(role_lead);
configured.extend(craft(lead));
if language_first {
configured.extend(craft(language));
@@ -372,7 +386,7 @@ impl UiFonts<'_> {
.craft_faces
.iter()
.enumerate()
.filter(|(_, face)| covers(face.scripts, script))
.filter(|(_, face)| covers(face.scripts, script) && !signature_face(face))
.filter_map(|(i, face)| {
let style = style_rank(face, weight)?;
let region = if script == "Hani" { region_rank(han_region(face), han) } else { 0 };
@@ -138,6 +138,49 @@ fn a_craft_face_with_the_mono_role_leads_the_monospace_family() {
assert_eq!(without.chain(&FontRef::monospace()).first(), default_head.as_ref(), "without the mono face the default monospace face leads");
}
/// craft-fonts' signature face leads the signature family and draws in no other; without it the signature family is
/// the proportional chain, so `FontRef::signature()` always names a family egui knows.
#[trial]
fn a_craft_face_with_the_signature_role_leads_only_the_signature_family() {
const SIGNATURE: EmbeddedFace = EmbeddedFace {
family: "Dancing Script",
style: "Regular",
scripts: &["Latn"],
bytes: &[],
index: 0,
role: Some(craft_fonts_build::SIGNATURE_ROLE),
};
const MONO: EmbeddedFace = EmbeddedFace {
family: "JetBrains Mono",
style: "Regular",
scripts: &["Latn"],
bytes: &[],
index: 0,
role: Some(craft_fonts_build::MONO_ROLE),
};
let build = |faces: &[EmbeddedFace]| {
UiFonts::new(&I18nScripts).craft_faces(faces).languages(&["en", "vi"]).ui_language("vi").system_fonts(SystemFonts::Off).stack()
};
let name = "Dancing Script Regular";
let with: Vec<EmbeddedFace> = CRAFT.iter().copied().chain([SIGNATURE, MONO]).collect();
let stack = build(&with);
let signature = stack.chain(&FontRef::signature());
assert_eq!(signature.first().map(String::as_str), Some(name), "the signature face leads the signature family");
assert!(!signature.iter().any(|face| face == "JetBrains Mono Regular"), "the mono face doesn't lead the signature family");
let proportional = stack.chain(&FontRef::proportional());
assert!(signature.len() > 1 && signature[1..].iter().all(|face| proportional.contains(face)), "the proportional chain follows");
for family in [FontRef::proportional(), FontRef::monospace()] {
// A Vietnamese UI asks Latin faces for the letters its base faces lack: the signature face isn't one of them.
assert!(!stack.chain(&family).iter().any(|face| face == name), "{family:?} has no signature face");
}
assert_eq!(stack.chain(&FontRef::monospace()).first().map(String::as_str), Some("JetBrains Mono Regular"), "the mono lead stays");
let without = build(CRAFT);
assert!(!without.chain(&FontRef::signature()).is_empty(), "the signature family is registered without its face");
assert_eq!(without.chain(&FontRef::signature()), without.chain(&FontRef::proportional()), "without its face it is the proportional chain");
}
#[trial]
fn variable_faces_draw_at_regular_weight() {
// The Arabic test face's default instance is Thin (100), like many variable system fonts.
+23 -9
View File
@@ -2,15 +2,16 @@
//! dims the body, frames it and shows a card with the label; a drop is reported in the output.
use crate::contract::{
Access, Accessible as _, Common, Component, Container, ContainerProps, Cx, DropMark, DropOperation, MeasureCx, NoValue, OsFiles, Outcome, Pad,
PaintUi, PartsCx, Pointer as _, Politeness, Props as _, Remember as _, Role, Sizing, WindowDropTarget, WordSetCx as _,
Access, Accessible as _, Common, Component, Container, ContainerProps, Cx, DropMark, DropOperation, Inner, MeasureCx, NoValue, OsFiles, Outcome,
Pad, PaintUi, PartsCx, Pointer as _, Politeness, Props as _, Remember as _, Role, ShowContainer, Sizing, WindowDropTarget, WordSetCx as _,
};
use crate::display::Text;
use crate::runtime::drag;
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, Corners, Insets, Stateful, StyleCx, SurfaceKind, SurfaceLook, TypeRole, UiTokens};
use craft_behavior::{Metrics, Proposal, Sense};
use egui::{Rect, Response};
use egui::{Rect, Response, Ui};
use std::sync::{Arc, Mutex, PoisonError};
#[cfg(feature = "testing")]
mod stories;
@@ -142,7 +143,7 @@ impl WindowDropTarget<OsFiles> for WholeWindow {
struct Announced(bool);
/// A body that dims and shows `label` on a card while the OS drags files over the window, and reports the files
/// dropped on the window.
/// dropped on the window. The body gets the files dropped in the pass that runs it, so it acts on them in that pass.
#[derive(crate::contract::Component)]
#[component(container)]
pub struct DropVeil {
@@ -151,7 +152,9 @@ pub struct DropVeil {
#[container]
props: ContainerProps,
hovering: bool,
dropped: Option<OsFiles>,
/// The files dropped this pass: `update` writes them before the body runs, the body and `finish` read them. A veil
/// is built anew every pass, so nothing outlives it.
dropped: Arc<Mutex<Option<OsFiles>>>,
/// The card's rect, from the card child's measured size.
card: Option<Rect>,
}
@@ -160,7 +163,16 @@ impl DropVeil {
/// A veil saying `label` ("Import 3 photos") while files hover.
pub fn new(label: impl Into<Label>) -> Self {
let props = ContainerProps::new().sizing(Sizing::Fill).pad(Pad::None);
DropVeil { common: Common::new(), props, hovering: false, dropped: None, card: None }.label(label)
DropVeil { common: Common::new(), props, hovering: false, dropped: Arc::default(), card: None }.label(label)
}
/// Shows the veil over `body`, which gets the files dropped on the window in this pass, if any.
pub fn show<R>(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, Option<&OsFiles>) -> R) -> Inner<DropVeilOutput, R> {
let dropped = Arc::clone(&self.dropped);
ShowContainer::show(self, ui, move |ui, _| {
let files = dropped.lock().unwrap_or_else(PoisonError::into_inner).clone();
body(ui, files.as_ref())
})
}
}
@@ -195,9 +207,10 @@ impl Component for DropVeil {
let held = drag::active::<OsFiles>(&cx.ctx).is_some_and(|files| !files.files.is_empty());
let target = WholeWindow::new(cx.rect);
let (id, ordinal) = (cx.id, drag::next_ordinal(&cx.ctx, cx.id));
self.dropped = cx.window_drop_target::<OsFiles, _>(&target);
let dropped = cx.window_drop_target::<OsFiles, _>(&target);
// The veil shows only while it is the target that would take the drop.
self.hovering = held && self.dropped.is_none() && drag::winning(&cx.ctx, id, ordinal);
self.hovering = held && dropped.is_none() && drag::winning(&cx.ctx, id, ordinal);
*self.dropped.lock().unwrap_or_else(PoisonError::into_inner) = dropped;
let announced = cx.memory::<Announced>();
let first = self.hovering && !announced.0;
announced.0 = self.hovering;
@@ -219,7 +232,8 @@ impl Component for DropVeil {
}
fn finish(self, cx: Cx<'_, Self>) -> DropVeilOutput {
DropVeilOutput { response: cx.response.clone(), dropped: self.dropped }
let dropped = self.dropped.lock().unwrap_or_else(PoisonError::into_inner).take();
DropVeilOutput { response: cx.response.clone(), dropped }
}
}
@@ -2,7 +2,7 @@
use super::DropVeil;
use crate::choice::Checkbox;
use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use crate::contract::{Bind, Props as _, Show as _};
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;