mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 10:48:15 +01:00
Merge craft-libs main 716a24ce4 into the port's framework
Conflicts and how each was resolved: - crates/text/src/ui/spelling.rs: upstream463af6d25makes Done the default button (close_on_enter(true)); the port's buttons disable Change All and Add for a repeated word and the dialog can be modeless. Both kept: the port's button list and modeless switch, with upstream's close_on_enter. - crates/ui-canvas/src/canvas/mod.rs: upstream adds Settled::wheel_token (wheel claims, 988e77876/66923d268); the port adds Settled::zoomed. Both fields kept. - crates/ui-canvas/tests/it/canvas/tools.rs: import union (upstream's ToolReadout, the port's ViewFit and ViewRequest). - crates/ui-contract/src/runtime/egui/alt_code.rs: the two sides disagree. The port (c064eb616,8577b382a) let only keypad digits enter a code, so an unclaimed main-row Alt+digit stayed a shortcut. Upstream (744812cbf,9f649dc80,4b1d442bb) keeps top-row digits composing codes and builds the Windows carrier and echo handling on a top_row flag. Took upstream's design and file. An app's Alt+digit shortcut now has to be claimed by the key target (upstream's `claimed` path), as it already is for the keypad. - crates/ui-contract/tests/it/runtime/alt_code.rs: upstream's helpers (keypad(), top_row_code()) replace the port's on_keypad/send_main_row. All of upstream's assertions are kept. The port's assertion that an unclaimed main-row Alt+5 reaches egui became "a claimed top-row Alt+3 reaches egui", which carries the port's shortcut need into upstream's design. The port's assertion that main-row digits type nothing is dropped: it contradicts upstream's "the text after a top-row code is typed as normal" (éй). - crates/ui-contract/src/runtime/focus.rs: each side added a function (the port's text_root, upstream's surrender_stop). Both kept. - crates/ui-widgets/src/list/row/placement.rs: upstream adds TreeIndent (a host's indent step) and ThumbSize::Custom; the port adds the side-menu place row (larger icon, roomy pad, section gap, taller row) and ThumbAspect. Merged: the port's place sizes with upstream's TreeIndent step, and the imports combined. - crates/ui-widgets/src/menu/item.rs: upstream no longer imports level::Row (065818eeb); the port imports ValueMark. Result: {MenuLevel, ValueMark}. - crates/ui-widgets/tests/it/list.rs: both sides added trials after text_rows_are_shorter_than_control_rows. All kept: the port's a_list_in_a_side_menu_has_taller_place_rows, and upstream's three thumbnail-size trials. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
28ffa4359e
289 files changed
+29189
-1395
No files matched your search
@@ -3,9 +3,9 @@ name: Shared audio
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
|
||||
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
|
||||
paths: ["crates/audio/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "scripts/fetch-opus-vectors.sh", "Cargo.toml", "Cargo.lock", ".github/workflows/audio.yml"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -3,9 +3,9 @@ name: Shared media
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
|
||||
paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
|
||||
paths: ["crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/media.yml"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -3,9 +3,9 @@ name: Shared video
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
|
||||
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
|
||||
pull_request:
|
||||
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
|
||||
paths: ["crates/video/**", "crates/media/**", "crates/media-testkit/**", "crates/testkit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/video.yml"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
Generated
+43
-21
@@ -835,12 +835,6 @@ dependencies = [
|
||||
"cpufeatures 0.3.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -1685,19 +1679,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-graphics2"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block",
|
||||
"cfg-if",
|
||||
"core-foundation 0.10.1",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core_detect"
|
||||
version = "1.0.0"
|
||||
@@ -1905,6 +1886,7 @@ dependencies = [
|
||||
"craft-pst",
|
||||
"craft-quit",
|
||||
"craft-raster-codecs",
|
||||
"craft-raster3d",
|
||||
"craft-raw",
|
||||
"craft-review",
|
||||
"craft-rtf",
|
||||
@@ -2055,6 +2037,8 @@ dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
@@ -2800,6 +2784,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.47.0",
|
||||
"write-fonts 0.54.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2959,6 +2944,7 @@ name = "craft-gpu-wgpu"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-gpu",
|
||||
"craft-gpu-device",
|
||||
"craft-gpu-providers",
|
||||
"pollster 0.4.0",
|
||||
"wgpu",
|
||||
@@ -3049,6 +3035,8 @@ version = "0.1.0"
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"brotli 9.1.1",
|
||||
"brotli-decompressor 6.3.1",
|
||||
"chrono",
|
||||
"fixed_decimal",
|
||||
"icu_calendar",
|
||||
@@ -3254,9 +3242,11 @@ dependencies = [
|
||||
"craft-ui-macros",
|
||||
"craft-xml",
|
||||
"egui",
|
||||
"global-hotkey",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"x11rb",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3509,6 +3499,7 @@ dependencies = [
|
||||
name = "craft-nightly"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"uds_windows",
|
||||
"winsafe",
|
||||
]
|
||||
|
||||
@@ -3798,17 +3789,20 @@ dependencies = [
|
||||
"async-process",
|
||||
"clipboard-win",
|
||||
"core-graphics",
|
||||
"core-graphics2",
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
"craft-docpath",
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
"craft-testkit",
|
||||
"craft-theme",
|
||||
"fmv-macos-events",
|
||||
"futures-lite",
|
||||
"js-sys",
|
||||
"log",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"objc2-foundation 0.3.2",
|
||||
"rfd",
|
||||
"serde",
|
||||
@@ -4017,6 +4011,14 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-raster3d"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-raw"
|
||||
version = "0.1.0"
|
||||
@@ -4354,7 +4356,9 @@ name = "craft-testkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"png 0.18.1",
|
||||
"proptest",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
@@ -4748,6 +4752,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"craft-host",
|
||||
"craft-testkit",
|
||||
"craft-theme",
|
||||
"craft-ui",
|
||||
"dunce",
|
||||
@@ -6944,6 +6949,23 @@ version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
|
||||
|
||||
[[package]]
|
||||
name = "global-hotkey"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "adda8c76a5139df3bae0eb0413c2cd746f66594e0bb66231a4daa0be3172da70"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"keyboard-types",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"once_cell",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.59.0",
|
||||
"x11rb",
|
||||
"xkeysym",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glow"
|
||||
version = "0.17.0"
|
||||
@@ -14678,7 +14700,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
[[package]]
|
||||
name = "winit"
|
||||
version = "0.30.13"
|
||||
source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc"
|
||||
source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45"
|
||||
dependencies = [
|
||||
"android-activity",
|
||||
"atomic-waker",
|
||||
|
||||
+3
-2
@@ -236,6 +236,7 @@ craft-text = { path = "crates/text" }
|
||||
craft-tcraft = { path = "crates/tcraft" }
|
||||
craft-texture = { path = "crates/texture" }
|
||||
craft-pbr = { path = "crates/pbr" }
|
||||
craft-raster3d = { path = "crates/raster3d" }
|
||||
craft-tga = { path = "crates/tga" }
|
||||
craft-timeline = { path = "crates/timeline" }
|
||||
craft-tiff = { path = "crates/tiff" }
|
||||
@@ -291,7 +292,7 @@ smallvec = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
typeid = "1"
|
||||
proptest = "1"
|
||||
proptest = "1.7"
|
||||
# Character sets of the WHATWG Encoding Standard (craft-mime). (Apache-2.0 OR MIT) AND BSD-3-Clause.
|
||||
encoding_rs = "0.8"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
@@ -341,7 +342,7 @@ egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
|
||||
|
||||
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
|
||||
# 32-bit stream the prediction can leave the i32 range while the sum does not, so a debug build
|
||||
|
||||
@@ -486,3 +486,11 @@ The Y4M range-backed source in crates/media-source/src/y4m.rs adapts FilmCraft's
|
||||
original implementation (3f137a7ed420cac79b32145f5243b7f98b31f71c), licensed
|
||||
MIT OR Apache-2.0. Source notice retained:
|
||||
Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors.
|
||||
|
||||
The CPU renderer in crates/raster3d (rasterizer, shading, shadow maps, resolve and encoding) and
|
||||
the copy of it in crates/raster3d/tests/it/reference/ are moved from:
|
||||
- EffectCraft, crates/render/src/three_d/adv.rs, adv/raster.rs, adv/shade.rs and adv/scene.rs,
|
||||
revision 2f16feb12f4d5ef601b35b2858f9c9a87077f61e, licensed under the MIT License or the Apache
|
||||
License, Version 2.0, at your option.
|
||||
https://github.com/storytold/effectcraft
|
||||
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors.
|
||||
@@ -394,6 +394,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
- [`craft-quit`](crates/quit/README.md): native macOS quit, a window close held for unsaved
|
||||
documents, the Quit menu item id and the unsaved-changes question one document at a time
|
||||
(`CloseGuard`). The prompt and the saving stay in each app.
|
||||
- [`craft-raster3d`](crates/raster3d/README.md): a CPU renderer for a prepared 3D scene, from
|
||||
EffectCraft: clipping, rasterization with a top-left fill rule, physically based shading,
|
||||
shadow maps, a box resolve of supersampled output and sRGB encoding. Scenes and sizes are
|
||||
checked before the target is allocated. `Limits` bounds sizes and coverage work. Preparation can
|
||||
allocate clipping and triangle buffers before a work-limit error. Building the scene stays in each app.
|
||||
- [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages
|
||||
(`\uN`, `\'hh`, single-byte and East Asian multibyte pages), escaping and dates, and a reader and writer
|
||||
for a small neutral model (paragraphs, character formatting, outline levels, tables).
|
||||
@@ -436,7 +441,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
test when the variable the caller names is `1`. Any other value of that variable except empty fails
|
||||
the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder
|
||||
against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures
|
||||
under `target/fixtures` and publishes each one under a lock. Not published.
|
||||
under `target/fixtures` and publishes each one under a lock. Its `temp` module makes a new test folder, private to the user on
|
||||
Unix, that is removed with its contents when dropped (best effort). Not published.
|
||||
- [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds
|
||||
hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns
|
||||
for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-appkit"
|
||||
description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
|
||||
description = "The macOS menu-tracking observers, Save panel calls and Core Graphics display calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -9,12 +9,19 @@ repository.workspace = true
|
||||
|
||||
# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through
|
||||
# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action.
|
||||
# The active display list and an image's pixel bytes from Core Graphics.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6.2"
|
||||
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
|
||||
objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "CGDataProvider", "CGDirectDisplay", "CGError", "CGImage"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] }
|
||||
|
||||
# A test image made from known bytes.
|
||||
[target.'cfg(target_os = "macos")'.dev-dependencies]
|
||||
objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std", "CFData"] }
|
||||
objc2-core-graphics = { version = "0.3.2", default-features = false, features = ["std", "CGColorSpace", "CGDataProvider", "CGImage"] }
|
||||
|
||||
# The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's
|
||||
# `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one
|
||||
# workspace lint.
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! The Core Graphics display calls that need `unsafe`: listing the active displays, and reading an image's pixels
|
||||
//! without copying them a second time.
|
||||
|
||||
use objc2_core_graphics::{CGDataProvider, CGDirectDisplayID, CGError, CGGetActiveDisplayList, CGImage};
|
||||
|
||||
/// The largest `max` that [`active_displays`] accepts.
|
||||
pub const MAX_DISPLAYS: usize = 1024;
|
||||
|
||||
/// The IDs of the active displays, at most `max` of them, or `None` when `max` is above [`MAX_DISPLAYS`] or Core
|
||||
/// Graphics reports an error.
|
||||
pub fn active_displays(max: usize) -> Option<Vec<CGDirectDisplayID>> {
|
||||
if max > MAX_DISPLAYS {
|
||||
return None;
|
||||
}
|
||||
let capacity = u32::try_from(max).ok()?;
|
||||
let mut ids: Vec<CGDirectDisplayID> = vec![0; max];
|
||||
let mut count = 0u32;
|
||||
// SAFETY: `ids` holds `capacity` writable IDs and `count` is a writable `u32`. Core Graphics writes at most
|
||||
// `capacity` IDs and the number it wrote.
|
||||
let result = unsafe { CGGetActiveDisplayList(capacity, ids.as_mut_ptr(), &mut count) };
|
||||
if result != CGError::Success {
|
||||
return None;
|
||||
}
|
||||
ids.truncate(usize::try_from(count).ok()?.min(max));
|
||||
Some(ids)
|
||||
}
|
||||
|
||||
/// Calls `read` with the bytes of `image`'s pixels, or returns `None` when the image has no data provider or the
|
||||
/// provider gives no data.
|
||||
pub fn with_image_bytes<R>(image: &CGImage, read: impl FnOnce(&[u8]) -> R) -> Option<R> {
|
||||
let data = CGDataProvider::data(CGImage::data_provider(Some(image)).as_deref())?;
|
||||
// SAFETY: `CGDataProviderCopyData` returns a new immutable `CFData` that this function holds until `read`
|
||||
// returns, so nothing changes its bytes while the slice is borrowed.
|
||||
Some(read(unsafe { data.as_bytes_unchecked() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use objc2_core_foundation::CFData;
|
||||
use objc2_core_graphics::{CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGImageAlphaInfo, CGMainDisplayID};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The list holds the main display and no more IDs than asked for; a `max` above the limit is refused.
|
||||
#[test]
|
||||
fn active_displays_lists_the_main_display_within_max() {
|
||||
let all = active_displays(MAX_DISPLAYS).unwrap_or_default();
|
||||
assert!(all.contains(&CGMainDisplayID()), "{all:?}");
|
||||
// 0 is `kCGNullDirectDisplay`: an ID Core Graphics did not write.
|
||||
assert!(!all.contains(&0), "{all:?}");
|
||||
assert_eq!(active_displays(0), Some(Vec::new()));
|
||||
assert_eq!(active_displays(1).map(|ids| ids.len()), Some(1));
|
||||
assert_eq!(active_displays(MAX_DISPLAYS + 1), None);
|
||||
assert_eq!(active_displays(usize::MAX), None);
|
||||
}
|
||||
|
||||
/// The bytes passed on are the image's own pixel rows, row padding included.
|
||||
#[test]
|
||||
fn image_bytes_are_the_pixels_of_the_image() {
|
||||
let pixels: Vec<u8> = (0u8..24).collect();
|
||||
let provider = CGDataProvider::with_cf_data(Some(&CFData::from_bytes(&pixels))).unwrap_or_else(|| panic!("no provider"));
|
||||
let space = CGColorSpace::new_device_rgb().unwrap_or_else(|| panic!("no color space"));
|
||||
// SAFETY: two rows of two RGBA pixels with 4 bytes of padding (12 bytes a row), 24 bytes in the provider, and a
|
||||
// null decode array.
|
||||
let image = unsafe {
|
||||
CGImage::new(
|
||||
2,
|
||||
2,
|
||||
8,
|
||||
32,
|
||||
12,
|
||||
Some(&space),
|
||||
CGBitmapInfo(CGImageAlphaInfo::PremultipliedLast.0),
|
||||
Some(&provider),
|
||||
std::ptr::null(),
|
||||
false,
|
||||
CGColorRenderingIntent::RenderingIntentDefault,
|
||||
)
|
||||
}
|
||||
.unwrap_or_else(|| panic!("no image"));
|
||||
assert_eq!(with_image_bytes(&image, <[u8]>::to_vec), Some(pixels));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the
|
||||
//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere.
|
||||
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, the
|
||||
//! Save panel calls in `save_panel`, and the Core Graphics display calls in `display`. macOS only; the crate is empty
|
||||
//! elsewhere.
|
||||
//!
|
||||
//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every
|
||||
//! block says why it is sound.
|
||||
@@ -14,6 +15,7 @@ use block2::RcBlock;
|
||||
use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification};
|
||||
use objc2_foundation::{NSNotification, NSNotificationCenter};
|
||||
|
||||
pub mod display;
|
||||
pub mod save_panel;
|
||||
|
||||
/// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)`
|
||||
|
||||
@@ -241,6 +241,35 @@ fn temp_name_format_is_valid() {
|
||||
assert!(name.ends_with(".craft_tmp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temp_name_keeps_long_non_latin_names_under_the_name_limit() {
|
||||
// 62 four-byte characters plus ".json" is a valid 253-byte name.
|
||||
let file = format!("{}.json", "\u{1F600}".repeat(62));
|
||||
assert_eq!(file.len(), 253);
|
||||
let name = temp_name(&file);
|
||||
assert!(name.len() <= 255, "{} bytes", name.len());
|
||||
assert!(name.starts_with(&format!(".{}.", "\u{1F600}".repeat(TEMP_STEM_BYTES / 4))));
|
||||
assert!(name.ends_with(".craft_tmp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temp_name_cuts_at_a_character_boundary() {
|
||||
// TEMP_STEM_BYTES - 1 ASCII bytes, then a two-byte character that would end one byte past the limit.
|
||||
let file = format!("{}\u{e9}tail", "a".repeat(TEMP_STEM_BYTES - 1));
|
||||
let name = temp_name(&file);
|
||||
assert!(name.starts_with(&format!(".{}.", "a".repeat(TEMP_STEM_BYTES - 1))));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn saves_a_long_non_latin_name() {
|
||||
let d = TempDir::new("long-name");
|
||||
let p = d.0.join(format!("{}.json", "\u{1F600}".repeat(62)));
|
||||
assert!(atomic_write(&p, b"saved").is_ok());
|
||||
assert_eq!(std::fs::read(&p).ok(), Some(b"saved".to_vec()));
|
||||
assert_no_temp(&d.0);
|
||||
}
|
||||
|
||||
/// What a [`Planting`] filesystem puts at a stage name just before the stage is created there.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Obstacle {
|
||||
|
||||
+123
-16
@@ -172,6 +172,8 @@ pub struct NumberCodec {
|
||||
/// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]).
|
||||
share: bool,
|
||||
signed_zoom: bool,
|
||||
/// A positive value is written with its `+` ([`NumberCodec::explicit_plus`]).
|
||||
plus: bool,
|
||||
}
|
||||
|
||||
impl fmt::Debug for NumberCodec {
|
||||
@@ -183,6 +185,7 @@ impl fmt::Debug for NumberCodec {
|
||||
.field("zoom", &self.zoom)
|
||||
.field("share", &self.share)
|
||||
.field("signed_zoom", &self.signed_zoom)
|
||||
.field("plus", &self.plus)
|
||||
.field("custom", &self.custom.is_some())
|
||||
.field("primary", &self.primary.is_some())
|
||||
.finish()
|
||||
@@ -207,6 +210,7 @@ impl PartialEq for NumberCodec {
|
||||
&& self.zoom == other.zoom
|
||||
&& self.share == other.share
|
||||
&& self.signed_zoom == other.signed_zoom
|
||||
&& self.plus == other.plus
|
||||
&& same_custom
|
||||
&& same_primary
|
||||
}
|
||||
@@ -242,7 +246,17 @@ const NUMBER_SAMPLE: &str = "0000.00";
|
||||
impl NumberCodec {
|
||||
/// A codec reading with `reader` and writing at most `decimals` decimal places.
|
||||
pub fn new(reader: Reader, decimals: usize) -> Self {
|
||||
NumberCodec { reader, decimals, fixed: false, custom: None, primary: None, zoom: false, share: false, signed_zoom: false }
|
||||
NumberCodec { reader, decimals, fixed: false, custom: None, primary: None, zoom: false, share: false, signed_zoom: false, plus: false }
|
||||
}
|
||||
|
||||
/// The same codec writing a positive value with its sign ("+2.50"), as an angle or an offset from a neutral value
|
||||
/// reads; a value that rounds to zero at the codec's decimals stays unsigned ("0.00"). A leading `+` in typed text
|
||||
/// is then the number's sign, as the field writes it, not the relative `+` of a plain field (which adds to the
|
||||
/// value the edit started from). An authoritative [`parse_with`](Self::parse_with) reader still receives the whole
|
||||
/// input, including the sign.
|
||||
pub fn explicit_plus(mut self) -> Self {
|
||||
self.plus = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown
|
||||
@@ -322,6 +336,25 @@ impl NumberCodec {
|
||||
self
|
||||
}
|
||||
|
||||
fn parse_builtin(&self, trimmed: &str, start: Option<f64>) -> Result<(Option<f64>, ParseNote), NotAValue> {
|
||||
if self.zoom {
|
||||
return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note));
|
||||
}
|
||||
// Without an edit-start operand the reader already treats a leading `+` as a unary sign. Take that
|
||||
// path directly rather than retrying each shorter suffix, and leave signed shares as absolute amounts.
|
||||
let absolute_plus = self.plus && trimmed.starts_with('+');
|
||||
if self.share
|
||||
&& !absolute_plus
|
||||
&& let Some(share_of_start) = self.reader.share(trimmed)
|
||||
{
|
||||
return start.map(|start| (Some(start * share_of_start), ParseNote::default())).ok_or(NotAValue);
|
||||
}
|
||||
match self.reader.read_tagged(trimmed, if absolute_plus { None } else { start }) {
|
||||
Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })),
|
||||
Err(rejected) => self.custom.as_ref().and_then(|parse| parse(trimmed)).map(|number| (Some(number), ParseNote::default())).ok_or(rejected),
|
||||
}
|
||||
}
|
||||
|
||||
/// The widest text the codec writes for a number in `range`: the longest of each end and the number one place of
|
||||
/// the last decimal inside it ("100" and "99.9" over 0 to 100 at one decimal), so a field over the range is sized
|
||||
/// for any value it shows in it.
|
||||
@@ -346,6 +379,12 @@ impl NumberCodec {
|
||||
pub fn reader(&self) -> &Reader {
|
||||
&self.reader
|
||||
}
|
||||
|
||||
/// Whether the codec writes a positive value with its `+` ([`NumberCodec::explicit_plus`]): its own text then
|
||||
/// starts with a sign that is the number's, not a relative edit.
|
||||
pub fn writes_sign(&self) -> bool {
|
||||
self.plus
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for NumberCodec {
|
||||
@@ -372,7 +411,9 @@ impl Codec for NumberCodec {
|
||||
} else {
|
||||
fixed
|
||||
};
|
||||
trimmed.replace('.', &self.reader.decimal_separator().to_string())
|
||||
let shown = trimmed.replace('.', &self.reader.decimal_separator().to_string());
|
||||
let zero = trimmed.bytes().all(|byte| matches!(byte, b'0' | b'.'));
|
||||
if self.plus && !trimmed.starts_with('-') && !zero { format!("+{shown}") } else { shown }
|
||||
}
|
||||
|
||||
fn parse(&self, text: &str, start: &Option<f64>) -> Result<Option<f64>, NotAValue> {
|
||||
@@ -389,20 +430,7 @@ impl Codec for NumberCodec {
|
||||
if let Some(parse) = &self.primary {
|
||||
return parse(trimmed).filter(|number| number.is_finite()).map(|number| (Some(number), ParseNote::default())).ok_or(NotAValue);
|
||||
}
|
||||
if self.zoom {
|
||||
return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note));
|
||||
}
|
||||
if self.share
|
||||
&& let Some(share) = self.reader.share(trimmed)
|
||||
{
|
||||
return start.map(|start| (Some(start * share), ParseNote::default())).ok_or(NotAValue);
|
||||
}
|
||||
match self.reader.read_tagged(text, *start) {
|
||||
Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })),
|
||||
Err(rejected) => {
|
||||
self.custom.as_ref().and_then(|parse| parse(text.trim())).map(|number| (Some(number), ParseNote::default())).ok_or(rejected)
|
||||
}
|
||||
}
|
||||
self.parse_builtin(trimmed, *start)
|
||||
}
|
||||
|
||||
/// Zoom typing takes ASCII digits, `/` and the decimal separator, with an optional minus; other fields take every character.
|
||||
@@ -427,4 +455,83 @@ mod tests {
|
||||
assert_eq!(one.format(&Some(-0.06)), "-0.1");
|
||||
assert_eq!(NumberCodec::new(Reader::new(), 1).fixed().format(&Some(-0.04)), "0.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_plus_codec_writes_the_sign_of_a_positive_value() {
|
||||
let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus();
|
||||
assert_eq!(angle.format(&Some(2.5)), "+2.50");
|
||||
assert_eq!(angle.format(&Some(-3.25)), "-3.25");
|
||||
assert_eq!(angle.format(&Some(0.0)), "0.00", "zero is unsigned");
|
||||
assert_eq!(angle.format(&Some(0.004)), "0.00", "a value that rounds to zero is unsigned");
|
||||
assert_eq!(angle.format(&Some(-0.004)), "0.00");
|
||||
assert_eq!(angle.format(&None), "");
|
||||
assert_eq!(NumberCodec::new(Reader::new(), 2).explicit_plus().format(&Some(1.5)), "+1.5", "trimmed decimals keep the sign");
|
||||
assert_eq!(NumberCodec::new(Reader::new(), 2).fixed().format(&Some(2.5)), "2.50", "without it a positive value has no sign");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_plus_codec_reads_a_leading_plus_as_the_sign() {
|
||||
let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus();
|
||||
assert_eq!(angle.parse("+2.50", &Some(10.0)).ok(), Some(Some(2.5)), "the written text reads back as itself, not added to the start");
|
||||
assert_eq!(angle.parse(&angle.format(&Some(7.25)), &Some(-1.0)).ok(), Some(Some(7.25)));
|
||||
assert_eq!(angle.parse("-3.25", &Some(10.0)).ok(), Some(Some(-3.25)));
|
||||
assert_eq!(angle.parse("4", &None).ok(), Some(Some(4.0)));
|
||||
assert!(angle.parse("+", &Some(1.0)).is_err(), "a lone plus is no number");
|
||||
let plain = NumberCodec::new(Reader::new(), 2);
|
||||
assert_eq!(plain.parse("+2", &Some(10.0)).ok(), Some(Some(12.0)), "a plain field's leading plus still adds to the start");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod review_tests {
|
||||
use super::*;
|
||||
|
||||
/// The `+` a field writes may be typed back with a space after it: "+ 2.50" is the number 2.5, not the relative
|
||||
/// "+ 2.50" added to the start value.
|
||||
#[test]
|
||||
fn an_explicit_plus_codec_reads_the_space_after_the_sign() {
|
||||
let angle = NumberCodec::new(Reader::new(), 2).fixed().explicit_plus();
|
||||
assert_eq!(angle.parse("+ 2.50", &Some(10.0)).ok(), Some(Some(2.5)), "a space after the sign keeps it the number's own");
|
||||
assert_eq!(angle.parse("+\t7", &Some(10.0)).ok(), Some(Some(7.0)));
|
||||
assert!(angle.parse("+", &Some(10.0)).is_err(), "a lone plus stays no number");
|
||||
let plain = NumberCodec::new(Reader::new(), 2);
|
||||
assert_eq!(plain.parse("+ 2", &Some(10.0)).ok(), Some(Some(12.0)), "a plain field's plus still adds to the start");
|
||||
// The digit after the sign may be written in any script the reader reads: Arabic-Indic ٣ is 3.
|
||||
assert_eq!(angle.parse("+\u{663}", &Some(10.0)).ok(), Some(Some(3.0)), "a sign before an Arabic-Indic digit is still the number's");
|
||||
// The signed text is absolute for every lead the reader accepts, an expression too: "+(2+3)" is 5, not 15.
|
||||
assert_eq!(angle.parse("+(2+3)", &Some(10.0)).ok(), Some(Some(5.0)), "a signed expression is the number, not added to the start");
|
||||
assert_eq!(angle.parse("+2+3", &Some(10.0)).ok(), Some(Some(5.0)), "and a signed sum reads the same as without the sign");
|
||||
assert_eq!(angle.parse("-(2+3)", &Some(10.0)).ok(), Some(Some(-5.0)), "a minus stays absolute, as it was");
|
||||
assert_eq!(plain.parse("+(2+3)", &Some(10.0)).ok(), Some(Some(15.0)), "a plain field still adds a leading plus to the start");
|
||||
// A word the field's own parser stands for is given the text as it was typed, `+` and all.
|
||||
let named = NumberCodec::new(Reader::new(), 2).explicit_plus().or_parse(|text| (text == "+Auto").then_some(42.0));
|
||||
assert_eq!(named.parse("+Auto", &Some(10.0)).ok(), Some(Some(42.0)), "a custom parser still sees the signed text");
|
||||
assert_eq!(named.parse("+2", &Some(10.0)).ok(), Some(Some(2.0)), "while a number after the sign stays absolute");
|
||||
assert_eq!(angle.parse("\u{663}", &Some(10.0)).ok(), Some(Some(3.0)), "and the reader reads that digit as before");
|
||||
assert_eq!(plain.parse("+\u{663}", &Some(10.0)).ok(), Some(Some(13.0)), "a plain field still adds it to the start");
|
||||
}
|
||||
|
||||
/// A share field's signed percentage is that number, not a share of the start value again.
|
||||
#[test]
|
||||
fn an_explicit_plus_share_codec_reads_a_signed_percentage_as_the_number() {
|
||||
let share = NumberCodec::new(Reader::new().unit("%", 1.0), 0).share_of_start().explicit_plus();
|
||||
assert_eq!(share.parse("+50%", &Some(10.0)).ok(), Some(Some(50.0)), "a signed percentage is absolute");
|
||||
assert_eq!(share.parse("50%", &Some(10.0)).ok(), Some(Some(5.0)), "an unsigned one is the share of the start");
|
||||
assert_eq!(share.parse("+50", &Some(10.0)).ok(), Some(Some(50.0)), "and a signed number is absolute too");
|
||||
}
|
||||
#[test]
|
||||
fn explicit_plus_still_gives_the_authoritative_reader_the_whole_signed_input() {
|
||||
let codec = NumberCodec::default().parse_with(|text| (text == "+12").then_some(17.0)).explicit_plus();
|
||||
assert_eq!(codec.parse(" +12 ", &Some(50.0)), Ok(Some(17.0)));
|
||||
assert_eq!(codec.parse("+(2+3)", &Some(50.0)), Err(NotAValue), "rejects instead of falling back to the expression reader");
|
||||
assert_eq!(codec.format(&Some(17.0)), "+17");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_plus_codec_reads_a_long_run_of_unary_signs_without_recursing() {
|
||||
let codec = NumberCodec::default().explicit_plus();
|
||||
let long = "+ ".repeat(32_768);
|
||||
assert_eq!(codec.parse(&format!("{long}--(2+3)"), &Some(10.0)), Ok(Some(5.0)));
|
||||
assert_eq!(codec.parse(&long, &Some(10.0)), Err(NotAValue));
|
||||
}
|
||||
}
|
||||
+159
-17
@@ -584,6 +584,23 @@ impl<T> Open<T> {
|
||||
!self.reported || (self.dragging && !self.drag_reported) || self.passing.is_some()
|
||||
}
|
||||
|
||||
/// The pointer reached `at`, by a move or by the button going up there: once past `slop` from the press, a target
|
||||
/// that senses a drag starts one, one that clicks and passes its drag waits for its hand-over, and any other loses
|
||||
/// its click. A release with no move before it (the pointer jumped) is judged where it went up, so only a release
|
||||
/// within slop clicks.
|
||||
fn reach(&mut self, at: Pos2, slop: f32) {
|
||||
if self.released_at.is_none() && !self.dragging && !self.abandoned && self.passing.is_none() && at.distance(self.start.origin) > slop {
|
||||
if self.sense.contains(Sense::DRAG) {
|
||||
self.dragging = true;
|
||||
self.silent = false;
|
||||
} else if self.sense.contains(Sense::CLICK | Sense::PASSES_DRAG) {
|
||||
self.passing = Some(at);
|
||||
} else {
|
||||
self.abandoned = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A release now is a click.
|
||||
fn clicks(&self) -> bool {
|
||||
!self.dragging && !self.abandoned && !self.left && self.passing.is_none() && self.sense.contains(Sense::CLICK)
|
||||
@@ -693,21 +710,8 @@ impl<T: Copy> PressMachine<T> {
|
||||
match *event {
|
||||
PointerEvent::Moved { at, .. } => {
|
||||
pos = at;
|
||||
if let Some(open) = &mut self.open
|
||||
&& open.released_at.is_none()
|
||||
&& !open.dragging
|
||||
&& !open.abandoned
|
||||
&& open.passing.is_none()
|
||||
&& at.distance(open.start.origin) > input.slop
|
||||
{
|
||||
if open.sense.contains(Sense::DRAG) {
|
||||
open.dragging = true;
|
||||
open.silent = false;
|
||||
} else if open.sense.contains(Sense::CLICK | Sense::PASSES_DRAG) {
|
||||
open.passing = Some(at);
|
||||
} else {
|
||||
open.abandoned = true;
|
||||
}
|
||||
if let Some(open) = &mut self.open {
|
||||
open.reach(at, input.slop);
|
||||
}
|
||||
}
|
||||
PointerEvent::Gone => {
|
||||
@@ -717,11 +721,14 @@ impl<T: Copy> PressMachine<T> {
|
||||
}
|
||||
PointerEvent::Pressed { button, pos: at, time, clicks } => {
|
||||
pos = at;
|
||||
// A release held for the next pass gives way to a new press; it ends in this pass.
|
||||
// A release held for the next pass gives way to a new press; it ends in this pass. A drag whose
|
||||
// start that pass still owed was never reported, so the release is no drag either: every part reads
|
||||
// `Down`, a `Release`, or `DragStart` then `Drag`, never a drag's end that never began. The press's
|
||||
// target hears where the button went up in `Release::pos`, and no click is at that distance.
|
||||
if let Some(open) = self.open
|
||||
&& let Some((up, click)) = open.released_at
|
||||
{
|
||||
released = Some((open.target, open.start, up, open.dragging, click, open.silent));
|
||||
released = Some((open.target, open.start, up, open.drag_reported, click, open.silent));
|
||||
self.open = None;
|
||||
}
|
||||
// A secondary press during an open primary press goes beside it, to the context target `pick` gives
|
||||
@@ -788,6 +795,9 @@ impl<T: Copy> PressMachine<T> {
|
||||
if self.open.is_some_and(|open| open.start.button != button || open.released_at.is_some()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(open) = &mut self.open {
|
||||
open.reach(at, input.slop);
|
||||
}
|
||||
if let Some(open) = &mut self.open
|
||||
&& open.owes_phase()
|
||||
{
|
||||
@@ -1114,4 +1124,136 @@ mod tests {
|
||||
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase);
|
||||
assert_eq!(end.activated, None);
|
||||
}
|
||||
|
||||
/// A release past slop with no move before it (the pointer jumped while the button was down) reads as a move there
|
||||
/// and a release: it does what a move past slop and a release in one pass do, for every sense. A target that drags
|
||||
/// starts its drag and ends it, with no click.
|
||||
#[test]
|
||||
fn a_jump_release_past_slop_starts_and_ends_a_drag() {
|
||||
let sense = Sense::CLICK | Sense::DRAG;
|
||||
let (far, near) = (SLOP * 4.0, SLOP / 2.0);
|
||||
let jumped = phases(&[&[press(0.0, 1.0)], &[up(far)], &[]], sense);
|
||||
assert_eq!(jumped, phases(&[&[press(0.0, 1.0)], &[moved(far), up(far)], &[]], sense), "a jump is a move and a release");
|
||||
assert_eq!(jumped, "D S R", "the drag starts where the button went up, then ends with no click");
|
||||
assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(near)]], sense), "D R!", "a jump within slop still clicks");
|
||||
|
||||
let mut machine = PressMachine::new();
|
||||
pass(&mut machine, &[press(0.0, 1.0)], sense);
|
||||
let start = pass(&mut machine, &[up(far)], sense);
|
||||
assert!(matches!(start.phase, Some(PressPhase::DragStart { pos, .. }) if pos == pos2(far, 0.0)), "{:?}", start.phase);
|
||||
assert!(machine.release_held(), "the release waits for the owed DragStart");
|
||||
let end = pass(&mut machine, &[], sense);
|
||||
assert!(matches!(end.phase, Some(PressPhase::Release { pos, click: false, .. }) if pos == pos2(far, 0.0)), "{:?}", end.phase);
|
||||
assert!(end.dragging, "the release ends a drag");
|
||||
assert_eq!(end.activated, None, "a jump release past slop is no click");
|
||||
}
|
||||
|
||||
/// A jump release past slop on a target that clicks and passes its drag passes the press as a move past slop does:
|
||||
/// the pass reports it in `passes`, a shape below that takes it drags and releases with no click, and a press no
|
||||
/// shape takes is abandoned with no click.
|
||||
#[test]
|
||||
fn a_jump_release_past_slop_on_a_part_that_passes_its_drag_passes_the_press() {
|
||||
let far = SLOP * 4.0;
|
||||
let origin = pos2(0.0, 0.0);
|
||||
for events in [&[up(far)][..], &[moved(far), up(far)][..]] {
|
||||
// No shape takes the press: the next pass abandons it, and its release is no click.
|
||||
let mut machine = PressMachine::new();
|
||||
passing_pass(&mut machine, &[press(0.0, 1.0)]);
|
||||
let passed = passing_pass(&mut machine, events);
|
||||
assert_eq!(passed.passes.map(|start| start.origin), Some(origin), "{events:?}: {passed:?}");
|
||||
assert!(matches!(passed.phase, Some(PressPhase::Held { .. })) && passed.activated.is_none(), "{events:?}: {passed:?}");
|
||||
let end = passing_pass(&mut machine, &[]);
|
||||
assert_eq!(end.target, Some(1));
|
||||
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{events:?}: {:?}", end.phase);
|
||||
assert_eq!(end.activated, None, "{events:?}: a passed press no shape took is no click");
|
||||
|
||||
// The shape below takes it: it starts the drag where the button went up and ends it with no click.
|
||||
let mut machine = PressMachine::new();
|
||||
passing_pass(&mut machine, &[press(0.0, 1.0)]);
|
||||
assert!(passing_pass(&mut machine, events).passes.is_some(), "{events:?}");
|
||||
let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag");
|
||||
assert_eq!(handed.target, Some(2));
|
||||
assert!(
|
||||
matches!(handed.phase, Some(PressPhase::DragStart { start, pos }) if start.origin == origin && pos == pos2(far, 0.0)),
|
||||
"{events:?}: {:?}",
|
||||
handed.phase
|
||||
);
|
||||
let end = passing_pass(&mut machine, &[]);
|
||||
assert_eq!(end.target, Some(2));
|
||||
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{events:?}: {:?}", end.phase);
|
||||
assert_eq!(end.activated, None, "{events:?}: a passed press is no click");
|
||||
}
|
||||
assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(SLOP / 2.0)]], PASSES), "D R!", "a jump within slop is the shape's click");
|
||||
}
|
||||
|
||||
/// A press whose button jumped far and came up in a batch that also pressed again: the release ends the press in
|
||||
/// that pass, so the `DragStart` the jump owed never comes. The release is then no drag either, and the parts read
|
||||
/// `Down` then a `Release` with no drag between them: a drag's end that never began would leave a part that tracks
|
||||
/// a drag holding a press forever. The new press reports its `Down` in the next pass.
|
||||
#[test]
|
||||
fn a_jump_release_that_gives_way_to_a_new_press_reports_no_drag() {
|
||||
let sense = Sense::CLICK | Sense::DRAG;
|
||||
let far = SLOP * 4.0;
|
||||
let jumped = [up(far), press(far, 1.1)];
|
||||
assert_eq!(phases(&[&[press(0.0, 1.0)], &jumped[..], &[]], sense), "D R D", "the release ends the press with no drag of its own");
|
||||
|
||||
let mut machine = PressMachine::new();
|
||||
pass(&mut machine, &[press(0.0, 1.0)], sense);
|
||||
let end = pass(&mut machine, &jumped, sense);
|
||||
assert!(
|
||||
matches!(end.phase, Some(PressPhase::Release { start, pos, click: false }) if start.origin == pos2(0.0, 0.0) && pos == pos2(far, 0.0)),
|
||||
"{:?}",
|
||||
end.phase
|
||||
);
|
||||
assert!(!end.dragging, "the press never reported its drag's start, so its release claims none");
|
||||
assert_eq!(end.activated, None, "a jump release past slop is no click");
|
||||
assert!(!machine.dragging(), "the new press is no drag either");
|
||||
pass(&mut machine, &[], sense);
|
||||
let next = machine.open.map(|open| open.start.origin);
|
||||
assert!(matches!(next, Some(place) if place == pos2(far, 0.0)), "the new press is open from where it went down");
|
||||
|
||||
// A press that did report its drag's start keeps its drag's end, whatever gives way to it.
|
||||
let mut machine = PressMachine::new();
|
||||
pass(&mut machine, &[press(0.0, 1.0)], sense);
|
||||
assert!(matches!(pass(&mut machine, &[up(far)], sense).phase, Some(PressPhase::DragStart { .. })), "the jump starts the drag");
|
||||
let end = pass(&mut machine, &[up(far), press(far, 1.3)], sense);
|
||||
assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase);
|
||||
assert!(end.dragging, "the release ends the drag the part saw start");
|
||||
}
|
||||
|
||||
/// A jump release past slop on a part that clicks and passes its drag reads the same when a new press shares its
|
||||
/// batch: the release ends the press before the move ever passes the drag on, so it reports no drag, and the new
|
||||
/// press opens from where it went down.
|
||||
#[test]
|
||||
fn a_passed_jump_release_that_gives_way_to_a_new_press_reports_no_drag() {
|
||||
let far = SLOP * 4.0;
|
||||
let mut machine = PressMachine::new();
|
||||
passing_pass(&mut machine, &[press(0.0, 1.0)]);
|
||||
let end = passing_pass(&mut machine, &[up(far), press(far, 1.5)]);
|
||||
assert!(matches!(end.phase, Some(PressPhase::Release { pos, click: false, .. }) if pos == pos2(far, 0.0)), "{:?}", end.phase);
|
||||
assert!(!end.dragging, "no shape was ever told the drag started, so its release claims none");
|
||||
assert_eq!(end.activated, None, "a jump release past slop is no click");
|
||||
assert_eq!(machine.target(), Some(1), "the new press is open");
|
||||
assert!(!machine.dragging(), "and it is no drag");
|
||||
}
|
||||
|
||||
/// A jump release past slop on a target that only clicks abandons the click as a move past slop does: the release
|
||||
/// is reported with no click and nothing activates.
|
||||
#[test]
|
||||
fn a_jump_release_past_slop_on_a_click_only_part_abandons_the_click() {
|
||||
let (far, near) = (SLOP * 4.0, SLOP / 2.0);
|
||||
let jumped = phases(&[&[press(0.0, 1.0)], &[up(far)]], Sense::CLICK);
|
||||
assert_eq!(jumped, phases(&[&[press(0.0, 1.0)], &[moved(far), up(far)]], Sense::CLICK), "a jump is a move and a release");
|
||||
assert_eq!(jumped, "D R", "the release is no click");
|
||||
assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(near)]], Sense::CLICK), "D R!", "a jump within slop still clicks");
|
||||
|
||||
let mut machine = PressMachine::new();
|
||||
pass(&mut machine, &[press(0.0, 1.0)], Sense::CLICK);
|
||||
let end = pass(&mut machine, &[up(far)], Sense::CLICK);
|
||||
assert_eq!(end.target, Some(1));
|
||||
assert!(matches!(end.phase, Some(PressPhase::Release { pos, click: false, .. }) if pos == pos2(far, 0.0)), "{:?}", end.phase);
|
||||
assert!(!end.dragging, "a click-only part never drags");
|
||||
assert_eq!(end.activated, None, "the abandoned click activates nothing");
|
||||
assert!(machine.target().is_none(), "the release ends the press");
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use crate::codec::NotAValue;
|
||||
const DIGIT_BLOCKS: [u32; 5] = [0x30, 0x660, 0x6F0, 0x966, 0xFF10];
|
||||
|
||||
/// The value of a decimal digit of any supported script.
|
||||
fn digit(c: char) -> Option<u32> {
|
||||
pub(crate) fn digit(c: char) -> Option<u32> {
|
||||
DIGIT_BLOCKS.iter().find_map(|&zero| (zero..zero + 10).contains(&(c as u32)).then(|| c as u32 - zero))
|
||||
}
|
||||
|
||||
@@ -198,15 +198,12 @@ impl Parse<'_> {
|
||||
/// A factor; `scaled` says it starts a term, where a number with no unit counts as the reader's bare factor.
|
||||
/// Otherwise it is a multiplier, which may be a percentage.
|
||||
fn factor(&mut self, scaled: bool) -> Result<f64, NotAValue> {
|
||||
match self.peek() {
|
||||
Some('-') => {
|
||||
self.at += 1;
|
||||
self.factor(scaled).map(|value| -value)
|
||||
}
|
||||
Some('+') => {
|
||||
self.at += 1;
|
||||
self.factor(scaled)
|
||||
}
|
||||
let mut negative = false;
|
||||
while let Some(sign @ ('+' | '-')) = self.peek() {
|
||||
negative ^= sign == '-';
|
||||
self.at += 1;
|
||||
}
|
||||
let value = match self.peek() {
|
||||
Some('(') => {
|
||||
self.at += 1;
|
||||
let value = self.expr()?;
|
||||
@@ -214,7 +211,8 @@ impl Parse<'_> {
|
||||
Ok(value)
|
||||
}
|
||||
_ => self.quantity(scaled),
|
||||
}
|
||||
}?;
|
||||
Ok(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
/// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a
|
||||
|
||||
@@ -106,8 +106,20 @@ pub struct Wheel {
|
||||
/// taker that owns the gesture; another taker's share holds its own `mods`.
|
||||
pub held: Mods,
|
||||
/// A wheel event of the running gesture, or one less than [`GESTURE_GAP`] seconds before it began, arrived while a
|
||||
/// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends.
|
||||
/// modal layer held the wheel: the turn began or went on under the modal, and it stays marked until it ends. An
|
||||
/// app's own modal window marks it too (`CanvasSpace::mark_wheel_modal`).
|
||||
pub modal: bool,
|
||||
/// The owner claimed an earlier share of the running gesture (`CanvasSpace::claim_wheel`): it takes the gesture
|
||||
/// for itself. For the taker that owns the gesture; another taker's share is never claimed.
|
||||
pub claimed: bool,
|
||||
/// The `scroll` of the running gesture's shares the owner claimed before this one. Motion the owner did not
|
||||
/// claim is not counted.
|
||||
pub claimed_gathered: Vec2,
|
||||
/// The `zoom_lines` of the running gesture's shares the owner claimed before this one.
|
||||
pub claimed_zoom_gathered: Vec2,
|
||||
/// The motion the owner said it used up (`spent`) with its claims of the running gesture so far, in its own
|
||||
/// unit: `claimed_gathered` or `claimed_zoom_gathered` less this is what the claimed shares left over.
|
||||
pub claimed_spent: Vec2,
|
||||
}
|
||||
|
||||
/// The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out.
|
||||
@@ -256,6 +268,10 @@ impl Wheel {
|
||||
moved: false,
|
||||
held: mods,
|
||||
modal: false,
|
||||
claimed: false,
|
||||
claimed_gathered: Vec2::ZERO,
|
||||
claimed_zoom_gathered: Vec2::ZERO,
|
||||
claimed_spent: Vec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! that says whose storage this is, a Save As page that picks a folder and
|
||||
//! names a file, and a save that refuses to overwrite somebody else's work.
|
||||
//!
|
||||
//! Three things shape the implementation.
|
||||
//! Four things shape the implementation.
|
||||
//!
|
||||
//! Nothing here opens a socket. Every call goes through [`CloudBackend`]. A
|
||||
//! host writes that half. This module never learns what it reaches. That keeps
|
||||
@@ -21,6 +21,12 @@
|
||||
//! list under a heading reads to a user as a broken window. A feature the
|
||||
//! provider does not have is therefore absent, heading and all.
|
||||
//!
|
||||
//! Nothing here acts on a stale answer. Every answer carries the account
|
||||
//! generation its job was issued in, and [`pump`] drops one whose generation
|
||||
//! is no longer current, so a reply that arrives after a sign-out or a new
|
||||
//! sign-in is not applied to the session that replaced its own. A new kind of
|
||||
//! answer follows the same rule.
|
||||
//!
|
||||
//! The application supplies [`CloudApp`]. That is what it alone can answer.
|
||||
//! What its documents are, how bytes become one and back, and the words it
|
||||
//! shows them in.
|
||||
|
||||
@@ -5,12 +5,11 @@
|
||||
//! look or change, add a note, decide whether an email goes out, and see who
|
||||
//! already has access so one of them can be taken away again.
|
||||
//!
|
||||
//! Three things shape the implementation.
|
||||
//! Four things shape the implementation.
|
||||
//!
|
||||
//! Nothing here opens a socket. Every call goes through [`ShareBackend`], and
|
||||
//! nothing here reaches the network. A host writes the backend, and this
|
||||
//! module never learns what it talks to.
|
||||
//! this file.
|
||||
//!
|
||||
//! Nothing here blocks. Answers arrive on a channel and are read once per
|
||||
//! frame. Autocomplete waits [`DEBOUNCE`] after the last keystroke before it
|
||||
@@ -21,6 +20,17 @@
|
||||
//! false until the service says sharing exists, and an app hides its Share
|
||||
//! control rather than offering a button that fails. Contacts and mail are
|
||||
//! reported separately and are hidden the same way.
|
||||
//!
|
||||
//! Nothing here acts on a stale answer. Every request carries a sequence
|
||||
//! number, and its answer comes back with it. An answer is applied only while
|
||||
//! the request it answers still stands: an answer to a query the
|
||||
//! user has typed past, a link granted or an account linked for a sheet that
|
||||
//! has since closed or moved to another document, and a capabilities answer
|
||||
//! to a question asked before [`ShareDialog::refresh`],
|
||||
//! [`ShareDialog::connect`] or [`ShareDialog::signed_out`] are dropped. A
|
||||
//! withdrawal is the one answer applied by share id instead: the share is gone
|
||||
//! on the service, so it leaves every list that still shows it. A new kind of
|
||||
//! answer follows the sequence rule.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
@@ -226,7 +236,9 @@ struct Sheet {
|
||||
/// Where it could be saved. `None` until the answer arrives.
|
||||
destinations: Option<Vec<Destination>>,
|
||||
destinations_seq: Option<u64>,
|
||||
link_seq: Option<u64>,
|
||||
/// Account links in flight, by request. More than one can be: every
|
||||
/// unlinked destination stays clickable while another one links.
|
||||
linking: Vec<u64>,
|
||||
/// Which one is selected, by id.
|
||||
destination: Option<String>,
|
||||
/// The name typed while the document still has nowhere to live.
|
||||
@@ -248,7 +260,7 @@ impl Sheet {
|
||||
Sheet {
|
||||
destinations: None,
|
||||
destinations_seq: None,
|
||||
link_seq: None,
|
||||
linking: Vec::new(),
|
||||
destination: None,
|
||||
save_as: title.clone(),
|
||||
saving: None,
|
||||
@@ -740,16 +752,16 @@ impl ShareDialog {
|
||||
}
|
||||
}
|
||||
Answer::Linked => {
|
||||
// An account arrived, so the list is stale. With no sheet open
|
||||
// there is no list to reload.
|
||||
if self.open.is_some() {
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.destinations = None;
|
||||
}
|
||||
let seq = self.issue(Request::Destinations);
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.destinations_seq = Some(seq);
|
||||
}
|
||||
// Only for the sheet that asked: after the sheet closed, moved
|
||||
// to another document or the account signed out, a late
|
||||
// answer asks the service for nothing.
|
||||
let Some(sheet) = self.open.as_mut().filter(|sheet| sheet.linking.contains(&seq)) else { return };
|
||||
// An account arrived, so the list is stale.
|
||||
sheet.linking.retain(|s| *s != seq);
|
||||
sheet.destinations = None;
|
||||
let seq = self.issue(Request::Destinations);
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.destinations_seq = Some(seq);
|
||||
}
|
||||
}
|
||||
Answer::Withdrawn { share_id } => {
|
||||
@@ -802,8 +814,8 @@ impl ShareDialog {
|
||||
sheet.destinations_seq = None;
|
||||
sheet.destinations = Some(Vec::new());
|
||||
sheet.save_error = Some(reason);
|
||||
} else if sheet.link_seq == Some(seq) {
|
||||
sheet.link_seq = None;
|
||||
} else if sheet.linking.contains(&seq) {
|
||||
sheet.linking.retain(|s| *s != seq);
|
||||
sheet.save_error = Some(reason);
|
||||
}
|
||||
}
|
||||
@@ -845,7 +857,7 @@ impl ShareDialog {
|
||||
// application's business and not this crate's.
|
||||
let seq = self.issue(Request::Link { destination });
|
||||
if let Some(sheet) = &mut self.open {
|
||||
sheet.link_seq = Some(seq);
|
||||
sheet.linking.push(seq);
|
||||
sheet.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,6 +307,49 @@ fn a_link_granted_after_the_sheet_moved_on_is_not_copied() {
|
||||
assert!(copied(&ctx).is_empty(), "nor after the sheet closed");
|
||||
}
|
||||
|
||||
fn destinations_asked(backend: &Silent) -> usize {
|
||||
backend.seen().iter().filter(|r| **r == Request::Destinations).count()
|
||||
}
|
||||
|
||||
fn last_link(dialog: &ShareDialog) -> u64 {
|
||||
dialog.open.as_ref().and_then(|s| s.linking.last().copied()).expect("asked")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_account_linked_for_a_sheet_that_moved_on_asks_for_nothing() {
|
||||
let (ctx, mut dialog, _) = ready();
|
||||
dialog.apply(&ctx, vec![Act::Link("drive".into())]);
|
||||
let first = last_link(&dialog);
|
||||
// A second destination is clicked before the first one answers.
|
||||
dialog.apply(&ctx, vec![Act::Link("mail".into())]);
|
||||
let second = last_link(&dialog);
|
||||
dialog.receive(&ctx, first, Ok(Answer::Linked));
|
||||
let sheet = dialog.open.as_ref().expect("open");
|
||||
assert!(sheet.destinations_seq.is_some(), "the sheet that asked fetches its destinations again");
|
||||
assert_eq!(sheet.linking, [second], "the later link is still in flight");
|
||||
dialog.receive(&ctx, second, Err("no account".into()));
|
||||
let sheet = dialog.open.as_ref().expect("open");
|
||||
assert!(sheet.linking.is_empty());
|
||||
assert_eq!(sheet.save_error.as_deref(), Some("no account"));
|
||||
|
||||
let (ctx, mut dialog, backend) = ready();
|
||||
dialog.apply(&ctx, vec![Act::Link("drive".into())]);
|
||||
let linking = last_link(&dialog);
|
||||
dialog.close();
|
||||
dialog.open("files/plan.docx", "Plan");
|
||||
let before = destinations_asked(&backend);
|
||||
dialog.receive(&ctx, linking, Ok(Answer::Linked));
|
||||
assert_eq!(destinations_asked(&backend), before, "the budget's link answer must not ask anything for the plan");
|
||||
|
||||
let (ctx, mut dialog, backend) = ready();
|
||||
dialog.apply(&ctx, vec![Act::Link("drive".into())]);
|
||||
let linking = last_link(&dialog);
|
||||
dialog.signed_out();
|
||||
let before = destinations_asked(&backend);
|
||||
dialog.receive(&ctx, linking, Ok(Answer::Linked));
|
||||
assert_eq!(destinations_asked(&backend), before, "nothing is asked for an account that signed out");
|
||||
}
|
||||
|
||||
/// Whether one frame of the sheet offers "Get a link" as a button that can
|
||||
/// be pressed, read off the accessibility tree.
|
||||
fn link_button_enabled(dialog: &mut ShareDialog) -> Option<bool> {
|
||||
|
||||
@@ -81,8 +81,8 @@ pub use picker::{
|
||||
PickedColor, ScreenPickGesture, TrackRamp,
|
||||
};
|
||||
pub use picker_dialog::{
|
||||
ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickerLibrary,
|
||||
PickerSwatches,
|
||||
ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickedSwatch,
|
||||
PickerLibrary, PickerSwatches,
|
||||
};
|
||||
pub use popover::{ColorPopover, ColorPopoverOutput};
|
||||
pub use profile_prompts::{ProfileAction, ProfileAnswer, ProfileMismatchDialog, ProfileMode, ProfileQuestion, ProfileStatus, ProfileWords};
|
||||
|
||||
@@ -99,6 +99,7 @@ impl<'a> Body<'a> {
|
||||
if shown.restore
|
||||
&& let Mixed::Same(current) = pass.compare
|
||||
{
|
||||
got.restored = true;
|
||||
got.clicks.push(current);
|
||||
}
|
||||
if let Some(warning) = shown.warning.and_then(|at| self.warnings.get(at)) {
|
||||
|
||||
@@ -106,6 +106,8 @@ pub struct ColorPickerOutput {
|
||||
pub events: EditEvents<PickedColor>,
|
||||
/// The screen-pick button's press this pass.
|
||||
pub screen_pick: Option<ScreenPickGesture>,
|
||||
/// The compare block's current half was activated this pass.
|
||||
pub restored: bool,
|
||||
}
|
||||
|
||||
impl Outcome for ColorPickerOutput {
|
||||
@@ -181,6 +183,7 @@ struct Collected {
|
||||
edits: EditEvents<PickedColor>,
|
||||
/// Colours the compare swatch and the warning chips set.
|
||||
clicks: Vec<PickedColor>,
|
||||
restored: bool,
|
||||
screen_pick: Option<ScreenPickGesture>,
|
||||
model_pick: Option<&'static str>,
|
||||
/// The mode the "Field shows" group picked.
|
||||
@@ -430,8 +433,8 @@ impl<'a> ColorPicker<'a> {
|
||||
events: EditEvents::new(),
|
||||
};
|
||||
let shown = Stack::new().label(label).show(ui, |ui, body| run.show(ui, body));
|
||||
let (events, screen_pick) = shown.inner.unwrap_or_default();
|
||||
ColorPickerOutput { response: shown.output, events, screen_pick }
|
||||
let (events, screen_pick, restored) = shown.inner.unwrap_or_default();
|
||||
ColorPickerOutput { response: shown.output, events, screen_pick, restored }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -461,7 +464,7 @@ struct Run<'s, 'a> {
|
||||
}
|
||||
|
||||
impl<'a> Run<'_, 'a> {
|
||||
fn show(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>) -> (EditEvents<PickedColor>, Option<ScreenPickGesture>) {
|
||||
fn show(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>) -> (EditEvents<PickedColor>, Option<ScreenPickGesture>, bool) {
|
||||
let memo = body.memory::<Memo>().clone();
|
||||
let held_mode = self.mode.as_ref().and_then(|held| held.read(&mut *body)).and_then(|held| held.same().copied());
|
||||
let mut mode = held_mode.unwrap_or(memo.mode);
|
||||
@@ -546,7 +549,7 @@ impl<'a> Run<'_, 'a> {
|
||||
None => body.memory::<Memo>().model = Some(next),
|
||||
}
|
||||
}
|
||||
(std::mem::take(&mut self.events), got.screen_pick)
|
||||
(std::mem::take(&mut self.events), got.screen_pick, got.restored)
|
||||
}
|
||||
|
||||
/// Lands `event`, an edit of the colour: a gesture's end takes the colour it began from, the binding takes the
|
||||
|
||||
@@ -128,9 +128,19 @@ impl PickerSwatches {
|
||||
/// The Color Swatches view: the library `Select` over the chosen library's spaced palette, whose cell equal to the colour
|
||||
/// in `held` is marked and whose pick replaces `held`; the notice for a library without swatches. `library` is the
|
||||
/// remembered index, which may lie past the end; it is written only when the user chooses another. The dialog's buttons
|
||||
/// stand in the cell after it, as they head the Full picker's second column.
|
||||
fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held: &mut Mixed<PickedColor>, library_label: &Label) {
|
||||
/// stand in the cell after it, as they head the Full picker's second column. `selected`, the swatch the colour was
|
||||
/// picked from, is the marked cell when its library is shown. Returns the swatch clicked this pass, also one with the
|
||||
/// colour already held, whose colour `held` then takes.
|
||||
fn show_swatches(
|
||||
ui: &mut Ui,
|
||||
view: &PickerSwatches,
|
||||
library: &mut usize,
|
||||
held: &mut Mixed<PickedColor>,
|
||||
selected: Option<PickedSwatch>,
|
||||
library_label: &Label,
|
||||
) -> Option<PickedSwatch> {
|
||||
let mut chosen = (*library).min(view.libraries.len().saturating_sub(1));
|
||||
let mut clicked = None;
|
||||
Grid::new(TWO_COLUMNS).fit(GridFit::Fixed).cells(CellAlign::Top).gap(Gap::Section).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
if !view.libraries.is_empty() {
|
||||
@@ -145,10 +155,20 @@ fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held:
|
||||
Some(lib) => {
|
||||
// A colour that is not set marks no cell of a library without it; black stands for "none yet".
|
||||
let color = held.same().map_or(Srgba::BLACK, |picked| picked.color);
|
||||
let shown = SwatchPalette::new(lib.name.clone(), Bind::given(color), &lib.swatches).spacing(SwatchSpacing::Spaced).show(ui);
|
||||
let marked = selected.filter(|s| s.library == chosen).map(|s| s.index);
|
||||
let shown = SwatchPalette::new(lib.name.clone(), Bind::given(color), &lib.swatches)
|
||||
.spacing(SwatchSpacing::Spaced)
|
||||
.selected_swatch(marked)
|
||||
.show(ui);
|
||||
if let Some(picked) = shown.edit.as_ref().and_then(|edit| edit.value()).copied() {
|
||||
*held = Mixed::Same(PickedColor::rgb(picked));
|
||||
}
|
||||
// The clicked swatch's own colour, also when the palette files no edit for it (the colour held, or
|
||||
// one that rounds to it).
|
||||
if let Some((index, (_, color))) = shown.picked_swatch.and_then(|index| Some((index, lib.swatches.get(index)?))) {
|
||||
*held = Mixed::Same(PickedColor::rgb(*color));
|
||||
clicked = Some(PickedSwatch { library: chosen, index });
|
||||
}
|
||||
}
|
||||
None => {
|
||||
Notice::new(Tone::Neutral, view.empty.clone()).layout(NoticeLayout::Centred).show(ui);
|
||||
@@ -157,6 +177,24 @@ fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held:
|
||||
});
|
||||
let _ = FooterSlot::new().show(ui);
|
||||
});
|
||||
clicked
|
||||
}
|
||||
|
||||
/// A swatch of a [`ColorPickerDialog`]'s Color Swatches view, by its place in the [`PickerSwatches`] the app gave.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub struct PickedSwatch {
|
||||
/// The index of its library in [`PickerSwatches::libraries`].
|
||||
pub library: usize,
|
||||
/// The index of the swatch in that library's [`PickerLibrary::swatches`].
|
||||
pub index: usize,
|
||||
}
|
||||
|
||||
impl PickedSwatch {
|
||||
/// The swatch at `index` of library `library`.
|
||||
pub fn new(library: usize, index: usize) -> Self {
|
||||
PickedSwatch { library, index }
|
||||
}
|
||||
}
|
||||
|
||||
/// The remembered scope of [`ColorPickerMemory`].
|
||||
@@ -170,6 +208,9 @@ pub struct ColorPickerResult {
|
||||
pub key: String,
|
||||
/// The colour, with the model values the user typed while they still give it (CMYK inks, Lab values outside sRGB).
|
||||
pub picked: PickedColor,
|
||||
/// The swatch of the Color Swatches view the colour was picked from, when the last change to the colour was a click
|
||||
/// on that swatch; `None` when the colour was set any other way, or changed after the click.
|
||||
pub swatch: Option<PickedSwatch>,
|
||||
}
|
||||
|
||||
/// How a [`ColorPickerDialog`] lays out its body.
|
||||
@@ -238,6 +279,9 @@ pub struct ColorPickerDialog {
|
||||
opening: Option<PickedColor>,
|
||||
/// The colour as it stands; `None` until the first pick when the dialog opened without one.
|
||||
current: Option<PickedColor>,
|
||||
/// The colour was set by the caller ([`set_color`](Self::set_color), [`pick_swatch`](Self::pick_swatch)); the
|
||||
/// Only Web Colors snap at the start then leaves it as it is.
|
||||
color_set: bool,
|
||||
compare: bool,
|
||||
/// [`no_current`](Self::no_current).
|
||||
no_current: bool,
|
||||
@@ -247,6 +291,8 @@ pub struct ColorPickerDialog {
|
||||
working_rgb: Option<Box<dyn ColorModel + Send + Sync>>,
|
||||
gamut: Option<Gamut<'static>>,
|
||||
swatches: Option<PickerSwatches>,
|
||||
/// The swatch the current colour was picked from, while no other change has followed the click.
|
||||
picked_swatch: Option<PickedSwatch>,
|
||||
eyedropper: bool,
|
||||
canvas_samples: bool,
|
||||
canvas: Option<Id>,
|
||||
@@ -420,6 +466,7 @@ impl ColorPickerDialog {
|
||||
title_args: Vec::new(),
|
||||
opening,
|
||||
current: opening,
|
||||
color_set: false,
|
||||
compare: true,
|
||||
no_current: false,
|
||||
remember: true,
|
||||
@@ -428,6 +475,7 @@ impl ColorPickerDialog {
|
||||
working_rgb: None,
|
||||
gamut: None,
|
||||
swatches: None,
|
||||
picked_swatch: None,
|
||||
eyedropper: true,
|
||||
canvas_samples: true,
|
||||
canvas: None,
|
||||
@@ -449,10 +497,12 @@ impl ColorPickerDialog {
|
||||
}
|
||||
|
||||
/// In the Full layout, a body button after Cancel switches between Color Models and Color Swatches: a library `Select` over a spaced
|
||||
/// `SwatchPalette` with the current colour's cell marked, a pick being an edit. Without it there is no button.
|
||||
/// `SwatchPalette` with the current colour's cell marked, a pick being an edit. Without it there is no button. A swatch
|
||||
/// picked from the view it replaces is no longer named.
|
||||
#[must_use]
|
||||
pub fn swatch_view(mut self, swatches: PickerSwatches) -> ColorPickerDialog {
|
||||
self.swatches = Some(swatches);
|
||||
self.picked_swatch = None;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -465,9 +515,13 @@ impl ColorPickerDialog {
|
||||
}
|
||||
|
||||
/// Sets the dialog's layout: Full (Photoshop) or Tabbed (Word's Colors dialog).
|
||||
/// A layout other than Full clears the picked swatch and keeps the current color.
|
||||
#[must_use]
|
||||
pub fn layout(mut self, l: ColorPickerDialogLayout) -> ColorPickerDialog {
|
||||
self.layout = l;
|
||||
if l != ColorPickerDialogLayout::Full {
|
||||
self.picked_swatch = None;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -497,7 +551,12 @@ impl ColorPickerDialog {
|
||||
/// what the sRGB colour converts to (storytold/photocraft#4196).
|
||||
#[must_use]
|
||||
pub fn kept(mut self, values: craft_theme::ModelValues) -> ColorPickerDialog {
|
||||
for held in [&mut self.opening, &mut self.current].into_iter().flatten() {
|
||||
if let Some(held) = &mut self.opening {
|
||||
held.model = Some(values);
|
||||
}
|
||||
if self.picked_swatch.is_none()
|
||||
&& let Some(held) = &mut self.current
|
||||
{
|
||||
held.model = Some(values);
|
||||
}
|
||||
self
|
||||
@@ -614,6 +673,28 @@ impl ColorPickerDialog {
|
||||
/// model values when it has them, and the colour is what OK answers. The compare swatch keeps the opening colour.
|
||||
pub fn set_color(&mut self, picked: PickedColor) {
|
||||
self.current = Some(picked);
|
||||
self.color_set = true;
|
||||
self.picked_swatch = None;
|
||||
}
|
||||
|
||||
/// The swatch of the Color Swatches view the colour was picked from, while no other change has followed the click
|
||||
/// (what OK answers as [`ColorPickerResult::swatch`]).
|
||||
pub fn picked_swatch(&self) -> Option<PickedSwatch> {
|
||||
self.picked_swatch
|
||||
}
|
||||
|
||||
/// Picks `swatch` of the Color Swatches view as a click on it would, for automation and scripts: the colour becomes
|
||||
/// the swatch's and its library the one shown. `None` when the layout is not Full or the view has no such swatch.
|
||||
pub fn pick_swatch(&mut self, swatch: PickedSwatch) -> Option<()> {
|
||||
if self.layout != ColorPickerDialogLayout::Full {
|
||||
return None;
|
||||
}
|
||||
let (_, color) = self.swatches.as_ref()?.libraries.get(swatch.library)?.swatches.get(swatch.index)?;
|
||||
self.current = Some(PickedColor::rgb(*color));
|
||||
self.color_set = true;
|
||||
self.memory.library = swatch.library;
|
||||
self.picked_swatch = Some(swatch);
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The colour Add to Swatches was pressed for, once; `None` otherwise.
|
||||
@@ -640,7 +721,7 @@ impl ColorPickerDialog {
|
||||
{
|
||||
Remembered::<ColorPickerMemory>::new(MEMORY_SCOPE).store(host, &self.memory);
|
||||
}
|
||||
Some(ColorPickerResult { key: self.key.clone(), picked })
|
||||
Some(ColorPickerResult { key: self.key.clone(), picked, swatch: self.picked_swatch })
|
||||
}
|
||||
|
||||
/// Runs the dialog's start for automation that reaches it before its first pass.
|
||||
@@ -651,6 +732,29 @@ impl ColorPickerDialog {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets one JSON field after the dialog's start: `swatch`, `color` or a memory field.
|
||||
fn set_field(&mut self, field: &str, value: serde_json::Value) -> Result<(), String> {
|
||||
if field == "swatch" {
|
||||
if value.is_null() {
|
||||
self.picked_swatch = None;
|
||||
return Ok(());
|
||||
}
|
||||
let index = |i: usize| value.get(i).and_then(serde_json::Value::as_u64).and_then(|n| usize::try_from(n).ok());
|
||||
let swatch = match (value.as_array().map(Vec::len), index(0), index(1)) {
|
||||
(Some(2), Some(library), Some(index)) => PickedSwatch { library, index },
|
||||
_ => return Err(FieldRefusal::Rejects(&value).message(field)),
|
||||
};
|
||||
return self.pick_swatch(swatch).ok_or_else(|| FieldRefusal::Rejects(&value).message(field));
|
||||
}
|
||||
if field != "color" {
|
||||
return set_serde_field(&mut self.memory, field, value);
|
||||
}
|
||||
let parsed = value.as_str().and_then(Srgba::from_hex);
|
||||
let color = parsed.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
|
||||
self.set_color(PickedColor { color, model: None });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The first pass: recalls the remembered field component and Only Web Colors, and with Only Web Colors on snaps
|
||||
/// the opening colour, which the compare swatch's current half follows (storytold/photocraft#4995).
|
||||
fn start(&mut self, host: Option<&Arc<Host>>) {
|
||||
@@ -672,7 +776,12 @@ impl ColorPickerDialog {
|
||||
{
|
||||
let [r, g, b] = web_safe([opening.color.r, opening.color.g, opening.color.b]);
|
||||
self.opening = Some(PickedColor { color: Srgba { r, g, b, a: opening.color.a }, model: None });
|
||||
self.current = self.opening;
|
||||
if !self.color_set {
|
||||
self.current = self.opening;
|
||||
}
|
||||
}
|
||||
if let Some(swatch) = self.picked_swatch {
|
||||
self.memory.library = swatch.library;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -710,24 +819,46 @@ impl StackDialog for ColorPickerDialog {
|
||||
self.instance
|
||||
}
|
||||
|
||||
/// `color` (`#rrggbb`, null when there is none yet), and the memory's own `mode`, `webColors`, `swatches`, `library`, `tab`
|
||||
/// and `model`.
|
||||
/// `color` (`#rrggbb`, null when there is none yet), `swatch` (`[library, index]` of the swatch the colour was picked
|
||||
/// from, or null), and the memory's own `mode`, `webColors`, `swatches`, `library`, `tab` and `model`.
|
||||
fn json_fields(&self) -> Option<serde_json::Value> {
|
||||
let mut fields = serde_fields(&self.memory)?;
|
||||
let color = self.current.map_or(serde_json::Value::Null, |picked| picked.color.to_hex().into());
|
||||
fields.as_object_mut()?.insert("color".to_owned(), color);
|
||||
let swatch = self.picked_swatch.map_or(serde_json::Value::Null, |s| serde_json::json!([s.library, s.index]));
|
||||
let object = fields.as_object_mut()?;
|
||||
object.insert("color".to_owned(), color);
|
||||
object.insert("swatch".to_owned(), swatch);
|
||||
Some(fields)
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &Context, field: &str, value: serde_json::Value) -> Result<(), String> {
|
||||
// The dialog's start recalls the memory and snaps the opening colour; a field set before it would be overwritten.
|
||||
self.set_json_fields(ctx, &[(field.to_owned(), value)])
|
||||
}
|
||||
|
||||
/// Sets the fields in order; when one is refused, the fields and startup state are restored to their earlier values.
|
||||
fn set_json_fields(&mut self, ctx: &Context, fields: &[(String, serde_json::Value)]) -> Result<(), String> {
|
||||
if fields.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let before = (
|
||||
self.started,
|
||||
self.host.clone(),
|
||||
self.opening,
|
||||
self.current,
|
||||
self.color_set,
|
||||
self.picked_swatch,
|
||||
self.memory.clone(),
|
||||
self.tab,
|
||||
self.on_swatches,
|
||||
);
|
||||
self.start_headless(ctx);
|
||||
if field != "color" {
|
||||
return set_serde_field(&mut self.memory, field, value);
|
||||
for (field, value) in fields {
|
||||
if let Err(refusal) = self.set_field(field, value.clone()) {
|
||||
(self.started, self.host, self.opening, self.current, self.color_set, self.picked_swatch, self.memory, self.tab, self.on_swatches) =
|
||||
before;
|
||||
return Err(refusal);
|
||||
}
|
||||
}
|
||||
let parsed = value.as_str().and_then(Srgba::from_hex);
|
||||
let color = parsed.ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
|
||||
self.set_color(PickedColor { color, model: None });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -774,7 +905,8 @@ impl StackDialog for ColorPickerDialog {
|
||||
}
|
||||
};
|
||||
let footer = ResetFooter::new(ui, None, true);
|
||||
let changed = self.current != self.opening;
|
||||
// A swatch picked at the opening colour is a change Reset takes back.
|
||||
let changed = self.current != self.opening || self.picked_swatch.is_some();
|
||||
let mut buttons = footer.buttons(FooterButton::new(common.ok.clone(), DialogRole::Accept).enabled(self.current.is_some()), changed).to_vec();
|
||||
let full = self.layout == ColorPickerDialogLayout::Full;
|
||||
// The buttons after OK and Cancel are placed by position; their indices are read back from the list.
|
||||
@@ -809,6 +941,7 @@ impl StackDialog for ColorPickerDialog {
|
||||
layout,
|
||||
standard,
|
||||
swatches: view,
|
||||
picked_swatch,
|
||||
working_rgb,
|
||||
..
|
||||
} = self;
|
||||
@@ -817,6 +950,9 @@ impl StackDialog for ColorPickerDialog {
|
||||
let (sampled, busy, compare_with) = (sample.take(), *screen_busy, compare.then(|| opening.map_or(Mixed::Mixed, Mixed::Same)));
|
||||
let color = current.map(|current| current.color);
|
||||
let web_only = memory.web_colors;
|
||||
let mut clicked = None;
|
||||
let mut restored = false;
|
||||
let mut sample_processed = false;
|
||||
let shown = Dialog::new(title.clone())
|
||||
.opened(Bind::bound(open))
|
||||
.buttons(buttons)
|
||||
@@ -846,7 +982,7 @@ impl StackDialog for ColorPickerDialog {
|
||||
// PLAN: the swatch view should keep the value fields and replace only the area and strip, which the picker body
|
||||
// (picker/mod.rs, not in this set) lays out; here it replaces the whole picker body.
|
||||
if let Some(view) = view.as_ref().filter(|_| memory.swatches) {
|
||||
show_swatches(ui, view, &mut memory.library, &mut held, &words.library);
|
||||
clicked = show_swatches(ui, view, &mut memory.library, &mut held, *picked_swatch, &words.library);
|
||||
return;
|
||||
}
|
||||
let mut models = models_with(working_rgb, |on| on.full);
|
||||
@@ -874,16 +1010,26 @@ impl StackDialog for ColorPickerDialog {
|
||||
.eyedropper_busy(busy);
|
||||
if let Some(sampled) = sampled {
|
||||
picker = picker.sampled(sampled);
|
||||
sample_processed = true;
|
||||
}
|
||||
if let Some(compare) = compare_with {
|
||||
picker = picker.compare(compare);
|
||||
}
|
||||
picker = picker.compare_none(*no_current);
|
||||
if let Some(gesture) = picker.show(ui).screen_pick {
|
||||
let output = picker.show(ui);
|
||||
restored = output.restored;
|
||||
if let Some(gesture) = output.screen_pick {
|
||||
*pending_screen = Some(gesture);
|
||||
}
|
||||
});
|
||||
self.current = held.same().copied();
|
||||
let after = held.same().copied();
|
||||
// A swatch click names the swatch; any other change to the colour leaves it picked from no swatch.
|
||||
if clicked.is_some() {
|
||||
self.picked_swatch = clicked;
|
||||
} else if restored || sample_processed || after != self.current {
|
||||
self.picked_swatch = None;
|
||||
}
|
||||
self.current = after;
|
||||
|
||||
let (picked, closed) = (shown.output.picked, shown.output.closed);
|
||||
if picked.is_some() && picked == toggle_at {
|
||||
@@ -893,6 +1039,7 @@ impl StackDialog for ColorPickerDialog {
|
||||
let ok = (picked == Some(0) || closed == Some(CloseReason::Enter)) && self.current.is_some();
|
||||
if !ok && picked == Some(1) && footer.resetting() {
|
||||
self.current = self.opening;
|
||||
self.picked_swatch = None;
|
||||
return None;
|
||||
}
|
||||
if picked.is_some() && picked == add_at {
|
||||
|
||||
@@ -101,6 +101,7 @@ pub struct SwatchesPanel<'a> {
|
||||
report_invalid_renames: bool,
|
||||
payloads: Vec<PayloadAdder<'a>>,
|
||||
row_items: Option<RowItemsFn<'a>>,
|
||||
host_version: Option<u64>,
|
||||
document: Option<IdSalt>,
|
||||
select_groups: bool,
|
||||
}
|
||||
@@ -135,6 +136,7 @@ impl<'a> SwatchesPanel<'a> {
|
||||
report_invalid_renames: false,
|
||||
payloads: Vec::new(),
|
||||
row_items: None,
|
||||
host_version: None,
|
||||
document: None,
|
||||
select_groups: false,
|
||||
}
|
||||
@@ -240,6 +242,14 @@ impl<'a> SwatchesPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The version of everything the host's `row_items`, `takes_drop` and `drag_payload` closures read, as
|
||||
/// `PresetBrowser::host_version` takes it: while it holds and nothing reaches the swatches, their view repaints its
|
||||
/// last run instead of running in every pass.
|
||||
pub fn host_version(mut self, version: u64) -> Self {
|
||||
self.host_version = Some(version);
|
||||
self
|
||||
}
|
||||
|
||||
/// The document whose swatches the panel shows. The browser keeps its own state (an open rename field, the scroll
|
||||
/// position) for each document, so a rename left open in one document does not open on another document's
|
||||
/// swatch of the same name. Without it the browser keeps that state for the `Ui` it is shown in.
|
||||
@@ -274,6 +284,7 @@ impl<'a> SwatchesPanel<'a> {
|
||||
report_invalid_renames,
|
||||
payloads,
|
||||
row_items,
|
||||
host_version,
|
||||
document,
|
||||
select_groups,
|
||||
} = self;
|
||||
@@ -316,6 +327,9 @@ impl<'a> SwatchesPanel<'a> {
|
||||
if let Some(id) = document_id {
|
||||
browser = browser.browser_id(id);
|
||||
}
|
||||
if let Some(version) = host_version {
|
||||
browser = browser.host_version(version);
|
||||
}
|
||||
if let Some(options) = footer_options {
|
||||
browser = browser.footer(options);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::rc::Rc;
|
||||
use craft_behavior::Mixed;
|
||||
use craft_color_ui::ui::{
|
||||
ChannelRow, ChannelRowOutput, ChannelRule, ColorPicker, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerLayout, ColorPickerTab,
|
||||
ColorPopover, ColorReadout, ColorWarning, PickedColor, PickerLibrary, PickerSwatches,
|
||||
ColorPopover, ColorReadout, ColorWarning, PickedColor, PickedSwatch, PickerLibrary, PickerSwatches,
|
||||
};
|
||||
use craft_host::{AppInfo, Host};
|
||||
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId};
|
||||
@@ -509,6 +509,324 @@ fn the_color_picker_dialogs_swatch_view_marks_the_current_colour_and_a_pick_is_a
|
||||
assert!(fixture.texts().iter().any(|run| run.text == "No swatches"), "an empty library shows the notice");
|
||||
}
|
||||
|
||||
const SWATCH_RED: Srgba = Srgba { r: 1.0, g: 0.0, b: 0.0, a: 1.0 };
|
||||
const SWATCH_BLUE: Srgba = Srgba { r: 0.0, g: 0.0, b: 1.0, a: 1.0 };
|
||||
|
||||
/// A picker opened on red over two libraries, showing library 1: two swatches of one blue, and red.
|
||||
fn swatch_picker() -> (Rc<RefCell<DialogHost>>, Fixture) {
|
||||
let (red, blue) = (SWATCH_RED, SWATCH_BLUE);
|
||||
let id = dialog_id(("color-picker", "fill"));
|
||||
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let shown = Rc::clone(&dialogs);
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.room(vec2(900.0, 700.0));
|
||||
let libraries = vec![
|
||||
PickerLibrary::new("Basic", vec![(Label::from("Red"), red)]),
|
||||
PickerLibrary::new("Inks", vec![(Label::from("Blue A"), blue), (Label::from("Blue B"), blue), (Label::from("Ink Red"), red)]),
|
||||
];
|
||||
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red).swatch_view(PickerSwatches::new(libraries, "No swatches")));
|
||||
fixture.idle(6);
|
||||
let ctx = fixture.ctx().clone();
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatches", serde_json::json!(true)), Ok(()));
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(1)), Ok(()));
|
||||
fixture.idle(4);
|
||||
(dialogs, fixture)
|
||||
}
|
||||
|
||||
/// OK on the picker: its colour and the swatch it names.
|
||||
fn swatch_answer(dialogs: &Rc<RefCell<DialogHost>>, fixture: &Fixture) -> Option<(String, Option<PickedSwatch>)> {
|
||||
let ctx = fixture.ctx().clone();
|
||||
assert!(dialogs.borrow_mut().confirm::<ColorPickerDialog>(&ctx));
|
||||
dialogs.borrow_mut().take::<ColorPickerDialog>().and_then(DialogResult::ok).map(|result| (result.picked.color.to_hex(), result.swatch))
|
||||
}
|
||||
|
||||
/// OK names the swatch the colour was picked from, by its library and its place there, also among swatches of one
|
||||
/// colour and for a click on the colour already held; a later change to the colour leaves it named by none.
|
||||
#[trial]
|
||||
fn the_color_picker_dialog_answers_the_swatch_its_colour_was_picked_from() {
|
||||
let (red, blue) = (SWATCH_RED, SWATCH_BLUE);
|
||||
let id = dialog_id(("color-picker", "fill"));
|
||||
let open = swatch_picker;
|
||||
let answer = swatch_answer;
|
||||
let click = |fixture: &mut Fixture, name: &str| {
|
||||
let cell = fixture.by_label(name).unwrap_or_else(|| panic!("the swatch view shows {name}"));
|
||||
fixture.click(&cell).idle(4);
|
||||
};
|
||||
|
||||
let (dialogs, mut fixture) = open();
|
||||
click(&mut fixture, "Blue B");
|
||||
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 1)));
|
||||
let selected = |fixture: &Fixture, name: &str| {
|
||||
let cell = fixture.by_label(name).unwrap_or_else(|| panic!("the swatch view shows {name}"));
|
||||
fixture.tree().selected_of(cell.node).unwrap_or(false)
|
||||
};
|
||||
assert!(selected(&fixture, "Blue B") && !selected(&fixture, "Blue A"), "the clicked one of two blue swatches is marked");
|
||||
assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), Some(PickedSwatch::new(1, 1)))), "the second of two blue swatches");
|
||||
|
||||
let (dialogs, mut fixture) = open();
|
||||
click(&mut fixture, "Ink Red");
|
||||
assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), Some(PickedSwatch::new(1, 2)))), "a click on the colour already held");
|
||||
|
||||
let (dialogs, mut fixture) = open();
|
||||
click(&mut fixture, "Blue A");
|
||||
let ctx = fixture.ctx().clone();
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "color", serde_json::json!("#00ff00")), Ok(()));
|
||||
fixture.idle(2);
|
||||
assert_eq!(answer(&dialogs, &fixture), Some(("#00ff00".to_owned(), None)), "a colour set after the click is no swatch's");
|
||||
|
||||
let (dialogs, fixture) = open();
|
||||
assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), None)), "the opening colour was picked from no swatch");
|
||||
}
|
||||
|
||||
/// Automation picks a swatch by its place, as a click does, is refused a place the view does not have, and clears the
|
||||
/// pick with null; a refused batch of fields leaves the colour, the pick and the library as they were.
|
||||
#[trial]
|
||||
fn automation_picks_a_color_picker_swatch_and_a_refused_batch_restores_the_pick() {
|
||||
let (red, blue) = (SWATCH_RED, SWATCH_BLUE);
|
||||
let id = dialog_id(("color-picker", "fill"));
|
||||
let open = swatch_picker;
|
||||
let answer = swatch_answer;
|
||||
let (dialogs, fixture) = open();
|
||||
let ctx = fixture.ctx().clone();
|
||||
for bad in [serde_json::json!([1, 3]), serde_json::json!([2, 0]), serde_json::json!([1]), serde_json::json!("1,1")] {
|
||||
assert!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", bad.clone()).is_err(), "{bad} is refused");
|
||||
}
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::json!([1, 1])), Ok(()));
|
||||
let fields = dialogs.borrow().get::<ColorPickerDialog>().and_then(StackDialog::json_fields);
|
||||
assert_eq!(fields.as_ref().map(|f| f["swatch"].clone()), Some(serde_json::json!([1, 1])), "the fields report the picked swatch");
|
||||
assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), Some(PickedSwatch::new(1, 1)))), "a swatch picked by automation");
|
||||
|
||||
let (dialogs, fixture) = open();
|
||||
let ctx = fixture.ctx().clone();
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::json!([1, 1])), Ok(()));
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatch", serde_json::Value::Null), Ok(()));
|
||||
assert_eq!(dialog_field(&dialogs, "swatch"), Some(serde_json::Value::Null));
|
||||
assert_eq!(answer(&dialogs, &fixture), Some((blue.to_hex(), None)), "clearing the pick keeps its colour");
|
||||
|
||||
for picked in [None, Some(PickedSwatch::new(1, 1))] {
|
||||
let (dialogs, fixture) = open();
|
||||
let ctx = fixture.ctx().clone();
|
||||
if let Some(swatch) = picked {
|
||||
assert_eq!(dialogs.borrow_mut().get_mut::<ColorPickerDialog>().expect("the picker").pick_swatch(swatch), Some(()));
|
||||
}
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(0)), Ok(()));
|
||||
let before = dialogs.borrow().get::<ColorPickerDialog>().and_then(StackDialog::json_fields);
|
||||
let current = dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.current());
|
||||
for order in [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] {
|
||||
let edits = [
|
||||
("color".to_owned(), serde_json::json!("#00ff00")),
|
||||
("swatch".to_owned(), serde_json::json!([0, 0])),
|
||||
("library".to_owned(), serde_json::json!(1)),
|
||||
];
|
||||
let mut fields: Vec<_> = order.into_iter().map(|index| edits[index].clone()).collect();
|
||||
fields.push(("swatch".to_owned(), serde_json::json!([2, 0])));
|
||||
assert!(dialogs.borrow_mut().set_json_fields(&ctx, id, &fields).is_err());
|
||||
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(StackDialog::json_fields), before);
|
||||
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.current()), current);
|
||||
}
|
||||
let color = if picked.is_some() { blue } else { red };
|
||||
assert_eq!(answer(&dialogs, &fixture), Some((color.to_hex(), picked)), "a refused batch restores the earlier pick");
|
||||
}
|
||||
}
|
||||
|
||||
/// A tabbed picker shows no swatch view, so it refuses a swatch pick and keeps its colour.
|
||||
#[trial]
|
||||
fn a_tabbed_color_picker_refuses_swatch_picks() {
|
||||
let red = SWATCH_RED;
|
||||
let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)])];
|
||||
let mut dialog = ColorPickerDialog::new("fill", "Fill", red)
|
||||
.layout(ColorPickerDialogLayout::Tabbed)
|
||||
.swatch_view(PickerSwatches::new(libraries, "No swatches"));
|
||||
let before = dialog.json_fields();
|
||||
assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), None);
|
||||
assert_eq!(dialog.json_fields(), before);
|
||||
assert!(dialog.set_json_field(&egui::Context::default(), "swatch", serde_json::json!([0, 0])).is_err());
|
||||
assert_eq!(dialog.json_fields(), before);
|
||||
assert_eq!(dialog.current(), Some(PickedColor::rgb(red)));
|
||||
assert_eq!(dialog.picked_swatch(), None);
|
||||
|
||||
let mut dialog = dialog.layout(ColorPickerDialogLayout::Full);
|
||||
assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(()));
|
||||
let dialog = dialog.layout(ColorPickerDialogLayout::Tabbed);
|
||||
assert_eq!(dialog.current(), Some(PickedColor::rgb(SWATCH_BLUE)));
|
||||
assert_eq!(dialog.picked_swatch(), None);
|
||||
}
|
||||
|
||||
/// A refused batch of fields set before the dialog first runs leaves it as it was, and its start runs later as usual.
|
||||
#[trial]
|
||||
fn a_refused_color_picker_batch_restores_state_before_startup() {
|
||||
let opened = Srgba::from_hex("#123456").expect("a color outside the web colors");
|
||||
let snapped = Srgba::from_hex("#003366").expect("the nearest web color");
|
||||
let id = dialog_id(("color-picker", "fill"));
|
||||
for render in [false, true] {
|
||||
for picked in [None, Some(PickedSwatch::new(1, 0))] {
|
||||
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let shown = Rc::clone(&dialogs);
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.room(vec2(900.0, 700.0));
|
||||
fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-batch-test", name: "Picker test", version: "0" }).build()));
|
||||
fixture.idle(1);
|
||||
let ctx = fixture.ctx().clone();
|
||||
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED));
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(()));
|
||||
assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None)));
|
||||
|
||||
let libraries = vec![
|
||||
PickerLibrary::new("Basic", vec![(Label::from("Red"), SWATCH_RED)]),
|
||||
PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)]),
|
||||
];
|
||||
let request = craft_ui::runtime::requests::ColorRequest::new("fill", opened).on_swatches();
|
||||
let mut dialog =
|
||||
ColorPickerDialog::from_request(request).tab(ColorPickerTab::Custom).swatch_view(PickerSwatches::new(libraries, "No swatches"));
|
||||
if let Some(swatch) = picked {
|
||||
assert_eq!(dialog.pick_swatch(swatch), Some(()));
|
||||
}
|
||||
let before = dialog.json_fields();
|
||||
let current = dialog.current();
|
||||
assert!(dialog.set_json_field(&ctx, "swatch", serde_json::json!([2, 0])).is_err());
|
||||
assert_eq!(dialog.json_fields(), before);
|
||||
assert_eq!(dialog.opening(), Some(PickedColor::rgb(opened)));
|
||||
assert_eq!(dialog.current(), current);
|
||||
assert_eq!(dialog.picked_swatch(), picked);
|
||||
let fields = [("swatch".to_owned(), serde_json::json!([0, 0])), ("swatch".to_owned(), serde_json::json!([2, 0]))];
|
||||
assert!(dialog.set_json_fields(&ctx, &fields).is_err());
|
||||
assert_eq!(dialog.json_fields(), before);
|
||||
assert_eq!(dialog.opening(), Some(PickedColor::rgb(opened)));
|
||||
assert_eq!(dialog.current(), current);
|
||||
assert_eq!(dialog.picked_swatch(), picked);
|
||||
|
||||
dialogs.borrow_mut().open(dialog);
|
||||
if render {
|
||||
fixture.idle(6);
|
||||
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.opening()), Some(PickedColor::rgb(snapped)));
|
||||
}
|
||||
let color = if picked.is_some() { SWATCH_BLUE } else { snapped };
|
||||
assert_eq!(swatch_answer(&dialogs, &fixture), Some((color.to_hex(), picked)), "startup runs after a refused batch");
|
||||
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED));
|
||||
fixture.idle(6);
|
||||
assert_eq!(dialog_field(&dialogs, "tab"), Some(serde_json::json!("custom")));
|
||||
assert_eq!(dialog_field(&dialogs, "swatches"), Some(serde_json::json!(true)));
|
||||
assert_eq!(dialog_field(&dialogs, "library"), Some(serde_json::json!(usize::from(picked.is_some()))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Restoring the opening color clears an equal-color swatch selection.
|
||||
#[trial]
|
||||
fn restoring_the_current_color_clears_the_picked_swatch() {
|
||||
let (dialogs, mut fixture) = swatch_picker();
|
||||
let red = fixture.by_label("Ink Red").expect("the opening color's swatch");
|
||||
fixture.click(&red).idle(4);
|
||||
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 2)));
|
||||
let models = fixture.by_label("Color Models").expect("the model view button");
|
||||
fixture.click(&models).idle(4);
|
||||
let restore = fixture.by_label("Restore current color").expect("the compare block's current half");
|
||||
fixture.click(&restore).idle(4);
|
||||
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.picked_swatch()), None);
|
||||
assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None)));
|
||||
}
|
||||
|
||||
/// Opening model values leave a picked swatch's RGB-only result unchanged.
|
||||
#[trial]
|
||||
fn opening_model_values_do_not_change_a_picked_swatch() {
|
||||
let values = ModelValues::new("cmyk", &[0.0, 100.0, 100.0, 0.0]);
|
||||
let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Blue"), SWATCH_BLUE)])];
|
||||
let mut dialog = ColorPickerDialog::new("fill", "Fill", SWATCH_RED).swatch_view(PickerSwatches::new(libraries, "No swatches"));
|
||||
assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(()));
|
||||
let mut dialog = dialog.kept(values);
|
||||
assert_eq!(dialog.opening(), Some(PickedColor { color: SWATCH_RED, model: Some(values) }));
|
||||
assert_eq!(dialog.current(), Some(PickedColor::rgb(SWATCH_BLUE)));
|
||||
let result = dialog.confirm(&egui::Context::default()).expect("the selected swatch");
|
||||
assert_eq!(result.picked, PickedColor::rgb(SWATCH_BLUE));
|
||||
assert_eq!(result.swatch, Some(PickedSwatch::new(0, 0)));
|
||||
}
|
||||
|
||||
/// A swatch picked before the dialog first runs keeps its colour through the Only Web Colors snap, and OK remembers its
|
||||
/// library.
|
||||
#[trial]
|
||||
fn a_color_picker_swatch_picked_before_startup_survives_it() {
|
||||
let red = SWATCH_RED;
|
||||
let id = dialog_id(("color-picker", "fill"));
|
||||
let answer = swatch_answer;
|
||||
for render in [false, true] {
|
||||
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let shown = Rc::clone(&dialogs);
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.room(vec2(900.0, 700.0));
|
||||
fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-start-test", name: "Picker test", version: "0" }).build()));
|
||||
fixture.idle(1);
|
||||
let ctx = fixture.ctx().clone();
|
||||
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red));
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(()));
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "swatches", serde_json::json!(true)), Ok(()));
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "library", serde_json::json!(0)), Ok(()));
|
||||
assert_eq!(answer(&dialogs, &fixture), Some((red.to_hex(), None)));
|
||||
|
||||
let ink = Srgba::from_hex("#123456").expect("a colour outside the web colours");
|
||||
let libraries =
|
||||
vec![PickerLibrary::new("Basic", vec![(Label::from("Red"), red)]), PickerLibrary::new("Inks", vec![(Label::from("Ink"), ink)])];
|
||||
let mut dialog = ColorPickerDialog::new("fill", "Fill", red).swatch_view(PickerSwatches::new(libraries, "No swatches"));
|
||||
assert_eq!(dialog.pick_swatch(PickedSwatch::new(1, 0)), Some(()));
|
||||
dialogs.borrow_mut().open(dialog);
|
||||
if render {
|
||||
fixture.idle(6);
|
||||
}
|
||||
assert_eq!(answer(&dialogs, &fixture), Some((ink.to_hex(), Some(PickedSwatch::new(1, 0)))), "startup keeps the direct pick");
|
||||
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", red));
|
||||
fixture.idle(6);
|
||||
assert_eq!(dialog_field(&dialogs, "library"), Some(serde_json::json!(1)), "OK remembers the picked swatch's library");
|
||||
}
|
||||
}
|
||||
|
||||
/// Replacing the swatch view before startup keeps the selected color and clears its swatch identity.
|
||||
#[trial]
|
||||
fn replacing_the_swatch_view_before_startup_preserves_the_selected_color() {
|
||||
for render in [false, true] {
|
||||
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let shown = Rc::clone(&dialogs);
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.room(vec2(900.0, 700.0));
|
||||
fixture.host(std::sync::Arc::new(Host::builder(AppInfo { id: "swatch-replace-test", name: "Picker test", version: "0" }).build()));
|
||||
fixture.idle(1);
|
||||
let ctx = fixture.ctx().clone();
|
||||
let id = dialog_id(("color-picker", "fill"));
|
||||
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", SWATCH_RED));
|
||||
assert_eq!(dialogs.borrow_mut().set_json_field(&ctx, id, "webColors", serde_json::json!(true)), Ok(()));
|
||||
assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_RED.to_hex(), None)));
|
||||
|
||||
let ink = Srgba::from_hex("#123456").expect("a color outside the web colors");
|
||||
let libraries = vec![PickerLibrary::new("Inks", vec![(Label::from("Ink"), ink)])];
|
||||
let mut dialog = ColorPickerDialog::new("fill", "Fill", SWATCH_RED).swatch_view(PickerSwatches::new(libraries, "No swatches"));
|
||||
assert_eq!(dialog.pick_swatch(PickedSwatch::new(0, 0)), Some(()));
|
||||
let dialog = dialog.swatch_view(PickerSwatches::new(Vec::new(), "No swatches"));
|
||||
assert_eq!(dialog.picked_swatch(), None);
|
||||
assert_eq!(dialog.current(), Some(PickedColor::rgb(ink)));
|
||||
dialogs.borrow_mut().open(dialog);
|
||||
if render {
|
||||
fixture.idle(6);
|
||||
}
|
||||
assert_eq!(swatch_answer(&dialogs, &fixture), Some((ink.to_hex(), None)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Sampling the selected swatch's color from the canvas clears its swatch identity.
|
||||
#[trial]
|
||||
fn an_equal_color_canvas_sample_clears_the_picked_swatch() {
|
||||
let (dialogs, mut fixture) = swatch_picker();
|
||||
let blue = fixture.by_label("Blue B").expect("the blue swatch");
|
||||
fixture.click(&blue);
|
||||
fixture.settle();
|
||||
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.picked_swatch()), Some(PickedSwatch::new(1, 1)));
|
||||
let models = fixture.by_label("Color Models").expect("the model view button");
|
||||
fixture.click(&models);
|
||||
fixture.settle();
|
||||
dialogs.borrow_mut().get_mut::<ColorPickerDialog>().expect("the picker").requests().answer_eyedropper("fill", SWATCH_BLUE);
|
||||
fixture.settle();
|
||||
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.current()), Some(PickedColor::rgb(SWATCH_BLUE)));
|
||||
assert_eq!(dialogs.borrow().get::<ColorPickerDialog>().and_then(|d| d.picked_swatch()), None);
|
||||
assert_eq!(swatch_answer(&dialogs, &fixture), Some((SWATCH_BLUE.to_hex(), None)));
|
||||
}
|
||||
|
||||
/// The Compact picker's width is set by the area and the strip, and its rows take that width; its popover is as wide
|
||||
/// wherever the well stands and whatever the room.
|
||||
#[trial]
|
||||
|
||||
@@ -238,6 +238,7 @@ craft-shared-vec = { workspace = true, optional = true }
|
||||
craft-ease = { workspace = true, optional = true }
|
||||
craft-i18n-build = { workspace = true, optional = true }
|
||||
craft-pbr = { workspace = true, optional = true }
|
||||
craft-raster3d = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
ui = [
|
||||
@@ -490,6 +491,7 @@ file-formats-ase = ["file-formats", "craft-file-formats/ase"]
|
||||
file-formats-avif = ["file-formats", "craft-file-formats/avif"]
|
||||
file-formats-designcraft = ["file-formats", "craft-file-formats/designcraft"]
|
||||
file-formats-heif = ["file-formats", "craft-file-formats/heif"]
|
||||
file-formats-jp2 = ["file-formats", "craft-file-formats/jp2"]
|
||||
file-formats-kra = ["file-formats", "craft-file-formats/kra"]
|
||||
file-formats-office = ["file-formats", "craft-file-formats/office"]
|
||||
file-formats-ora = ["file-formats", "craft-file-formats/ora"]
|
||||
@@ -591,11 +593,25 @@ image-codecs-avif = ["image-codecs", "craft-image-codecs/avif"]
|
||||
image-codecs-avif-decode = ["image-codecs", "craft-image-codecs/avif-decode"]
|
||||
image-codecs-cms = ["image-codecs", "craft-image-codecs/cms"]
|
||||
image-codecs-corpus = ["image-codecs", "craft-image-codecs/corpus"]
|
||||
image-codecs-dds = ["image-codecs", "craft-image-codecs/dds"]
|
||||
image-codecs-dicom = ["image-codecs", "craft-image-codecs/dicom"]
|
||||
image-codecs-dpx = ["image-codecs", "craft-image-codecs/dpx"]
|
||||
image-codecs-exr = ["image-codecs", "craft-image-codecs/exr"]
|
||||
image-codecs-fits = ["image-codecs", "craft-image-codecs/fits"]
|
||||
image-codecs-heif = ["image-codecs", "craft-image-codecs/heif"]
|
||||
image-codecs-iff = ["image-codecs", "craft-image-codecs/iff"]
|
||||
image-codecs-jp2 = ["image-codecs", "craft-image-codecs/jp2"]
|
||||
image-codecs-jpegls = ["image-codecs", "craft-image-codecs/jpegls"]
|
||||
image-codecs-jxl = ["image-codecs", "craft-image-codecs/jxl"]
|
||||
image-codecs-jxl-encode = ["image-codecs", "craft-image-codecs/jxl-encode"]
|
||||
image-codecs-pnm = ["image-codecs", "craft-image-codecs/pnm"]
|
||||
image-codecs-sgi = ["image-codecs", "craft-image-codecs/sgi"]
|
||||
image-codecs-sunraster = ["image-codecs", "craft-image-codecs/sunraster"]
|
||||
image-codecs-tga = ["image-codecs", "craft-image-codecs/tga"]
|
||||
image-codecs-threads = ["image-codecs", "craft-image-codecs/threads"]
|
||||
image-codecs-tiff = ["image-codecs", "craft-image-codecs/tiff"]
|
||||
image-codecs-webp = ["image-codecs", "craft-image-codecs/webp"]
|
||||
image-codecs-xpm = ["image-codecs", "craft-image-codecs/xpm"]
|
||||
|
||||
imaging = ["dep:craft-imaging", "color-ui", "keymap"]
|
||||
|
||||
@@ -623,6 +639,7 @@ jxl-encode = ["jxl", "craft-jxl/encode"]
|
||||
|
||||
keymap = ["dep:craft-keymap"]
|
||||
keymap-egui = ["keymap", "craft-keymap/egui"]
|
||||
keymap-global = ["keymap", "craft-keymap/global"]
|
||||
|
||||
kiwi = ["dep:craft-kiwi"]
|
||||
|
||||
@@ -802,6 +819,8 @@ quit = ["dep:craft-quit"]
|
||||
|
||||
raster-codecs = ["dep:craft-raster-codecs"]
|
||||
|
||||
raster3d = ["dep:craft-raster3d"]
|
||||
|
||||
raw = ["dep:craft-raw"]
|
||||
raw-arw = ["raw", "craft-raw/arw"]
|
||||
raw-cr2 = ["raw", "craft-raw/cr2"]
|
||||
|
||||
@@ -331,6 +331,8 @@ pub use craft_pst as pst;
|
||||
pub use craft_quit as quit;
|
||||
#[cfg(feature = "raster-codecs")]
|
||||
pub use craft_raster_codecs as raster_codecs;
|
||||
#[cfg(feature = "raster3d")]
|
||||
pub use craft_raster3d as raster3d;
|
||||
#[cfg(feature = "raw")]
|
||||
pub use craft_raw as raw;
|
||||
#[cfg(feature = "review")]
|
||||
|
||||
@@ -11,6 +11,8 @@ mod style;
|
||||
mod tools;
|
||||
mod words;
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_behavior::geometry::{SelectionOperation, axis_or_diagonal};
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2};
|
||||
use craft_behavior::{
|
||||
@@ -72,7 +74,8 @@ pub enum BezierTool {
|
||||
/// handles; a handle drag moves that handle alone; a drag on a straight segment bends it, or moves the whole path
|
||||
/// when every anchor is selected.
|
||||
Convert,
|
||||
/// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools).
|
||||
/// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools). The overlay declares no part and no
|
||||
/// AccessKit object for its anchors and handles.
|
||||
Anchors,
|
||||
/// Add Anchor Point: a click on a segment, within 5 screen points of it, inserts an anchor at the hit's `t`
|
||||
/// ([`PathEdit::InsertAnchor`]); a drag inserts it and pulls out its handles as the Pen does
|
||||
@@ -394,6 +397,44 @@ struct Scene {
|
||||
selected: SelectedAnchors,
|
||||
}
|
||||
|
||||
/// A scene and what it was laid out from, kept on the overlay so that the later steps of the same pass reuse it.
|
||||
struct Laid {
|
||||
scene: Rc<Scene>,
|
||||
paths: Vec<EditPath>,
|
||||
view: CanvasView,
|
||||
rect: Rect,
|
||||
reach: f32,
|
||||
tool: BezierTool,
|
||||
}
|
||||
|
||||
impl Laid {
|
||||
/// Whether the scene is the one of `paths` with these view, rect, reach and tool: a step that sees other paths (an
|
||||
/// edit, a reset or the end of a press changed them) lays out its own.
|
||||
fn matches(&self, paths: &[EditPath], view: &CanvasView, rect: Rect, reach: f32, tool: BezierTool) -> bool {
|
||||
self.view == *view && self.rect == rect && self.reach.to_bits() == reach.to_bits() && self.tool == tool && self.paths == paths
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of scenes the overlay laid out on this thread, for trials that count the overlay's work.
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
pub(crate) mod laid {
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
static LAID: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Counts one scene laid out.
|
||||
pub(crate) fn add() {
|
||||
LAID.with(|laid| laid.set(laid.get() + 1));
|
||||
}
|
||||
|
||||
/// The scenes laid out since the last call, and starts the count again.
|
||||
pub(crate) fn take() -> usize {
|
||||
LAID.with(|laid| laid.replace(0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Paths with anchors and direction handles over a canvas, edited by the pointer and the keyboard as PhotoCraft's
|
||||
/// Direct Selection and Convert Point tools edit them. The value is the paths: a drag proposes them with the gesture's
|
||||
/// edit applied and Escape restores the start; [`BezierOutput::change`] carries the gesture's [`PathEdit`] from its
|
||||
@@ -420,7 +461,10 @@ struct Scene {
|
||||
/// [`path_options`](Self::path_options) change the look; [`hit_test`](Self::hit_test) answers the press priority
|
||||
/// without a pass.
|
||||
/// - The units and the zero point of the AccessKit values come from the canvas, and snapping of a dragged point is
|
||||
/// the canvas's [`Snap`].
|
||||
/// the canvas's [`Snap`]. Under [`BezierTool::Anchors`] the anchors and handles have no parts and no AccessKit
|
||||
/// objects.
|
||||
/// - A pass lays out its anchors, handles and segments once and its steps share them; a step that sees other paths
|
||||
/// (after an edit or a reset) lays them out again.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(canvas_control, content_painter)]
|
||||
pub struct BezierOverlay<'a> {
|
||||
@@ -447,6 +491,8 @@ pub struct BezierOverlay<'a> {
|
||||
report: Report,
|
||||
marquee: Option<DocRect>,
|
||||
hover_mark: Option<BezierHit>,
|
||||
/// The scene the latest step of this pass laid out.
|
||||
laid: Option<Laid>,
|
||||
}
|
||||
|
||||
impl<'a> BezierOverlay<'a> {
|
||||
@@ -464,6 +510,7 @@ impl<'a> BezierOverlay<'a> {
|
||||
report: Report::default(),
|
||||
marquee: None,
|
||||
hover_mark: None,
|
||||
laid: None,
|
||||
}
|
||||
.label(label)
|
||||
}
|
||||
@@ -483,6 +530,8 @@ impl<'a> BezierOverlay<'a> {
|
||||
if limited {
|
||||
return Scene { items, limited, selected: SelectedAnchors::default() };
|
||||
}
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
laid::add();
|
||||
let selected = SelectedAnchors::of(self.selection);
|
||||
let near = rect.expand(reach);
|
||||
let shown =
|
||||
@@ -567,6 +616,17 @@ impl<'a> BezierOverlay<'a> {
|
||||
Scene { items, limited, selected }
|
||||
}
|
||||
|
||||
/// The scene of `paths`: the one an earlier step of this pass laid out from equal paths with the same view, rect,
|
||||
/// reach and tool, else a new one, kept for the later steps.
|
||||
fn scene_of(&mut self, paths: &[EditPath], view: &CanvasView, rect: Rect, reach: f32) -> Rc<Scene> {
|
||||
if let Some(laid) = self.laid.as_ref().filter(|laid| laid.matches(paths, view, rect, reach, self.tool)) {
|
||||
return Rc::clone(&laid.scene);
|
||||
}
|
||||
let scene = Rc::new(self.scene(paths, view, rect, reach));
|
||||
self.laid = Some(Laid { scene: Rc::clone(&scene), paths: paths.to_vec(), view: *view, rect, reach, tool: self.tool });
|
||||
scene
|
||||
}
|
||||
|
||||
/// Whether the press on `item` is the tool's.
|
||||
fn takes(&self, item: &Item) -> bool {
|
||||
self.tool.takes(&item.proxy(), item.interior, item.straight)
|
||||
@@ -1304,20 +1364,24 @@ impl Component for BezierOverlay<'_> {
|
||||
|
||||
/// The anchors and shown handles in view, then the segments the tool takes, and under Direct Selection one part
|
||||
/// below them all for the marquee. The anchors and handles are one roving group in keyboard order: one Tab stop,
|
||||
/// arriving at the first selected anchor. The Page keys, Home and End are the overlay's own moves.
|
||||
/// arriving at the first selected anchor. The Page keys, Home and End are the overlay's own moves. Anchors declares
|
||||
/// none.
|
||||
fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let held = cx.press_slot::<Held>();
|
||||
self.press_tool(held.as_ref());
|
||||
let Some(space) = canvas_space(&cx.env) else { return };
|
||||
let reach = cx.style.reach;
|
||||
let scene = match &held {
|
||||
Some(held) => self.scene(&held.start, &space.view, rect, reach),
|
||||
Some(held) => self.scene_of(&held.start, &space.view, rect, reach),
|
||||
None => {
|
||||
let Some(paths) = cx.value() else { return };
|
||||
self.scene(paths, &space.view, rect, reach)
|
||||
self.scene_of(paths, &space.view, rect, reach)
|
||||
}
|
||||
};
|
||||
let focusable = self.tool != BezierTool::Anchors;
|
||||
// Anchors draws the anchors and handles without parts: nothing of them takes a press or the keyboard.
|
||||
if self.tool == BezierTool::Anchors {
|
||||
return;
|
||||
}
|
||||
if self.tool == BezierTool::Direct && !scene.limited {
|
||||
cx.part(MARQUEE, HitShape::Rect(rect))
|
||||
.sense(Sense::DRAG.union(Sense::CLICK).union(Sense::TAKE_FOCUS))
|
||||
@@ -1333,7 +1397,7 @@ impl Component for BezierOverlay<'_> {
|
||||
let arrival = self.selection.path.zip(self.selection.anchors.first().copied());
|
||||
for item in &scene.items {
|
||||
let press = self.takes(item);
|
||||
let keyboard = item.kind != Kind::Segment && item.shown && focusable;
|
||||
let keyboard = item.kind != Kind::Segment && item.shown;
|
||||
let selected = item.kind == Kind::Anchor && scene.selected.has_anchor(item.key, item.knot);
|
||||
let part = cx.part(item.part(), item.shape.clone()).priority(item.priority());
|
||||
let part = if press { part.sense(PRESS) } else { part };
|
||||
@@ -1349,7 +1413,7 @@ impl Component for BezierOverlay<'_> {
|
||||
part.selected();
|
||||
}
|
||||
}
|
||||
if focusable && scene.items.iter().any(|item| item.kind != Kind::Segment && item.shown) {
|
||||
if scene.items.iter().any(|item| item.kind != Kind::Segment && item.shown) {
|
||||
cx.roving(Roving::new(NavShape::Flat).home_end(false));
|
||||
}
|
||||
}
|
||||
@@ -1360,7 +1424,7 @@ impl Component for BezierOverlay<'_> {
|
||||
let held = cx.press_slot::<Held>().clone();
|
||||
let Some(paths) = held.as_ref().map(|held| held.start.clone()).or_else(|| cx.value().cloned()) else { return };
|
||||
self.press_tool(held.as_ref());
|
||||
let scene = self.scene(&paths, &space.view, cx.rect, cx.style.reach);
|
||||
let scene = self.scene_of(&paths, &space.view, cx.rect, cx.style.reach);
|
||||
self.run_pointer(cx, &space, &scene, &paths);
|
||||
self.run_keys(cx, &space, &scene, &paths);
|
||||
}
|
||||
@@ -1368,7 +1432,7 @@ impl Component for BezierOverlay<'_> {
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let (Some(space), Some(paths)) = (canvas_space(&cx.env), cx.value()) else { return };
|
||||
let (view, style) = (space.view, &cx.style);
|
||||
let scene = self.scene(paths, &view, cx.rect, style.reach);
|
||||
let scene = self.scene_of(paths, &view, cx.rect, style.reach);
|
||||
let options = self.path_options;
|
||||
let thickness = options.and_then(|options| options.thickness);
|
||||
let option_color =
|
||||
@@ -1484,10 +1548,21 @@ impl Component for BezierOverlay<'_> {
|
||||
}
|
||||
|
||||
/// A graphics object per anchor and shown handle, named "Anchor 3 of 12", "In handle" and "Out handle" and valued
|
||||
/// in the canvas's units. None above [`MAX_ANCHORS`].
|
||||
/// in the canvas's units. None above [`MAX_ANCHORS`] or under [`BezierTool::Anchors`].
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
if self.tool == BezierTool::Anchors {
|
||||
return;
|
||||
}
|
||||
let (Some(space), Some(paths)) = (canvas_space(&cx.env), cx.value()) else { return };
|
||||
let scene = self.scene(paths, &space.view, cx.rect, cx.style.reach);
|
||||
let (rect, reach) = (cx.rect, cx.style.reach);
|
||||
let built;
|
||||
let scene = match self.laid.as_ref().filter(|laid| laid.matches(paths, &space.view, rect, reach, self.tool)) {
|
||||
Some(laid) => &*laid.scene,
|
||||
None => {
|
||||
built = self.scene(paths, &space.view, rect, reach);
|
||||
&built
|
||||
}
|
||||
};
|
||||
let (words, units, rulers) = (cx.words::<BezierWords>(), cx.env.units(), space.rulers());
|
||||
for item in scene.items.iter().filter(|item| item.kind != Kind::Segment && item.shown) {
|
||||
let Some(knot) = paths[item.path].knot(item.knot) else { continue };
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets};
|
||||
use craft_behavior::kurbo::{ParamCurve as _, Point, Size, Vec2};
|
||||
use craft_behavior::{CanvasView, EditEvent};
|
||||
use craft_behavior::{CanvasView, EditEvent, PartKey};
|
||||
use craft_draw::ui::{
|
||||
AnchorDelete, AnchorTool, AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef,
|
||||
PathEdit, PathSelection, PathTool, SegmentMark,
|
||||
@@ -11,6 +11,7 @@ use craft_ui::canvas::{Canvas, Guide, Momentary, NavigationOptions, Snap, ToolHo
|
||||
use craft_ui::canvas_controls::Guides;
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::primitives::cancel_press_of;
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
use egui::{Id, Pos2, Vec2 as ScreenVec, vec2};
|
||||
use std::cell::RefCell;
|
||||
@@ -530,6 +531,55 @@ fn a_frame_reads_the_selections_anchor_lists_in_proportion_to_the_selection() {
|
||||
assert!(large < small * 3, "{small} entries read for 60 selected paths, {large} for 120");
|
||||
}
|
||||
|
||||
// A pass lays out the anchors, handles and segments once for all of its steps (parts, update, paint, access): a frame
|
||||
// at rest lays out one scene per pass.
|
||||
#[trial]
|
||||
fn a_pass_lays_out_the_overlays_scene_once() {
|
||||
for tool in [BezierTool::Direct, BezierTool::Anchors] {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| (st.tool, st.selection) = (tool, sel(1, &[(0, 1)])));
|
||||
craft_draw::ui::pen::bezier::laid::take();
|
||||
h.fixture.frame(Vec::new());
|
||||
let (laid, passes) = (craft_draw::ui::pen::bezier::laid::take(), h.fixture.passes());
|
||||
assert!(passes > 0, "{tool:?}: the frame ran");
|
||||
assert_eq!(laid, passes, "{tool:?}: {laid} scenes laid out in {passes} passes");
|
||||
}
|
||||
}
|
||||
|
||||
// A step that sees other paths than the one before it lays out its own scene: the pass of an arrow nudge paints the
|
||||
// moved anchor where the next frame, at rest, paints it.
|
||||
#[trial]
|
||||
fn the_pass_of_an_edit_paints_the_edited_anchors() {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| st.selection = sel(1, &[(0, 1)]));
|
||||
h.fixture.key(egui::Key::Tab, egui::Modifiers::NONE).key(egui::Key::Tab, egui::Modifiers::NONE).settle();
|
||||
let arrow = egui::Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
let nudged = format!("{:?}", h.fixture.frame_shapes_with(vec![arrow]));
|
||||
assert!(matches!(h.last_change(), Some(PathEdit::MoveAnchors { path: 1, .. })), "{:?}", h.last_change());
|
||||
let rest = format!("{:?}", h.fixture.frame_shapes());
|
||||
assert_eq!(nudged, rest, "the nudge's pass paints the anchors of the nudged paths");
|
||||
}
|
||||
|
||||
// Under Anchors the overlay draws the anchors without declaring them: no part of an anchor and no AccessKit object,
|
||||
// where Direct Selection declares both. The anchors still draw.
|
||||
#[trial]
|
||||
fn anchors_draws_its_anchors_with_no_part_and_no_accesskit_object() {
|
||||
for (tool, declared) in [(BezierTool::Direct, true), (BezierTool::Anchors, false)] {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| (st.tool, st.selection) = (tool, sel(1, &[(0, 1)])));
|
||||
let id = h.state.borrow().id;
|
||||
assert_eq!(h.fixture.part_rect(id, PartKey::new("anchor").at(0)).is_some(), declared, "{tool:?}: the first anchor's part");
|
||||
let objects = h.fixture.by_role(Role::GRAPHICS_OBJECT).len();
|
||||
assert_eq!(objects > 0, declared, "{tool:?}: {objects} AccessKit objects");
|
||||
}
|
||||
let shapes = |anchors: AnchorsShown| {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| (st.tool, st.anchors, st.selection) = (BezierTool::Anchors, anchors, sel(1, &[(0, 1)])));
|
||||
h.fixture.frame_shapes().len()
|
||||
};
|
||||
assert!(shapes(AnchorsShown::All) > shapes(AnchorsShown::Hidden), "Anchors draws the anchors that outlines only leave out");
|
||||
}
|
||||
|
||||
// Hovering a segment under Add reports the segment with its parameter, which the preview anchor stands at.
|
||||
|
||||
// `AnchorsShown::Hidden` draws outlines only: no anchor, no handle, no part, no AccessKit object.
|
||||
|
||||
+223
-42
@@ -1,7 +1,8 @@
|
||||
//! Bounded conversion of common planar DXF entities into neutral Bézier paths.
|
||||
//!
|
||||
//! This is geometry extraction, not a full CAD scene renderer: unsupported entities such as
|
||||
//! text, dimensions, meshes, and block inserts are reported as warnings and omitted.
|
||||
//! This is geometry extraction, not a full CAD scene renderer: block inserts are expanded
|
||||
//! (scaled, rotated, arrayed and nested up to [`MAX_INSERT_DEPTH`] levels), while unsupported
|
||||
//! entities such as text, dimensions and meshes are reported as warnings and omitted.
|
||||
|
||||
use kurbo::{BezPath, Point, Rect, Shape as _};
|
||||
|
||||
@@ -39,51 +40,16 @@ pub fn import(bytes: &[u8]) -> Result<Imported, Error> {
|
||||
let unit_to_mm = units_to_mm(drawing.header.insunits(), drawing.header.measurement());
|
||||
let layer_visibility: std::collections::HashMap<_, _> =
|
||||
drawing.layers().into_iter().map(|layer| (layer.name, layer.on && !layer.frozen)).collect();
|
||||
let mut paths = Vec::new();
|
||||
let blocks: std::collections::HashMap<&str, &crate::model::Block<'_>> = drawing.blocks.iter().map(|b| (b.name, b)).collect();
|
||||
let mut state = State { paths: Vec::new(), unsupported: 0, elements: 0, layers: &layer_visibility, blocks: &blocks };
|
||||
let mut warnings = Vec::new();
|
||||
let mut unsupported = 0usize;
|
||||
let mut elements = 0usize;
|
||||
for record in &drawing.entities {
|
||||
let entity = crate::model::Entity::read(record);
|
||||
if !entity.common.visible || record.paper_space() || layer_visibility.get(&entity.common.layer) == Some(&false) {
|
||||
if record.paper_space() {
|
||||
continue;
|
||||
}
|
||||
if excessive_sweep(&entity.kind) {
|
||||
return Err(Error::TooManySegments);
|
||||
}
|
||||
let remaining = MAX_PATH_ELEMENTS.saturating_sub(elements);
|
||||
if estimated_elements(&entity.kind) > remaining {
|
||||
return Err(Error::TooManySegments);
|
||||
}
|
||||
let converted = if let crate::model::EntityKind::Spline(spline) = &entity.kind {
|
||||
spline_path(spline)?.into_iter().collect()
|
||||
} else {
|
||||
entity_paths(&entity.kind, entity.common.extrusion)
|
||||
};
|
||||
if converted.iter().flat_map(|path| path.elements()).any(|element| {
|
||||
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
|
||||
match *element {
|
||||
kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => !finite(p),
|
||||
kurbo::PathEl::QuadTo(a, b) => !finite(a) || !finite(b),
|
||||
kurbo::PathEl::CurveTo(a, b, c) => !finite(a) || !finite(b) || !finite(c),
|
||||
kurbo::PathEl::ClosePath => false,
|
||||
}
|
||||
}) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
if converted.is_empty() {
|
||||
unsupported = unsupported.saturating_add(1);
|
||||
continue;
|
||||
}
|
||||
elements = elements.saturating_add(converted.iter().map(|path| path.elements().len()).sum::<usize>());
|
||||
if elements > MAX_PATH_ELEMENTS {
|
||||
return Err(Error::TooManySegments);
|
||||
}
|
||||
if paths.len().saturating_add(converted.len()) > MAX_PATHS {
|
||||
return Err(Error::TooManyPaths);
|
||||
}
|
||||
paths.extend(converted);
|
||||
convert(&mut state, record, kurbo::Affine::IDENTITY, 0)?;
|
||||
}
|
||||
let State { paths, unsupported, .. } = state;
|
||||
if unsupported > 0 {
|
||||
warnings.push(format!("{unsupported} visible DXF entities are unsupported and were omitted"));
|
||||
}
|
||||
@@ -94,6 +60,100 @@ pub fn import(bytes: &[u8]) -> Result<Imported, Error> {
|
||||
Ok(Imported { paths, bounds, unit_to_mm, warnings })
|
||||
}
|
||||
|
||||
/// The deepest chain of block inserts expanded (deeper ones are omitted with a warning).
|
||||
pub const MAX_INSERT_DEPTH: usize = 16;
|
||||
/// The most copies one arrayed insert makes.
|
||||
const MAX_INSERT_COPIES: i64 = 10_000;
|
||||
|
||||
struct State<'s, 'a> {
|
||||
paths: Vec<BezPath>,
|
||||
unsupported: usize,
|
||||
elements: usize,
|
||||
layers: &'s std::collections::HashMap<String, bool>,
|
||||
blocks: &'s std::collections::HashMap<&'a str, &'s crate::model::Block<'a>>,
|
||||
}
|
||||
|
||||
/// Convert one entity record through `transform`, expanding block inserts.
|
||||
fn convert(state: &mut State<'_, '_>, record: &crate::model::EntityRecord<'_>, transform: kurbo::Affine, depth: usize) -> Result<(), Error> {
|
||||
let entity = crate::model::Entity::read(record);
|
||||
if !entity.common.visible || state.layers.get(&entity.common.layer) == Some(&false) {
|
||||
return Ok(());
|
||||
}
|
||||
if let crate::model::EntityKind::Insert(insert) = &entity.kind {
|
||||
let Some(block) = state.blocks.get(insert.block.trim()).copied() else {
|
||||
state.unsupported = state.unsupported.saturating_add(1);
|
||||
return Ok(());
|
||||
};
|
||||
if depth >= MAX_INSERT_DEPTH {
|
||||
state.unsupported = state.unsupported.saturating_add(1);
|
||||
return Ok(());
|
||||
}
|
||||
let [bx, by, _] = block.groups().point(10);
|
||||
let [ix, iy, _] = insert.insert;
|
||||
let [sx, sy, _] = insert.scale;
|
||||
let (columns, rows) = (insert.columns.max(1), insert.rows.max(1));
|
||||
if columns.saturating_mul(rows) > MAX_INSERT_COPIES {
|
||||
return Err(Error::TooManyPaths);
|
||||
}
|
||||
let all_finite = [bx, by, ix, iy, sx, sy, insert.rotation, insert.column_spacing, insert.row_spacing].iter().all(|v| v.is_finite());
|
||||
if !all_finite {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
for row in 0..rows {
|
||||
for column in 0..columns {
|
||||
// Array offsets are along the insert's rotated axes, before scaling.
|
||||
let offset = kurbo::Vec2::new(column as f64 * insert.column_spacing, row as f64 * insert.row_spacing);
|
||||
let local = kurbo::Affine::translate((ix, iy))
|
||||
* kurbo::Affine::rotate(insert.rotation.to_radians())
|
||||
* kurbo::Affine::translate(offset)
|
||||
* kurbo::Affine::scale_non_uniform(sx, sy)
|
||||
* kurbo::Affine::translate((-bx, -by));
|
||||
for child in &block.entities {
|
||||
convert(state, child, transform * local, depth + 1)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if excessive_sweep(&entity.kind) {
|
||||
return Err(Error::TooManySegments);
|
||||
}
|
||||
let remaining = MAX_PATH_ELEMENTS.saturating_sub(state.elements);
|
||||
if estimated_elements(&entity.kind) > remaining {
|
||||
return Err(Error::TooManySegments);
|
||||
}
|
||||
let converted: Vec<BezPath> = if let crate::model::EntityKind::Spline(spline) = &entity.kind {
|
||||
spline_path(spline)?.into_iter().collect()
|
||||
} else {
|
||||
entity_paths(&entity.kind, entity.common.extrusion)
|
||||
};
|
||||
let converted: Vec<BezPath> = converted.into_iter().map(|path| transform * path).collect();
|
||||
if converted.iter().flat_map(|path| path.elements()).any(|element| {
|
||||
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
|
||||
match *element {
|
||||
kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => !finite(p),
|
||||
kurbo::PathEl::QuadTo(a, b) => !finite(a) || !finite(b),
|
||||
kurbo::PathEl::CurveTo(a, b, c) => !finite(a) || !finite(b) || !finite(c),
|
||||
kurbo::PathEl::ClosePath => false,
|
||||
}
|
||||
}) {
|
||||
return Err(Error::NonFinite);
|
||||
}
|
||||
if converted.is_empty() {
|
||||
state.unsupported = state.unsupported.saturating_add(1);
|
||||
return Ok(());
|
||||
}
|
||||
state.elements = state.elements.saturating_add(converted.iter().map(|path| path.elements().len()).sum::<usize>());
|
||||
if state.elements > MAX_PATH_ELEMENTS {
|
||||
return Err(Error::TooManySegments);
|
||||
}
|
||||
if state.paths.len().saturating_add(converted.len()) > MAX_PATHS {
|
||||
return Err(Error::TooManyPaths);
|
||||
}
|
||||
state.paths.extend(converted);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn estimated_elements(kind: &crate::model::EntityKind) -> usize {
|
||||
use crate::model::EntityKind as E;
|
||||
let arc_count = |sweep: f64| (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil().max(1.0) as usize;
|
||||
@@ -857,3 +917,124 @@ mod spline_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod insert_tests {
|
||||
use super::*;
|
||||
|
||||
/// A DXF with the given BLOCKS and ENTITIES section bodies (group-code / value pairs).
|
||||
fn dxf(blocks: &[(&str, &str)], entities: &[(&str, &str)]) -> Vec<u8> {
|
||||
let mut out = String::from("0\nSECTION\n2\nBLOCKS\n");
|
||||
for (code, value) in blocks {
|
||||
out.push_str(&format!("{code}\n{value}\n"));
|
||||
}
|
||||
out.push_str("0\nENDSEC\n0\nSECTION\n2\nENTITIES\n");
|
||||
for (code, value) in entities {
|
||||
out.push_str(&format!("{code}\n{value}\n"));
|
||||
}
|
||||
out.push_str("0\nENDSEC\n0\nEOF\n");
|
||||
out.into_bytes()
|
||||
}
|
||||
|
||||
/// Block `name` with base point (`bx`, `by`) holding one line from (bx, by) to (bx + 10, by).
|
||||
fn block(name: &'static str, bx: &'static str, by: &'static str, x1: &'static str) -> Vec<(&'static str, &'static str)> {
|
||||
vec![
|
||||
("0", "BLOCK"),
|
||||
("8", "0"),
|
||||
("2", name),
|
||||
("70", "0"),
|
||||
("10", bx),
|
||||
("20", by),
|
||||
("30", "0"),
|
||||
("0", "LINE"),
|
||||
("8", "0"),
|
||||
("10", bx),
|
||||
("20", by),
|
||||
("30", "0"),
|
||||
("11", x1),
|
||||
("21", by),
|
||||
("31", "0"),
|
||||
("0", "ENDBLK"),
|
||||
]
|
||||
}
|
||||
|
||||
fn ends(imported: &Imported) -> Vec<(f64, f64, f64, f64)> {
|
||||
imported
|
||||
.paths
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let b = p.bounding_box();
|
||||
let r = |v: f64| (v * 1000.0).round() / 1000.0;
|
||||
(r(b.x0), r(b.y0), r(b.x1), r(b.y1))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserts_place_their_blocks_scaled_rotated_and_arrayed() {
|
||||
let b = block("SEG", "5", "5", "15");
|
||||
// Insert at (100, 0), scale 2 in x, rotated 90°: the 10-long line from the base point
|
||||
// becomes 20 long, pointing up from (100, 0).
|
||||
let one =
|
||||
dxf(&b, &[("0", "INSERT"), ("8", "0"), ("2", "SEG"), ("10", "100"), ("20", "0"), ("30", "0"), ("41", "2"), ("42", "1"), ("50", "90")]);
|
||||
let got = import(&one).unwrap();
|
||||
assert_eq!(ends(&got), vec![(100.0, 0.0, 100.0, 20.0)]);
|
||||
assert!(got.warnings.is_empty(), "{:?}", got.warnings);
|
||||
// A 3 × 2 array, 30 apart in columns and 7 in rows.
|
||||
let array = dxf(
|
||||
&b,
|
||||
&[("0", "INSERT"), ("8", "0"), ("2", "SEG"), ("10", "0"), ("20", "0"), ("30", "0"), ("70", "3"), ("71", "2"), ("44", "30"), ("45", "7")],
|
||||
);
|
||||
let got = import(&array).unwrap();
|
||||
assert_eq!(got.paths.len(), 6);
|
||||
assert!(ends(&got).contains(&(60.0, 7.0, 70.0, 7.0)), "{:?}", ends(&got));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_blocks_expand_and_self_reference_stops() {
|
||||
let mut blocks = block("INNER", "0", "0", "10");
|
||||
blocks.extend([
|
||||
("0", "BLOCK"),
|
||||
("8", "0"),
|
||||
("2", "OUTER"),
|
||||
("70", "0"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("30", "0"),
|
||||
("0", "INSERT"),
|
||||
("8", "0"),
|
||||
("2", "INNER"),
|
||||
("10", "50"),
|
||||
("20", "50"),
|
||||
("30", "0"),
|
||||
("0", "ENDBLK"),
|
||||
("0", "BLOCK"),
|
||||
("8", "0"),
|
||||
("2", "LOOP"),
|
||||
("70", "0"),
|
||||
("10", "0"),
|
||||
("20", "0"),
|
||||
("30", "0"),
|
||||
("0", "INSERT"),
|
||||
("8", "0"),
|
||||
("2", "LOOP"),
|
||||
("10", "1"),
|
||||
("20", "0"),
|
||||
("30", "0"),
|
||||
("0", "ENDBLK"),
|
||||
]);
|
||||
let got = import(&dxf(&blocks, &[("0", "INSERT"), ("8", "0"), ("2", "OUTER"), ("10", "10"), ("20", "0"), ("30", "0")])).unwrap();
|
||||
assert_eq!(ends(&got), vec![(60.0, 50.0, 70.0, 50.0)]);
|
||||
let looped = import(&dxf(&blocks, &[("0", "INSERT"), ("8", "0"), ("2", "LOOP"), ("10", "0"), ("20", "0"), ("30", "0")])).unwrap();
|
||||
assert!(looped.paths.is_empty());
|
||||
assert!(!looped.warnings.is_empty(), "the cut-off chain is reported");
|
||||
// A missing block and an absurd array are reported, not crashes.
|
||||
let missing = import(&dxf(&[], &[("0", "INSERT"), ("8", "0"), ("2", "NOPE"), ("10", "0"), ("20", "0"), ("30", "0")])).unwrap();
|
||||
assert!(!missing.warnings.is_empty());
|
||||
let huge = dxf(
|
||||
&block("SEG", "0", "0", "1"),
|
||||
&[("0", "INSERT"), ("8", "0"), ("2", "SEG"), ("10", "0"), ("20", "0"), ("30", "0"), ("70", "100000"), ("71", "100000")],
|
||||
);
|
||||
assert!(import(&huge).is_err());
|
||||
}
|
||||
}
|
||||
@@ -150,6 +150,9 @@ impl<'de> Deserialize<'de> for BranchIndex {
|
||||
pub struct Header {
|
||||
pub version: Option<u64>,
|
||||
pub images: Option<Vec<String>>,
|
||||
/// Stored dimensions, retained even when a consumer cannot decode an image's codec.
|
||||
/// These are untrusted metadata, not permission to allocate a pixel buffer.
|
||||
pub image_dimensions: std::collections::BTreeMap<String, (u32, u32)>,
|
||||
}
|
||||
|
||||
pub fn read_header(text: &str) -> Result<Header, serde_json::Error> {
|
||||
@@ -170,10 +173,20 @@ impl<'de> Deserialize<'de> for Header {
|
||||
match k.as_str() {
|
||||
"version" => h.version = m.next_value::<Value>()?.as_u64(),
|
||||
"imageIndex" => {
|
||||
h.images = m
|
||||
.next_value::<Value>()?
|
||||
let value = m.next_value::<Value>()?;
|
||||
h.images =
|
||||
value.as_array().map(|a| a.iter().filter_map(|v| v.get("hash").and_then(Value::as_str).map(str::to_owned)).collect());
|
||||
h.image_dimensions = value
|
||||
.as_array()
|
||||
.map(|a| a.iter().filter_map(|v| v.get("hash").and_then(Value::as_str).map(str::to_owned)).collect())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|v| {
|
||||
let hash = v.get("hash")?.as_str()?.to_owned();
|
||||
let width = u32::try_from(v.get("width")?.as_u64()?).ok()?;
|
||||
let height = u32::try_from(v.get("height")?.as_u64()?).ok()?;
|
||||
Some((hash, (width, height)))
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
_ => {
|
||||
m.next_value::<IgnoredAny>()?;
|
||||
@@ -324,6 +337,17 @@ pub fn write_document_json<D: Serialize, W: std::io::Write>(doc: &D, images: &[I
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn image_dimensions_survive_the_native_envelope() {
|
||||
let images = [super::ImageIndexEntry { hash: "original-image".into(), width: 731, height: 419 }];
|
||||
let mut json = Vec::new();
|
||||
super::write_document_json(&serde_json::json!({"name":"original fixture"}), &images, &mut json).unwrap();
|
||||
let header = super::read_header(std::str::from_utf8(&json).unwrap()).unwrap();
|
||||
assert_eq!(header.image_dimensions.get(&images[0].hash), Some(&(images[0].width, images[0].height)));
|
||||
let legacy = super::read_header(r#"{"imageIndex":[{"hash":"legacy"},{"hash":"overflow","width":4294967296,"height":1}]}"#).unwrap();
|
||||
assert_eq!(legacy.images.unwrap().len(), 2);
|
||||
assert!(legacy.image_dimensions.is_empty());
|
||||
}
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
@@ -437,8 +461,8 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn newer_version_is_reported_before_document_decode() {
|
||||
assert_eq!(check_version(&Header { version: Some(2), images: None }), Err(NewerVersion(2)));
|
||||
assert_eq!(check_version(&Header { version: Some(u64::MAX), images: None }), Err(NewerVersion(u32::MAX)));
|
||||
assert_eq!(check_version(&Header { version: Some(2), ..Header::default() }), Err(NewerVersion(2)));
|
||||
assert_eq!(check_version(&Header { version: Some(u64::MAX), ..Header::default() }), Err(NewerVersion(u32::MAX)));
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Payload {
|
||||
|
||||
@@ -27,6 +27,7 @@ default = []
|
||||
raster-codecs = ["dep:craft-image-codecs"]
|
||||
heif = ["raster-codecs", "craft-image-codecs/heif"]
|
||||
avif = ["raster-codecs", "craft-image-codecs/avif"]
|
||||
jp2 = ["raster-codecs", "craft-image-codecs/jp2"]
|
||||
pdf = []
|
||||
svg = []
|
||||
ora = ["dep:craft-ora"]
|
||||
|
||||
@@ -12,7 +12,7 @@ craft-file-formats = { workspace = true }
|
||||
craft-raster-codecs = { workspace = true }
|
||||
craft-svg = { workspace = true }
|
||||
craft-dxf = { workspace = true }
|
||||
craft-pdf = { workspace = true, features = ["paths", "write"] }
|
||||
craft-pdf = { workspace = true, features = ["paths", "write", "raster"] }
|
||||
craft-eps = { workspace = true, features = ["paths"] }
|
||||
kurbo = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -311,6 +311,40 @@ fn import_dxf(bytes: &[u8], format: ImportFormat, limits: Limits) -> Result<Impo
|
||||
Ok(Imported::Vector(VectorScene { format, width_mm, height_mm, shapes, warnings: imported.warnings, dropped_warnings: 0 }))
|
||||
}
|
||||
|
||||
/// A PDF page drawn as a picture at `dpi`, over white: everything on it (images, text, fills),
|
||||
/// for an app that places the page as an image instead of reading its vector paths. Bounded by
|
||||
/// `limits` (input size and raster size); `dpi` is 1–1200.
|
||||
pub fn render_pdf_page(bytes: &[u8], page: usize, dpi: f64, limits: Limits) -> Result<RasterImage, Error> {
|
||||
if bytes.len() > limits.max_input_bytes {
|
||||
return Err(Error::InputLimit { size: bytes.len(), limit: limits.max_input_bytes });
|
||||
}
|
||||
if !(dpi.is_finite() && (1.0..=1200.0).contains(&dpi)) {
|
||||
return Err(Error::Decode(format!("dpi {dpi} is outside 1–1200")));
|
||||
}
|
||||
let doc = craft_pdf::open_slice(bytes, None).map_err(|error| Error::Decode(error.to_string()))?;
|
||||
let pages = doc.pages();
|
||||
let page = pages.get(page).ok_or_else(|| Error::Decode(format!("the PDF has no page {}", page + 1)))?;
|
||||
// In 1/72..=1200/72, so the cast keeps its value.
|
||||
let scale = (dpi / 72.0) as f32;
|
||||
let options = craft_pdf::raster::Options { scale: [scale, scale], background: [255; 4], ..Default::default() };
|
||||
let [width, height] = craft_pdf::raster::dimensions(page, &options).map_err(|error| Error::Decode(error.to_string()))?;
|
||||
let pixels = u64::from(width) * u64::from(height);
|
||||
if width == 0
|
||||
|| height == 0
|
||||
|| width > limits.max_raster_width
|
||||
|| height > limits.max_raster_height
|
||||
|| pixels > limits.max_raster_pixels
|
||||
|| pixels.saturating_mul(4) > limits.max_raster_alloc_bytes
|
||||
{
|
||||
return Err(Error::Decode(format!("a {width} × {height} pixel page is outside the raster limits")));
|
||||
}
|
||||
let raster =
|
||||
craft_pdf::raster::render(page, &craft_pdf::raster::RenderCache::new(), &craft_pdf::interpret::InterpreterSettings::default(), &options)
|
||||
.map_err(|error| Error::Decode(error.to_string()))?;
|
||||
// Opaque over the white background, so premultiplied and straight alpha agree.
|
||||
Ok(RasterImage { format: ImportFormat::Pdf, width: raster.width, height: raster.height, rgba: raster.bytes().to_vec() })
|
||||
}
|
||||
|
||||
fn import_pdf(bytes: &[u8], format: ImportFormat, limits: Limits) -> Result<Imported, Error> {
|
||||
let imported = craft_pdf::paths::import_page(
|
||||
bytes,
|
||||
@@ -396,6 +430,41 @@ fn path_is_finite(path: &BezPath) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod format_tests {
|
||||
|
||||
#[test]
|
||||
fn a_pdf_page_renders_as_a_picture_of_everything_on_it() {
|
||||
// A 50 × 50 mm page with a filled red square from 10 to 30 mm.
|
||||
let mut square = kurbo::BezPath::new();
|
||||
square.move_to((10.0, 10.0));
|
||||
square.line_to((30.0, 10.0));
|
||||
square.line_to((30.0, 30.0));
|
||||
square.line_to((10.0, 30.0));
|
||||
square.close_path();
|
||||
let pdf = crate::write::write_pdf_pages(&[crate::write::PdfPage {
|
||||
width_mm: 50.0,
|
||||
height_mm: 50.0,
|
||||
view_box: [0.0, 0.0, 50.0, 50.0],
|
||||
paths: vec![crate::write::PdfPath { path: square, color_rgb: [255, 0, 0], stroke_width_mm: None }],
|
||||
images: vec![],
|
||||
}])
|
||||
.unwrap();
|
||||
let image = render_pdf_page(&pdf, 0, 72.0, Limits::default()).unwrap();
|
||||
// 50 mm at 72 dpi is about 142 px.
|
||||
assert!((140..=143).contains(&image.width), "{}", image.width);
|
||||
assert_eq!(image.rgba.len(), (image.width * image.height * 4) as usize);
|
||||
let at = |x_mm: f64, y_mm: f64| {
|
||||
let (x, y) = ((x_mm / 25.4 * 72.0) as u32, (y_mm / 25.4 * 72.0) as u32);
|
||||
let i = ((y * image.width + x) * 4) as usize;
|
||||
[image.rgba[i], image.rgba[i + 1], image.rgba[i + 2]]
|
||||
};
|
||||
assert_eq!(at(20.0, 20.0), [255, 0, 0], "the square");
|
||||
assert_eq!(at(40.0, 40.0), [255, 255, 255], "the white page");
|
||||
assert!(render_pdf_page(&pdf, 3, 72.0, Limits::default()).is_err(), "no such page");
|
||||
assert!(render_pdf_page(&pdf, 0, f64::NAN, Limits::default()).is_err());
|
||||
let tight = Limits { max_raster_pixels: 100, ..Limits::default() };
|
||||
assert!(render_pdf_page(&pdf, 0, 72.0, tight).is_err(), "over the raster limit");
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -36,6 +36,42 @@ pub struct OutputPath {
|
||||
pub data_kind: Option<String>,
|
||||
/// Close each open contour for formats that require closed cutting operations.
|
||||
pub close_open_contours: bool,
|
||||
/// The colour the path is filled with in SVG and PDF output (even-odd, as drawn); `None`
|
||||
/// leaves it unfilled. Cutter and DXF writers ignore it.
|
||||
pub fill_rgb: Option<[u8; 3]>,
|
||||
}
|
||||
|
||||
/// A placed raster picture: straight RGBA pixels, row by row from the top, and the box it
|
||||
/// fills in view-box coordinates (millimetres for the PDF writer).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct OutputImage {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub width: f64,
|
||||
pub height: f64,
|
||||
pub width_px: u32,
|
||||
pub height_px: u32,
|
||||
pub rgba: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The largest side of an [`OutputImage`], in pixels.
|
||||
pub const MAX_IMAGE_SIDE_PX: u32 = 16_384;
|
||||
|
||||
/// The most images one scene or page holds.
|
||||
pub const MAX_IMAGES: usize = 1_000;
|
||||
|
||||
impl OutputImage {
|
||||
/// Whether the box is finite and positive and `rgba` holds exactly `width_px × height_px`
|
||||
/// pixels within [`MAX_IMAGE_SIDE_PX`].
|
||||
pub fn is_valid(&self) -> bool {
|
||||
let pixels = u64::from(self.width_px) * u64::from(self.height_px);
|
||||
[self.x, self.y, self.width, self.height].iter().all(|v| v.is_finite())
|
||||
&& self.width > 0.0
|
||||
&& self.height > 0.0
|
||||
&& (1..=MAX_IMAGE_SIDE_PX).contains(&self.width_px)
|
||||
&& (1..=MAX_IMAGE_SIDE_PX).contains(&self.height_px)
|
||||
&& u64::try_from(self.rgba.len()).is_ok_and(|len| Some(len) == pixels.checked_mul(4))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -45,6 +81,9 @@ pub struct OutputScene {
|
||||
pub view_box: [f64; 4],
|
||||
pub layers: Vec<OutputLayer>,
|
||||
pub paths: Vec<OutputPath>,
|
||||
/// Placed pictures, drawn under the paths in order. The PDF writer embeds them; the SVG,
|
||||
/// DXF and cutter writers leave them out.
|
||||
pub images: Vec<OutputImage>,
|
||||
}
|
||||
|
||||
/// One page for the shared PDF path writer. Coordinates and stroke widths are millimetres.
|
||||
@@ -54,6 +93,8 @@ pub struct PdfPage {
|
||||
pub height_mm: f64,
|
||||
pub view_box: [f64; 4],
|
||||
pub paths: Vec<PdfPath>,
|
||||
/// Placed pictures in view-box coordinates, drawn under the paths in order.
|
||||
pub images: Vec<OutputImage>,
|
||||
}
|
||||
|
||||
/// A PDF path with either a fill or a stroke. `None` fills the path; `Some(width)` strokes it.
|
||||
@@ -133,11 +174,15 @@ fn write_svg(scene: &OutputScene) -> Result<String, Error> {
|
||||
.iter()
|
||||
.map(|path| {
|
||||
let color = path.color_rgb;
|
||||
let fill = path.fill_rgb.map_or_else(|| "none".to_string(), |[r, g, b]| format!("#{r:02x}{g:02x}{b:02x}"));
|
||||
let mut attributes = vec![
|
||||
craft_svg::write::Attribute::text("fill", "none"),
|
||||
craft_svg::write::Attribute::text("fill", fill),
|
||||
craft_svg::write::Attribute::text("stroke", format!("#{:02x}{:02x}{:02x}", color[0], color[1], color[2])),
|
||||
craft_svg::write::Attribute::text("stroke-width", format_float(path.stroke_width_mm / view_scale)),
|
||||
];
|
||||
if path.fill_rgb.is_some() {
|
||||
attributes.push(craft_svg::write::Attribute::text("fill-rule", "evenodd"));
|
||||
}
|
||||
if let Some(class) = &path.class {
|
||||
attributes.push(craft_svg::write::Attribute::text("class", class.clone()));
|
||||
}
|
||||
@@ -173,9 +218,20 @@ fn write_pdf(scene: &OutputScene) -> Result<Vec<u8>, Error> {
|
||||
.enumerate()
|
||||
.filter(|(_, layer)| layer.visible)
|
||||
.flat_map(|(layer_index, _)| paths_by_layer[layer_index].iter().copied())
|
||||
.map(|path| PdfPath { path: path.path.clone(), color_rgb: path.color_rgb, stroke_width_mm: Some(path.stroke_width_mm) })
|
||||
// A filled path paints its fill, then its line over it.
|
||||
.flat_map(|path| {
|
||||
let fill = path.fill_rgb.map(|rgb| PdfPath { path: path.path.clone(), color_rgb: rgb, stroke_width_mm: None });
|
||||
fill.into_iter().chain(std::iter::once(PdfPath {
|
||||
path: path.path.clone(),
|
||||
color_rgb: path.color_rgb,
|
||||
stroke_width_mm: Some(path.stroke_width_mm),
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
write_pdf_pages(&[PdfPage { width_mm: scene.width_mm, height_mm: scene.height_mm, view_box: scene.view_box, paths }])
|
||||
write_pdf_pages_with_rule(
|
||||
&[PdfPage { width_mm: scene.width_mm, height_mm: scene.height_mm, view_box: scene.view_box, paths, images: scene.images.clone() }],
|
||||
craft_pdf::write::backend::paint::FillRule::EvenOdd,
|
||||
)
|
||||
}
|
||||
|
||||
/// Group the neutral paths once so writing does not rescan all paths for every layer.
|
||||
@@ -191,6 +247,11 @@ fn paths_by_layer(scene: &OutputScene) -> Vec<Vec<&OutputPath>> {
|
||||
|
||||
/// Encode a neutral list of laid-out pages with vector paths as PDF.
|
||||
pub fn write_pdf_pages(pages: &[PdfPage]) -> Result<Vec<u8>, Error> {
|
||||
write_pdf_pages_with_rule(pages, craft_pdf::write::backend::paint::FillRule::NonZero)
|
||||
}
|
||||
|
||||
// Scene fills are explicitly even-odd. Keep the existing standalone PDF page API's nonzero rule.
|
||||
fn write_pdf_pages_with_rule(pages: &[PdfPage], fill_rule: craft_pdf::write::backend::paint::FillRule) -> Result<Vec<u8>, Error> {
|
||||
use craft_pdf::write::{Metadata, Writer, backend};
|
||||
const PT_PER_MM: f64 = 72.0 / 25.4;
|
||||
craft_pdf::write::guard(|| {
|
||||
@@ -235,6 +296,26 @@ pub fn write_pdf_pages(pages: &[PdfPage]) -> Result<Vec<u8>, Error> {
|
||||
if !(view_scale.is_finite() && view_scale > 0.0 && offset_x.is_finite() && offset_y.is_finite()) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
if source_page.images.len() > MAX_IMAGES {
|
||||
return Err(Error::Write(format!("more than {MAX_IMAGES} images on a page")));
|
||||
}
|
||||
for image in &source_page.images {
|
||||
if !image.is_valid() {
|
||||
return Err(Error::Write("an image's box or pixels are not usable".into()));
|
||||
}
|
||||
let x = ((image.x - view_x) * view_scale + offset_x) * PT_PER_MM;
|
||||
let y = ((image.y - view_y) * view_scale + offset_y) * PT_PER_MM;
|
||||
let w = image.width * view_scale * PT_PER_MM;
|
||||
let h = image.height * view_scale * PT_PER_MM;
|
||||
if ![x, y, w, h].iter().all(|v| v.is_finite() && v.abs() <= f64::from(f32::MAX)) {
|
||||
return Err(Error::Write("an image is outside the PDF range".into()));
|
||||
}
|
||||
let size = backend::geom::Size::from_wh(w as f32, h as f32).ok_or_else(|| Error::Write("an image has no size".into()))?;
|
||||
let picture = backend::image::Image::from_rgba8(image.rgba.clone(), image.width_px, image.height_px);
|
||||
surface.push_transform(&backend::geom::Transform::from_translate(x as f32, y as f32));
|
||||
surface.draw_image(picture, size);
|
||||
surface.pop();
|
||||
}
|
||||
for source in &source_page.paths {
|
||||
let mut path = backend::geom::PathBuilder::new();
|
||||
for element in source.path.elements() {
|
||||
@@ -288,7 +369,7 @@ pub fn write_pdf_pages(pages: &[PdfPage]) -> Result<Vec<u8>, Error> {
|
||||
}
|
||||
None => {
|
||||
surface.set_stroke(None);
|
||||
surface.set_fill(Some(backend::paint::Fill { paint: color.into(), ..Default::default() }));
|
||||
surface.set_fill(Some(backend::paint::Fill { paint: color.into(), rule: fill_rule, ..Default::default() }));
|
||||
}
|
||||
}
|
||||
surface.draw_path(&path);
|
||||
@@ -420,6 +501,9 @@ fn validate_scene(scene: &OutputScene) -> Result<(), Error> {
|
||||
if !(scene.width_mm.is_finite() && scene.height_mm.is_finite() && scene.width_mm > 0.0 && scene.height_mm > 0.0) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
if scene.images.len() > MAX_IMAGES || scene.images.iter().any(|image| !image.is_valid()) {
|
||||
return Err(Error::InvalidGeometry);
|
||||
}
|
||||
if !(scene.view_box.iter().all(|value| value.is_finite()) && scene.view_box[2] > 0.0 && scene.view_box[3] > 0.0)
|
||||
|| scene.paths.len() > crate::MAX_SHAPES
|
||||
|| scene.paths.iter().any(|path| {
|
||||
@@ -445,3 +529,123 @@ fn point_is_finite(point: Point) -> bool {
|
||||
fn format_float(value: f64) -> String {
|
||||
value.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod fill_tests {
|
||||
use super::*;
|
||||
|
||||
fn scene(fill_rgb: Option<[u8; 3]>) -> OutputScene {
|
||||
let mut square = BezPath::new();
|
||||
square.move_to((10.0, 10.0));
|
||||
square.line_to((30.0, 10.0));
|
||||
square.line_to((30.0, 30.0));
|
||||
square.line_to((10.0, 30.0));
|
||||
square.close_path();
|
||||
OutputScene {
|
||||
width_mm: 50.0,
|
||||
height_mm: 50.0,
|
||||
view_box: [0.0, 0.0, 50.0, 50.0],
|
||||
layers: vec![OutputLayer { name: "cut".into(), dxf_name: "CUT".into(), visible: true, dxf_color_index: 1, class: None, data_kind: None }],
|
||||
paths: vec![OutputPath {
|
||||
path: square,
|
||||
layer: 0,
|
||||
color_rgb: [255, 0, 0],
|
||||
stroke_width_mm: 0.25,
|
||||
class: None,
|
||||
data_kind: None,
|
||||
close_open_contours: false,
|
||||
fill_rgb,
|
||||
}],
|
||||
images: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filled_path_is_filled_in_svg_and_pdf() {
|
||||
let svg = write_svg(&scene(Some([0x12, 0x34, 0x56]))).unwrap();
|
||||
assert!(svg.contains("fill=\"#123456\""), "{svg}");
|
||||
assert!(write_svg(&scene(None)).unwrap().contains("fill=\"none\""));
|
||||
let filled = write_pdf(&scene(Some([0x12, 0x34, 0x56]))).unwrap();
|
||||
let plain = write_pdf(&scene(None)).unwrap();
|
||||
assert!(filled.len() > plain.len(), "a fill is drawn as well as the line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_direction_nested_contours_preserve_the_hole() {
|
||||
let mut scene = scene(Some([255, 0, 0]));
|
||||
let path = &mut scene.paths[0].path;
|
||||
path.move_to((15.0, 15.0));
|
||||
path.line_to((25.0, 15.0));
|
||||
path.line_to((25.0, 25.0));
|
||||
path.line_to((15.0, 25.0));
|
||||
path.close_path();
|
||||
assert!(write_svg(&scene).unwrap().contains("fill-rule=\"evenodd\""));
|
||||
let sample = |pdf: &[u8], x_mm: f64, y_mm: f64| {
|
||||
let image = crate::render_pdf_page(pdf, 0, 72.0, crate::Limits::default()).unwrap();
|
||||
let (x, y) = ((x_mm / 25.4 * 72.0) as u32, (y_mm / 25.4 * 72.0) as u32);
|
||||
let i = ((y * image.width + x) * 4) as usize;
|
||||
[image.rgba[i], image.rgba[i + 1], image.rgba[i + 2]]
|
||||
};
|
||||
let pdf = write_pdf(&scene).unwrap();
|
||||
assert_eq!(sample(&pdf, 12.0, 12.0), [255, 0, 0]);
|
||||
assert_eq!(sample(&pdf, 20.0, 20.0), [255, 255, 255]);
|
||||
let standalone = write_pdf_pages(&[PdfPage {
|
||||
width_mm: scene.width_mm,
|
||||
height_mm: scene.height_mm,
|
||||
view_box: scene.view_box,
|
||||
paths: vec![PdfPath { path: scene.paths[0].path.clone(), color_rgb: [255, 0, 0], stroke_width_mm: None }],
|
||||
images: Vec::new(),
|
||||
}])
|
||||
.unwrap();
|
||||
assert_eq!(sample(&standalone, 20.0, 20.0), [255, 0, 0], "standalone PDF API retains nonzero fill");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod image_tests {
|
||||
use super::*;
|
||||
|
||||
fn page(images: Vec<OutputImage>) -> PdfPage {
|
||||
let mut square = BezPath::new();
|
||||
square.move_to((10.0, 10.0));
|
||||
square.line_to((20.0, 10.0));
|
||||
square.line_to((20.0, 20.0));
|
||||
square.close_path();
|
||||
PdfPage {
|
||||
width_mm: 100.0,
|
||||
height_mm: 100.0,
|
||||
view_box: [0.0, 0.0, 100.0, 100.0],
|
||||
paths: vec![PdfPath { path: square, color_rgb: [255, 0, 0], stroke_width_mm: Some(0.25) }],
|
||||
images,
|
||||
}
|
||||
}
|
||||
|
||||
fn picture(width_px: u32, height_px: u32) -> OutputImage {
|
||||
OutputImage { x: 30.0, y: 30.0, width: 40.0, height: 20.0, width_px, height_px, rgba: vec![200; (width_px * height_px * 4) as usize] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_picture_is_embedded_under_the_paths() {
|
||||
let plain = write_pdf_pages(&[page(Vec::new())]).unwrap();
|
||||
let with = write_pdf_pages(&[page(vec![picture(4, 2)])]).unwrap();
|
||||
let text = String::from_utf8_lossy(&with);
|
||||
assert!(text.contains("/Subtype/Image"), "an image XObject");
|
||||
assert!(!String::from_utf8_lossy(&plain).contains("/Subtype/Image"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unusable_pictures_are_errors_not_crashes() {
|
||||
let mut short = picture(4, 2);
|
||||
short.rgba.pop();
|
||||
for bad in [
|
||||
short,
|
||||
OutputImage { width: f64::NAN, ..picture(4, 2) },
|
||||
OutputImage { height: 0.0, ..picture(4, 2) },
|
||||
OutputImage { width_px: 0, rgba: Vec::new(), ..picture(4, 2) },
|
||||
OutputImage { width_px: MAX_IMAGE_SIDE_PX + 1, ..picture(4, 2) },
|
||||
] {
|
||||
assert!(!bad.is_valid());
|
||||
assert!(write_pdf_pages(&[page(vec![bad])]).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,8 @@ craft-fonts-build = { workspace = true }
|
||||
craft-font-manager = { path = ".", features = ["suite"] }
|
||||
# The shared preview test vectors.
|
||||
serde_json = { workspace = true }
|
||||
# Test faces built for the script filter (a script no shipped test font covers).
|
||||
write-fonts = "0.54"
|
||||
|
||||
[[test]]
|
||||
name = "it"
|
||||
|
||||
@@ -86,6 +86,15 @@ craft_ui::words! {
|
||||
script_east_asian: "fontPicker.scriptEastAsian" = "East Asian";
|
||||
script_japanese: "fontPicker.scriptJapanese" = "Japanese";
|
||||
script_thai: "fontPicker.scriptThai" = "Thai";
|
||||
script_devanagari: "fontPicker.scriptDevanagari" = "Devanagari";
|
||||
script_bengali: "fontPicker.scriptBengali" = "Bengali";
|
||||
script_gurmukhi: "fontPicker.scriptGurmukhi" = "Gurmukhi";
|
||||
script_gujarati: "fontPicker.scriptGujarati" = "Gujarati";
|
||||
script_odia: "fontPicker.scriptOdia" = "Odia";
|
||||
script_tamil: "fontPicker.scriptTamil" = "Tamil";
|
||||
script_telugu: "fontPicker.scriptTelugu" = "Telugu";
|
||||
script_kannada: "fontPicker.scriptKannada" = "Kannada";
|
||||
script_malayalam: "fontPicker.scriptMalayalam" = "Malayalam";
|
||||
any_kind: "fontPicker.anyKind" = "Any Kind";
|
||||
font_technology: "fontPicker.fontTechnology" = "Font Technology";
|
||||
preview_size: "fontPicker.previewSize" = "Font Preview Size";
|
||||
@@ -206,7 +215,7 @@ fn chosen_sample<'s, 'a>(texts: &'s [SampleText<'a>], settings: Option<&FontPick
|
||||
/// Coverage from the face: Latin, the basic Latin letters in the cmap; East Asian, the CJK Windows code pages
|
||||
/// (JIS, Simplified/Traditional Chinese, Wansung, Johab) or CJK ideographs/kana/Hangul when no code pages are declared;
|
||||
/// Japanese, the OS/2 kana or CJK unicode-range bits or the JIS code page bit, or a Japanese family name; Thai, U+0E01
|
||||
/// and U+0E32 in the cmap. Read lazily like the class.
|
||||
/// and U+0E32 in the cmap; an Indic script, its letter KA and vowel sign AA in the cmap. Read lazily like the class.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum FontScript {
|
||||
@@ -218,11 +227,43 @@ pub enum FontScript {
|
||||
Japanese,
|
||||
/// Thai.
|
||||
Thai,
|
||||
/// Devanagari.
|
||||
Devanagari,
|
||||
/// Bengali.
|
||||
Bengali,
|
||||
/// Gurmukhi.
|
||||
Gurmukhi,
|
||||
/// Gujarati.
|
||||
Gujarati,
|
||||
/// Odia.
|
||||
Odia,
|
||||
/// Tamil.
|
||||
Tamil,
|
||||
/// Telugu.
|
||||
Telugu,
|
||||
/// Kannada.
|
||||
Kannada,
|
||||
/// Malayalam.
|
||||
Malayalam,
|
||||
}
|
||||
|
||||
impl FontScript {
|
||||
/// Every script the script row can offer, in order.
|
||||
pub const ALL: [FontScript; 4] = [FontScript::Latin, FontScript::EastAsian, FontScript::Japanese, FontScript::Thai];
|
||||
pub const ALL: [FontScript; 13] = [
|
||||
FontScript::Latin,
|
||||
FontScript::EastAsian,
|
||||
FontScript::Japanese,
|
||||
FontScript::Thai,
|
||||
FontScript::Devanagari,
|
||||
FontScript::Bengali,
|
||||
FontScript::Gurmukhi,
|
||||
FontScript::Gujarati,
|
||||
FontScript::Odia,
|
||||
FontScript::Tamil,
|
||||
FontScript::Telugu,
|
||||
FontScript::Kannada,
|
||||
FontScript::Malayalam,
|
||||
];
|
||||
}
|
||||
|
||||
/// A family set the host gives (VectorCraft: Document, Recently Added), one filter toggle each. An `ordered` set that
|
||||
|
||||
@@ -200,9 +200,26 @@ const JAPANESE_RANGES: u32 = (1 << (49 - 32)) | (1 << (50 - 32)) | (1 << (59 - 3
|
||||
/// Hangul Syllables (56) plus [`JAPANESE_RANGES`].
|
||||
const EAST_ASIAN_RANGES: u32 = JAPANESE_RANGES | (1 << (56 - 32));
|
||||
|
||||
/// The Indic scripts and the first code point of their Unicode block. Every block has its letter KA and vowel sign AA
|
||||
/// at the same offsets.
|
||||
const INDIC_BLOCKS: [(FontScript, u32); 9] = [
|
||||
(FontScript::Devanagari, 0x0900),
|
||||
(FontScript::Bengali, 0x0980),
|
||||
(FontScript::Gurmukhi, 0x0A00),
|
||||
(FontScript::Gujarati, 0x0A80),
|
||||
(FontScript::Odia, 0x0B00),
|
||||
(FontScript::Tamil, 0x0B80),
|
||||
(FontScript::Telugu, 0x0C00),
|
||||
(FontScript::Kannada, 0x0C80),
|
||||
(FontScript::Malayalam, 0x0D00),
|
||||
];
|
||||
const INDIC_KA: u32 = 0x15;
|
||||
const INDIC_AA: u32 = 0x3E;
|
||||
|
||||
/// The scripts a face covers: Latin, the basic Latin letters in its `cmap`; East Asian, its East Asian Windows code
|
||||
/// pages, CJK/kana/Hangul Unicode ranges, CJK ideographs in `cmap`, or a CJK localized name; Japanese, the JIS code
|
||||
/// page, the kana or CJK Unicode ranges of its `OS/2` table, or a Japanese family name; Thai, ก and า in its `cmap`.
|
||||
/// page, the kana or CJK Unicode ranges of its `OS/2` table, or a Japanese family name; Thai, ก and า in its `cmap`;
|
||||
/// an Indic script, its letter KA and vowel sign AA in its `cmap` (no code page covers these scripts).
|
||||
fn read_scripts(catalog: &Catalog, face: &FaceInfo) -> Option<Vec<FontScript>> {
|
||||
let data = catalog.load(face).ok()?;
|
||||
let font = FontRef::from_index(&data.bytes, face.index).ok()?;
|
||||
@@ -217,7 +234,11 @@ fn read_scripts(catalog: &Catalog, face: &FaceInfo) -> Option<Vec<FontScript>> {
|
||||
let japanese = face.code_pages[0] & JIS_CODE_PAGE != 0 || ranges & JAPANESE_RANGES != 0 || japanese_name(face);
|
||||
let thai = ['\u{0E01}', '\u{0E32}'].into_iter().all(&mapped);
|
||||
let scripts = [(FontScript::Latin, latin), (FontScript::EastAsian, east_asian), (FontScript::Japanese, japanese), (FontScript::Thai, thai)];
|
||||
Some(scripts.into_iter().filter_map(|(script, covered)| covered.then_some(script)).collect())
|
||||
let indic = INDIC_BLOCKS.into_iter().map(|(script, block)| {
|
||||
let at = |offset: u32| char::from_u32(block + offset).is_some_and(&mapped);
|
||||
(script, at(INDIC_KA) && at(INDIC_AA))
|
||||
});
|
||||
Some(scripts.into_iter().chain(indic).filter_map(|(script, covered)| covered.then_some(script)).collect())
|
||||
}
|
||||
|
||||
/// The class of a family from its regular face, `None` when the catalog lacks it.
|
||||
|
||||
@@ -350,6 +350,15 @@ fn script_label(script: FontScript, words: &FontPickerWords) -> Label {
|
||||
FontScript::EastAsian => words.script_east_asian.clone(),
|
||||
FontScript::Japanese => words.script_japanese.clone(),
|
||||
FontScript::Thai => words.script_thai.clone(),
|
||||
FontScript::Devanagari => words.script_devanagari.clone(),
|
||||
FontScript::Bengali => words.script_bengali.clone(),
|
||||
FontScript::Gurmukhi => words.script_gurmukhi.clone(),
|
||||
FontScript::Gujarati => words.script_gujarati.clone(),
|
||||
FontScript::Odia => words.script_odia.clone(),
|
||||
FontScript::Tamil => words.script_tamil.clone(),
|
||||
FontScript::Telugu => words.script_telugu.clone(),
|
||||
FontScript::Kannada => words.script_kannada.clone(),
|
||||
FontScript::Malayalam => words.script_malayalam.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -235,7 +235,7 @@ fn font_picker_filter_chips(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
FamilySet::new("document", "Document", &document),
|
||||
FamilySet::new("added", "Recently Added", &added).ordered().enabled(false).hint("No fonts were added recently"),
|
||||
];
|
||||
let scripts = [FontScript::Latin, FontScript::Japanese, FontScript::Thai];
|
||||
let scripts = [FontScript::Latin, FontScript::Japanese, FontScript::Thai, FontScript::Devanagari, FontScript::Gujarati];
|
||||
let filters = FontFilters { sets: vec!["document".to_owned()], ..FontFilters::default() };
|
||||
let extras = Extras { sets: &sets, scripts: &scripts, layout: FilterLayout::Chips, ..Extras::default() };
|
||||
show_with(ui, data, demo("Hack", FontPickerSettings::default(), filters), &catalog(), &extras)
|
||||
|
||||
@@ -385,6 +385,54 @@ fn a_thai_and_a_cjk_face_each_pass_their_own_scripts_filter() {
|
||||
assert!(!thai.iter().chain(&japanese).any(|family| family.contains("Inter")), "Inter covers neither");
|
||||
}
|
||||
|
||||
/// A face named `family` whose `cmap` maps the basic Latin letters and `extra`: only the tables the catalog and the
|
||||
/// coverage read, with an empty `glyf` so it counts as drawable.
|
||||
fn face_mapping(family: &str, extra: &[char]) -> Vec<u8> {
|
||||
use write_fonts::FontBuilder;
|
||||
use write_fonts::tables::cmap::Cmap;
|
||||
use write_fonts::tables::maxp::Maxp;
|
||||
use write_fonts::tables::name::{Name, NameRecord};
|
||||
use write_fonts::tables::os2::Os2;
|
||||
use write_fonts::types::{GlyphId, NameId, Tag};
|
||||
|
||||
let chars: Vec<char> = ('A'..='Z').chain('a'..='z').chain(extra.iter().copied()).collect();
|
||||
let cmap = Cmap::from_mappings(chars.iter().zip(1u32..).map(|(&c, g)| (c, GlyphId::new(g)))).expect("a cmap");
|
||||
let mut records = vec![
|
||||
NameRecord::new(3, 1, 0x409, NameId::new(1), family.to_owned().into()),
|
||||
NameRecord::new(3, 1, 0x409, NameId::new(2), "Regular".to_owned().into()),
|
||||
NameRecord::new(3, 1, 0x409, NameId::new(4), format!("{family} Regular").into()),
|
||||
NameRecord::new(3, 1, 0x409, NameId::new(6), format!("{}-Regular", family.replace(' ', "")).into()),
|
||||
];
|
||||
records.sort_by_key(|r| r.name_id);
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_table(&Name::new(records)).expect("name");
|
||||
builder.add_table(&Os2 { us_weight_class: 400, us_width_class: 5, ..Default::default() }).expect("OS/2");
|
||||
builder.add_table(&cmap).expect("cmap");
|
||||
builder.add_table(&Maxp::new(u16::try_from(chars.len() + 1).expect("few glyphs"))).expect("maxp");
|
||||
builder.add_raw(Tag::new(b"glyf"), vec![0u8; 4]);
|
||||
builder.build()
|
||||
}
|
||||
|
||||
/// An Indic script is read from the face's `cmap` (KA and vowel sign AA); no code page marks it. A face with
|
||||
/// Devanagari passes the Devanagari filter, not the Gujarati one, and Latin-only and Thai faces pass neither.
|
||||
#[trial]
|
||||
fn an_indic_face_passes_its_own_scripts_filter() {
|
||||
const THAI: &[u8] = include_bytes!("../../../font-subset/tests/data/sarabun/Sarabun-Regular.ttf");
|
||||
let deva = face_mapping("Test Devanagari", &['\u{0915}', '\u{093E}']);
|
||||
// A lone KA, as a symbol font might carry, is not coverage.
|
||||
let ka_only = face_mapping("Test Lone Ka", &['\u{0A95}']);
|
||||
let catalog = catalog_of(&[INTER_REGULAR, THAI, &deva, &ka_only]);
|
||||
let with = |script: FontScript| {
|
||||
let mut filters = FontFilters::default();
|
||||
filters.script = Some(script);
|
||||
listed(&catalog, &filters, &[])
|
||||
};
|
||||
let devanagari = with(FontScript::Devanagari);
|
||||
assert!(devanagari.iter().any(|family| family.contains("Test Devanagari")), "Devanagari: {devanagari:?}");
|
||||
assert!(!devanagari.iter().any(|family| family.contains("Inter") || family.contains("Sarabun")), "Devanagari: {devanagari:?}");
|
||||
assert!(with(FontScript::Gujarati).is_empty(), "nothing covers Gujarati: {:?}", with(FontScript::Gujarati));
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_host_set_keeps_only_its_families_and_an_ordered_one_lists_them_in_its_order() {
|
||||
let catalog = three_faces();
|
||||
|
||||
@@ -106,7 +106,10 @@ index, bytes, role }` literals; any struct with those fields and that name in sc
|
||||
`None`, or `Some("tab")` on the face `tab_face()` adds; craft-ui's font stack leads the Monospace
|
||||
family with the `mono` face, the signature family (`FontRef::signature()`) with the `signature`
|
||||
face and the tab-title family with the `tab` face. `EmbeddedFace` itself has `name()`,
|
||||
`has_script(tag)`, `is_cjk()` and `weight()`.
|
||||
`has_script(tag)`, `is_cjk()` and `weight()`. Tests and tables written by hand build a face with
|
||||
`EmbeddedFace::new(family, style, scripts, bytes)`, which sets no `role`, plus `.with_index(n)`
|
||||
for a face in a collection; both are `const fn`. Code that uses `new` keeps compiling when a
|
||||
field with a default is added; a struct literal does not.
|
||||
|
||||
## Document fonts
|
||||
|
||||
|
||||
@@ -87,6 +87,26 @@ pub struct EmbeddedFace {
|
||||
}
|
||||
|
||||
impl EmbeddedFace {
|
||||
/// A face at index 0 of `bytes` with no `role`, for tests and for tables written by hand. Code
|
||||
/// that builds faces with `new` keeps compiling when a field with a default is added; a struct
|
||||
/// literal does not.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_fonts_build::EmbeddedFace;
|
||||
///
|
||||
/// static FACE: EmbeddedFace = EmbeddedFace::new("Sans", "Bold", &["Latn"], b"").with_index(2);
|
||||
/// assert_eq!((FACE.name().as_str(), FACE.index), ("Sans Bold", 2));
|
||||
/// ```
|
||||
pub const fn new(family: &'static str, style: &'static str, scripts: &'static [&'static str], bytes: &'static [u8]) -> Self {
|
||||
Self { family, style, scripts, index: 0, bytes, role: None }
|
||||
}
|
||||
|
||||
/// The same face at `index` in a font collection (`.ttc`).
|
||||
#[must_use]
|
||||
pub const fn with_index(self, index: u32) -> Self {
|
||||
Self { index, ..self }
|
||||
}
|
||||
|
||||
/// `"<family> <style>"`, e.g. `"Noto Sans Arabic Regular"`.
|
||||
pub fn name(&self) -> String {
|
||||
format!("{} {}", self.family, self.style)
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use crate::cmap::Cmap;
|
||||
use crate::embed::Env;
|
||||
use crate::{Embed, Error};
|
||||
use crate::{Embed, EmbeddedFace, Error};
|
||||
|
||||
fn fixture() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixture/craft-fonts")
|
||||
@@ -46,6 +46,20 @@ fn run(embed: Embed, dir: Option<&Path>, required: Option<&str>) -> Run {
|
||||
Run { result: result.map(|faces| faces.iter().map(|f| format!("{} {}", f.family, f.style)).collect()), cargo, table }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_face_new_starts_at_index_zero() {
|
||||
const SCRIPTS: &[&str] = &["Jpan", "Latn"];
|
||||
const FACE: EmbeddedFace = EmbeddedFace::new("Sans JP", "Bold", SCRIPTS, b"font");
|
||||
assert_eq!((FACE.family, FACE.style, FACE.scripts, FACE.index, FACE.bytes), ("Sans JP", "Bold", SCRIPTS, 0, &b"font"[..]));
|
||||
assert_eq!(FACE.role, None);
|
||||
let in_collection = FACE.with_index(3);
|
||||
assert_eq!(in_collection.index, 3);
|
||||
assert_eq!(
|
||||
(in_collection.family, in_collection.style, in_collection.bytes, in_collection.role),
|
||||
(FACE.family, FACE.style, FACE.bytes, FACE.role)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_replaces_a_stale_copy_of_the_same_size() {
|
||||
let scratch = Scratch::new("serve-stale");
|
||||
|
||||
@@ -16,6 +16,9 @@ The `gpu-device` feature of `craft` exports this crate as `craft::gpu_device`.
|
||||
settings for flags and backend options when that instance is first created. `native_descriptor`
|
||||
reads those settings on every call.
|
||||
|
||||
`native_instance` returns `Result<wgpu::Instance, OpenError>`. It returns `OpenError::NoAdapter`
|
||||
when no wgpu backend is compiled for the target.
|
||||
|
||||
Licensed under MIT OR Apache-2.0.
|
||||
|
||||
## Contents
|
||||
@@ -24,7 +27,7 @@ Licensed under MIT OR Apache-2.0.
|
||||
|---|---|
|
||||
| `Candidate` | one listed adapter as plain data: name, backend, device type, PCI vendor, device and bus, driver, feature count, and whether it can draw to the window's surface |
|
||||
| `list(instance, surface)` | every adapter the instance lists, as `wgpu::Adapter`s and as `Candidate`s |
|
||||
| `native_instance`, `native_descriptor` | a wgpu instance over Vulkan, Metal and DirectX 12, plus OpenGL except on Windows; wgpu's `WGPU_*` flag variables apply |
|
||||
| `native_instance`, `native_descriptor` | a wgpu instance over Vulkan, Metal and DirectX 12, plus OpenGL; OpenGL is excluded on Windows unless it is the only compiled native backend; wgpu's `WGPU_*` flag variables apply |
|
||||
| `choose(candidates, power)` | wgpu's own adapter rule with two corrections: the newest version of a driver that lists one GPU twice, and DirectX 12 instead of Vulkan on Intel Gen 9 to Gen 11 integrated GPUs (`intel_gen9_to_gen11`) |
|
||||
| `Preference` | `Auto` (high performance), `LowPower`, `Adapter(AdapterKey)` or `Software`; serde form `{"kind":"auto"}`, `{"kind":"adapter","name":…,"backend":…,"vendor":…,"device":…,"pciBusId":…,"driver":…}` |
|
||||
| `AdapterKey` | what identifies an adapter across runs: backend, PCI vendor, device and bus, the Vulkan driver's name, and the name when the backend reports no PCI ids |
|
||||
@@ -80,7 +83,8 @@ Licensed under MIT OR Apache-2.0.
|
||||
`Device::poll` raises on a lost device and record the loss.
|
||||
- wgpu keeps one device-lost callback per device, and a later `set_device_lost_callback`
|
||||
replaces the one `DeviceHealth::watch` set. A `craft-gpu` context on a watched device reads
|
||||
`DeviceHealth::device_status` instead of setting its own callback.
|
||||
`DeviceHealth::device_status` instead of setting its own callback, as `craft-gpu-wgpu`'s
|
||||
`WgpuContext` does.
|
||||
- After an out-of-memory error, polls and waits keep running, so staging memory is reclaimed.
|
||||
The app reads `DeviceHealth::out_of_memory_count` when it handles the error, frees memory, and
|
||||
passes the count to `DeviceHealth::clear_out_of_memory`. The device is then healthy again,
|
||||
|
||||
@@ -133,21 +133,30 @@ pub(crate) fn wgpu_choice(candidates: &[Candidate], power: PowerPreference) -> O
|
||||
}
|
||||
|
||||
/// A wgpu instance over the native backends (Vulkan, Metal, DirectX 12), and OpenGL except on
|
||||
/// Windows. On Windows, OpenGL starts a WGL context thread inside the vendor driver (NVIDIA's
|
||||
/// `nvoglv64` is both its OpenGL driver and its Vulkan driver), and instances created and devices
|
||||
/// dropped at the same time can then deadlock in that driver.
|
||||
/// Windows, unless OpenGL is the only compiled native backend. On Windows, OpenGL starts a WGL
|
||||
/// context thread inside the vendor driver (NVIDIA's `nvoglv64` is both its OpenGL driver and its
|
||||
/// Vulkan driver), and instances created and devices dropped at the same time can then deadlock
|
||||
/// in that driver.
|
||||
///
|
||||
/// On native targets, the first call creates one shared instance and reads wgpu's environment
|
||||
/// settings for flags and backend options. Later calls return clones of that instance.
|
||||
pub fn native_instance() -> wgpu::Instance {
|
||||
/// Returns [`crate::OpenError::NoAdapter`] when no wgpu backend is compiled for this target.
|
||||
pub fn native_instance() -> Result<wgpu::Instance, crate::OpenError> {
|
||||
native_instance_with_backends(wgpu::Instance::enabled_backend_features())
|
||||
}
|
||||
|
||||
fn native_instance_with_backends(backends: wgpu::Backends) -> Result<wgpu::Instance, crate::OpenError> {
|
||||
if backends.is_empty() {
|
||||
return Err(crate::OpenError::NoAdapter);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
static SHARED: std::sync::OnceLock<wgpu::Instance> = std::sync::OnceLock::new();
|
||||
SHARED.get_or_init(|| wgpu::Instance::new(native_descriptor())).clone()
|
||||
Ok(SHARED.get_or_init(|| wgpu::Instance::new(native_descriptor())).clone())
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
wgpu::Instance::new(native_descriptor())
|
||||
Ok(wgpu::Instance::new(native_descriptor()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,8 +171,15 @@ pub fn native_instance() -> wgpu::Instance {
|
||||
/// or pass the descriptor to egui-wgpu as `WgpuSetupCreateNew::instance_descriptor`, where eframe
|
||||
/// fills in the window's display handle.
|
||||
pub fn native_descriptor() -> wgpu::InstanceDescriptor {
|
||||
native_descriptor_with_backends(wgpu::Instance::enabled_backend_features())
|
||||
}
|
||||
|
||||
fn native_descriptor_with_backends(backends: wgpu::Backends) -> wgpu::InstanceDescriptor {
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL };
|
||||
if backends.contains(wgpu::Backends::GL) && !backends.intersects(wgpu::Backends::PRIMARY) {
|
||||
desc.backends |= wgpu::Backends::GL;
|
||||
}
|
||||
desc.flags = desc.flags.with_env();
|
||||
desc.backend_options = desc.backend_options.with_env();
|
||||
desc
|
||||
@@ -245,13 +261,14 @@ pub fn intel_gen9_to_gen11(device: u32) -> bool {
|
||||
|
||||
/// Whether `c` is an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan
|
||||
/// driver ([`intel_gen9_to_gen11`]). Mesa's Vulkan driver for the same GPUs on Linux reports a
|
||||
/// driver name with "Mesa" in it and is not included.
|
||||
/// driver name or driver information with "Mesa" in it and is not included.
|
||||
pub(crate) fn intel_vulkan_crashes(c: &Candidate) -> bool {
|
||||
c.backend == Backend::Vulkan
|
||||
&& c.device_type == DeviceType::IntegratedGpu
|
||||
&& c.vendor == INTEL
|
||||
&& intel_gen9_to_gen11(c.device)
|
||||
&& !c.driver.to_ascii_lowercase().contains("mesa")
|
||||
&& !c.driver_info.to_ascii_lowercase().contains("mesa")
|
||||
}
|
||||
|
||||
/// For an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan driver, the
|
||||
@@ -505,6 +522,16 @@ pub(crate) mod tests {
|
||||
assert_eq!(choose(&discrete, HighPerformance), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesa_driver_info_keeps_dozen_eligible() {
|
||||
let adapters = vec![gpu("Intel(R) UHD Graphics 630", Vulkan, IntegratedGpu, INTEL, 0x3e91, "", "Dozen", "Mesa 26.1.0", 44)];
|
||||
for power in POWERS {
|
||||
assert_eq!(choose(&adapters, power), Some(0));
|
||||
}
|
||||
assert!(!intel_vulkan_crashes(&adapters[0]));
|
||||
assert!(intel_vulkan_crashes(&uhd_630()[0]), "the Intel Windows driver remains excluded");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gen9_to_gen11_ids() {
|
||||
for id in [0x1916, 0x0a84, 0x5a85, 0x3184, 0x5917, 0x87c0, 0x3e91, 0x3ea0, 0x9b41, 0x5a52, 0x8a5a, 0x4571, 0x4e61] {
|
||||
@@ -576,19 +603,37 @@ pub(crate) mod tests {
|
||||
std::thread::scope(|scope| {
|
||||
let first = scope.spawn(|| {
|
||||
gate.wait();
|
||||
native_instance()
|
||||
native_instance().unwrap()
|
||||
});
|
||||
let second = scope.spawn(|| {
|
||||
gate.wait();
|
||||
native_instance()
|
||||
native_instance().unwrap()
|
||||
});
|
||||
gate.wait();
|
||||
let first = first.join().unwrap();
|
||||
assert_eq!(first, second.join().unwrap());
|
||||
assert_eq!(first, native_instance());
|
||||
assert_eq!(first, native_instance().unwrap());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_compiled_backend_returns_an_error() {
|
||||
assert_eq!(native_instance_with_backends(wgpu::Backends::empty()), Err(crate::OpenError::NoAdapter));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gles_is_selected_when_it_is_the_only_compiled_native_backend() {
|
||||
let desc = native_descriptor_with_backends(wgpu::Backends::GL | wgpu::Backends::NOOP);
|
||||
assert!(desc.backends.contains(wgpu::Backends::GL));
|
||||
if cfg!(windows) {
|
||||
for other in [wgpu::Backends::DX12, wgpu::Backends::VULKAN, wgpu::Backends::METAL] {
|
||||
let desc = native_descriptor_with_backends(wgpu::Backends::GL | other);
|
||||
assert!(!desc.backends.contains(wgpu::Backends::GL));
|
||||
}
|
||||
assert!(!native_descriptor_with_backends(wgpu::Backends::NOOP).backends.contains(wgpu::Backends::GL));
|
||||
}
|
||||
}
|
||||
|
||||
/// The instance reads wgpu's flag variables and keeps its own backends whatever `WGPU_BACKEND`
|
||||
/// says. Runs in a child process, which has them set.
|
||||
#[test]
|
||||
@@ -608,7 +653,11 @@ pub(crate) mod tests {
|
||||
}
|
||||
let desc = native_descriptor();
|
||||
assert!(desc.flags.contains(wgpu::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER), "{:?}", desc.flags);
|
||||
let backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL };
|
||||
let mut backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL };
|
||||
let compiled = wgpu::Instance::enabled_backend_features();
|
||||
if compiled.contains(wgpu::Backends::GL) && !compiled.intersects(wgpu::Backends::PRIMARY) {
|
||||
backends |= wgpu::Backends::GL;
|
||||
}
|
||||
assert_eq!(desc.backends, backends);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//!
|
||||
//! wgpu's default uncaptured-error handler panics, and `Device::poll` panics on a lost device
|
||||
//! whatever the handler. [`DeviceHealth::watch`] replaces the handler with one that records the
|
||||
//! fault and registers the device-lost callback, and the polls here run only while the device is
|
||||
//! healthy, catching the poll's panic as a last resort. Every GPU entry point checks
|
||||
//! fault and registers the device-lost callback. [`DeviceHealth::probe`] keeps polling until
|
||||
//! that callback runs or a poll panics. Every GPU entry point checks
|
||||
//! [`DeviceHealth::fault`] first.
|
||||
//!
|
||||
//! Builds for the web too: the callbacks only touch atomics and a mutex.
|
||||
@@ -101,8 +101,10 @@ struct Inner {
|
||||
/// The first other error.
|
||||
error: OnceLock<String>,
|
||||
errors: AtomicU64,
|
||||
/// wgpu itself reported the device lost (see [`DeviceHealth::device_lost`]).
|
||||
/// A device loss was confirmed (see [`DeviceHealth::device_lost`]).
|
||||
device_lost: AtomicBool,
|
||||
/// The device-lost callback ran or a poll panicked.
|
||||
polling_stopped: AtomicBool,
|
||||
}
|
||||
|
||||
/// Shared health flag of one wgpu device. Cheap to clone; every clone sees the same state.
|
||||
@@ -137,8 +139,8 @@ impl DeviceHealth {
|
||||
};
|
||||
log::error!("wgpu device lost ({reason:?}): {detail}");
|
||||
// The loss first: a caller that sees `device_lost` then also sees the fault.
|
||||
lost.mark(Fault::Lost(detail));
|
||||
lost.0.device_lost.store(true, Ordering::Release);
|
||||
lost.confirm_device_lost(detail);
|
||||
lost.0.polling_stopped.store(true, Ordering::Release);
|
||||
});
|
||||
let errors = health.clone();
|
||||
device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| errors.uncaptured(&e)));
|
||||
@@ -236,6 +238,11 @@ impl DeviceHealth {
|
||||
self.0.error.get().map(|text| Fault::Error(text.clone()))
|
||||
}
|
||||
|
||||
/// A recorded device loss or error other than out of memory that stops polls and waits.
|
||||
pub fn polling_fault(&self) -> Option<Fault> {
|
||||
self.0.lost.get().map(|text| Fault::Lost(text.clone())).or_else(|| self.0.error.get().map(|text| Fault::Error(text.clone())))
|
||||
}
|
||||
|
||||
/// The device loss in the form of `craft_gpu::GpuContext::device_status`:
|
||||
/// [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost) once a loss is recorded,
|
||||
/// otherwise `Ok`. Other errors are reported by [`fault`](Self::fault). wgpu keeps one
|
||||
@@ -253,8 +260,10 @@ impl DeviceHealth {
|
||||
self.0.errors.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether wgpu itself reported the device lost: its device-lost callback ran, or polling it
|
||||
/// panicked. A fault recorded with [`mark`](Self::mark) is not one. After a real loss nothing
|
||||
/// Whether a device loss was confirmed: its device-lost callback ran, polling it panicked,
|
||||
/// or [`confirm_device_lost`](Self::confirm_device_lost) or
|
||||
/// [`record_device_loss`](Self::record_device_loss) was called. A fault recorded with
|
||||
/// [`mark`](Self::mark) is not one. After a real loss nothing
|
||||
/// drawn with the device reaches the screen, the window's own frames included.
|
||||
pub fn device_lost(&self) -> bool {
|
||||
self.0.device_lost.load(Ordering::Acquire)
|
||||
@@ -262,9 +271,10 @@ impl DeviceHealth {
|
||||
|
||||
/// Non-blocking poll that runs even after a fault was recorded, so a device that is lost
|
||||
/// later (a driver reset while the app sat idle, or the PC slept) is noticed before the next
|
||||
/// frame is drawn with it. Skipped once [`device_lost`](Self::device_lost).
|
||||
/// frame is drawn with it. Polling stops only after the device-lost callback ran or a poll
|
||||
/// panicked, including when a caller already confirmed the loss.
|
||||
pub fn probe(&self, device: &wgpu::Device) {
|
||||
if self.device_lost() {
|
||||
if self.0.polling_stopped.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() {
|
||||
@@ -274,7 +284,19 @@ impl DeviceHealth {
|
||||
|
||||
/// `Device::poll` panicked: wgpu found the device lost.
|
||||
fn lost_by_poll(&self) {
|
||||
self.mark(Fault::Lost("the device stopped responding".into()));
|
||||
self.record_device_loss("the device stopped responding".into());
|
||||
self.0.polling_stopped.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
/// Record a confirmed device loss even when wgpu has deferred its device-lost callback.
|
||||
/// [`probe`](Self::probe) continues polling until that callback runs or a poll panics.
|
||||
pub fn record_device_loss(&self, detail: String) {
|
||||
self.confirm_device_lost(detail);
|
||||
}
|
||||
|
||||
/// Record a caller-confirmed device loss without stopping [`probe`](Self::probe).
|
||||
pub fn confirm_device_lost(&self, detail: String) {
|
||||
self.mark(Fault::Lost(detail));
|
||||
self.0.device_lost.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
@@ -506,6 +528,15 @@ fn one_line(s: &str) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn confirming_device_loss_keeps_probe_polling() {
|
||||
let h = DeviceHealth::new();
|
||||
h.clone().confirm_device_lost("destroyed".into());
|
||||
assert!(h.device_lost());
|
||||
assert_eq!(h.fault(), Some(Fault::Lost("destroyed".into())));
|
||||
assert!(!h.0.polling_stopped.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_fault_wins_but_loss_replaces_an_error() {
|
||||
let h = DeviceHealth::new();
|
||||
|
||||
@@ -12,20 +12,20 @@ workspace = true
|
||||
[dependencies]
|
||||
craft-gpu = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
wgpu = { workspace = true, features = ["webgpu"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Chooses and opens the device, and watches it for a loss (`adapter-probe`).
|
||||
craft-gpu-device = { workspace = true, optional = true }
|
||||
pollster = { workspace = true, optional = true }
|
||||
wgpu = { workspace = true }
|
||||
# Native code uses wgpu only with `adapter-probe`.
|
||||
wgpu = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
adapter-probe = ["dep:pollster"]
|
||||
native-vulkan = ["wgpu/vulkan"]
|
||||
native-dx12 = ["wgpu/dx12"]
|
||||
native-metal = ["wgpu/metal"]
|
||||
native-gles = ["wgpu/gles"]
|
||||
adapter-probe = ["dep:pollster", "dep:craft-gpu-device", "dep:wgpu"]
|
||||
native-vulkan = ["wgpu?/vulkan"]
|
||||
native-dx12 = ["wgpu?/dx12"]
|
||||
native-metal = ["wgpu?/metal"]
|
||||
native-gles = ["wgpu?/gles"]
|
||||
|
||||
[dev-dependencies]
|
||||
pollster = { workspace = true }
|
||||
@@ -33,3 +33,7 @@ pollster = { workspace = true }
|
||||
# providers against a real WgpuContext, not just craft-gpu-null, per RFC-0022 acceptance
|
||||
# requirement 2. Dev-only: no cycle (craft-gpu-providers never depends on craft-gpu-wgpu).
|
||||
craft-gpu-providers = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
# The noop backend opens devices without a GPU in the tests.
|
||||
wgpu = { workspace = true, features = ["noop"] }
|
||||
+284
-106
@@ -1,10 +1,14 @@
|
||||
//! wgpu-backed [`GpuContext`].
|
||||
//!
|
||||
//! WebGPU on `wasm32`; native APIs when backend features are enabled. With the `adapter-probe`
|
||||
//! feature (native only, pollster) and at least one `native-*` backend feature,
|
||||
//! [`WgpuContext::new`] requests a real device and builds [`DeviceCaps`] from what that device
|
||||
//! actually enabled (`Device::limits()` / `Device::features()`), never from the adapter's
|
||||
//! advertised maximum. Without a usable adapter (the features above are off, no GPU is present,
|
||||
//! feature (native only), [`WgpuContext::new`] opens a real device through `craft-gpu-device`
|
||||
//! (its adapter choice for `Preference::Auto`, its driver corrections and its fallback order) and
|
||||
//! builds [`DeviceCaps`] from what that device actually enabled (`Device::limits()` /
|
||||
//! `Device::features()`), never from the adapter's advertised maximum.
|
||||
//! With the native `adapter-probe` feature, `WgpuContext::from_opened` and `WgpuContext::with_device`
|
||||
//! take a device the caller opened.
|
||||
//! A loss is read from the device's `craft_gpu_device::DeviceHealth`, which owns the device's
|
||||
//! device-lost callback. Without a usable adapter (`adapter-probe` is off, no GPU is present,
|
||||
//! or on `wasm32` where real device creation needs the async worker-init path noted in
|
||||
//! `docs/gpu-backends.md`), the context degrades to the same in-memory staging behavior as
|
||||
//! `craft_gpu_null::NullContext` (not a dependency of this crate; named here only for context);
|
||||
@@ -32,29 +36,17 @@ fn probe_fallback(backend_name: &str, device_name: &str) -> DeviceCaps {
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
fn probe_caps_native() -> DeviceCaps {
|
||||
let instance = native::instance();
|
||||
let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) {
|
||||
Ok(adapter) => adapter,
|
||||
Err(_) => return probe_fallback("wgpu", "no-adapter"),
|
||||
};
|
||||
let info = adapter.get_info();
|
||||
let limits = adapter.limits();
|
||||
DeviceCaps {
|
||||
backend_name: format!("{:?}", info.backend),
|
||||
device_name: info.name,
|
||||
max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size,
|
||||
max_buffer_size: limits.max_buffer_size,
|
||||
max_texture_dimension_2d: limits.max_texture_dimension_2d,
|
||||
features: Vec::new(),
|
||||
vendor_id: info.vendor,
|
||||
software: info.device_type == wgpu::DeviceType::Cpu,
|
||||
}
|
||||
native::instance().as_ref().map(native::probe_caps_on).unwrap_or_else(|| probe_fallback("wgpu", "no-adapter"))
|
||||
}
|
||||
|
||||
/// Adapter-advertised limits, when an adapter is available; otherwise conservative defaults. This
|
||||
/// is the quick, device-free probe for UI surfaces that want a number before any context exists
|
||||
/// (Settings). It is advisory only: these are the adapter's maximums, not a device's granted
|
||||
/// ones. [`WgpuContext::caps`] is the authoritative, device-truth source once a context exists.
|
||||
/// ones. With `adapter-probe` it reports the adapter `craft_gpu_device::pick` chooses for
|
||||
/// `Preference::Auto` without opening a device on it; when a device then fails to open there,
|
||||
/// [`WgpuContext::new`] opens the next adapter in `craft_gpu_device::ranked` order, or a software
|
||||
/// one, which this probe does not report. [`WgpuContext::caps`] is the authoritative, device-truth
|
||||
/// source once a context exists.
|
||||
pub fn probe_caps() -> DeviceCaps {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
{
|
||||
@@ -74,11 +66,10 @@ pub fn probe_caps() -> DeviceCaps {
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
mod native {
|
||||
use std::sync::{Arc, Mutex};
|
||||
use craft_gpu::DeviceCaps;
|
||||
use craft_gpu_device::{Capabilities, DeviceHealth, Opened, Preference, Request};
|
||||
|
||||
use craft_gpu::{DeviceCaps, GpuFault};
|
||||
|
||||
use crate::{Backing, DeviceBacking};
|
||||
use crate::{Backing, DeviceBacking, probe_fallback};
|
||||
|
||||
/// Features this context asks a device for. No provider dispatches a real WGSL job on wgpu
|
||||
/// yet (`craft-gpu-providers` ships CPU stand-ins, by design, until that lands); extend this
|
||||
@@ -86,71 +77,77 @@ mod native {
|
||||
/// [`create_device`].
|
||||
const DESIRED_FEATURES: wgpu::Features = wgpu::Features::empty();
|
||||
|
||||
/// An instance over whichever native backends were compiled in (`native-vulkan`,
|
||||
/// `native-dx12`, `native-metal`, `native-gles`), honoring `WGPU_BACKEND` when set, so the
|
||||
/// An instance over `craft_gpu_device::native_descriptor`'s backends (Vulkan, Metal and
|
||||
/// DirectX 12, plus OpenGL except on Windows). OpenGL is also used on Windows when it is
|
||||
/// the only compiled native backend. The instance honors `WGPU_BACKEND` when set, so the
|
||||
/// same build can be pointed at a software Vulkan adapter (lavapipe/llvmpipe) in a local container run or a CI lane.
|
||||
/// `new_without_display_handle` because this context never has a window (no surface is ever
|
||||
/// requested); FilmCraft's own off-screen export device uses the same constructor for the
|
||||
/// same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`).
|
||||
/// The descriptor has no display handle because this context never has a window (no surface
|
||||
/// is ever requested); FilmCraft's own off-screen export device uses the same constructor for
|
||||
/// the same reason (`filmcraft-gpu`'s `export_renderer.rs`, see `docs/gpu-backends.md`).
|
||||
///
|
||||
/// The process holds one instance, made on the first call and returned by every later one,
|
||||
/// so `WGPU_BACKEND` is read once. Every context and every probe requests its adapter from
|
||||
/// it. An instance per context loads and unloads every installed Vulkan driver each time, and
|
||||
/// on Linux with Ubuntu's `mesa-vulkan-drivers` installed, contexts opened that way from
|
||||
/// several threads at once crash with SIGSEGV while a lavapipe device is in use.
|
||||
pub(crate) fn instance() -> wgpu::Instance {
|
||||
static SHARED: std::sync::OnceLock<wgpu::Instance> = std::sync::OnceLock::new();
|
||||
SHARED
|
||||
.get_or_init(|| {
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
if let Some(backends) = wgpu::Backends::from_env() {
|
||||
desc.backends = backends;
|
||||
}
|
||||
wgpu::Instance::new(desc)
|
||||
})
|
||||
.clone()
|
||||
pub(crate) fn instance() -> Option<wgpu::Instance> {
|
||||
instance_with_backends(wgpu::Instance::enabled_backend_features())
|
||||
}
|
||||
|
||||
/// Request a real device. `None` on the defined no-adapter path (no usable adapter): the
|
||||
/// caller degrades to the staging backing, identical in shape to `craft-gpu-null`.
|
||||
pub(crate) fn instance_with_backends(backends: wgpu::Backends) -> Option<wgpu::Instance> {
|
||||
if backends.is_empty() {
|
||||
return None;
|
||||
}
|
||||
static SHARED: std::sync::OnceLock<wgpu::Instance> = std::sync::OnceLock::new();
|
||||
Some(
|
||||
SHARED
|
||||
.get_or_init(|| {
|
||||
let mut desc = craft_gpu_device::native_descriptor();
|
||||
if let Some(backends) = wgpu::Backends::from_env() {
|
||||
desc.backends = backends;
|
||||
}
|
||||
wgpu::Instance::new(desc)
|
||||
})
|
||||
.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Open a real device on `instance` with `craft-gpu-device`'s choice for
|
||||
/// `Preference::Auto`. `None` on the defined no-adapter path (no usable adapter): the caller
|
||||
/// degrades to the staging backing, identical in shape to `craft-gpu-null`.
|
||||
///
|
||||
/// Never panics: `required_features` is intersected with what the adapter actually
|
||||
/// advertises, and `required_limits` is set to the adapter's own limits (never more), so
|
||||
/// Never panics: `craft_gpu_device::open` asks only for the features from
|
||||
/// [`DESIRED_FEATURES`] the adapter has, and for the adapter's own limits (never more), so
|
||||
/// `request_device`'s documented panics ("features/limits not supported by this adapter")
|
||||
/// cannot trigger here.
|
||||
pub(crate) fn create_device_on(instance: &wgpu::Instance) -> Option<(DeviceCaps, Backing)> {
|
||||
let request = Request { label: Some("craft-gpu-wgpu"), optional_features: DESIRED_FEATURES, ..Default::default() };
|
||||
let opened = craft_gpu_device::open(instance, None, &Preference::Auto, &request).ok()?;
|
||||
Some(backing_of(&opened))
|
||||
}
|
||||
|
||||
pub(crate) fn create_device() -> Option<(DeviceCaps, Backing)> {
|
||||
let instance = instance();
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).ok()?;
|
||||
let features = DESIRED_FEATURES & adapter.features();
|
||||
let limits = adapter.limits();
|
||||
let desc =
|
||||
wgpu::DeviceDescriptor { label: Some("craft-gpu-wgpu"), required_features: features, required_limits: limits, ..Default::default() };
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&desc)).ok()?;
|
||||
create_device_on(&instance()?)
|
||||
}
|
||||
|
||||
let lost = Arc::new(Mutex::new(None));
|
||||
{
|
||||
let lost = Arc::clone(&lost);
|
||||
device.set_device_lost_callback(move |reason, message| {
|
||||
if let Ok(mut slot) = lost.lock() {
|
||||
*slot = Some(GpuFault::DeviceLost(format!("{reason:?}: {message}")));
|
||||
}
|
||||
});
|
||||
pub(crate) fn backing_of(opened: &Opened) -> (DeviceCaps, Backing) {
|
||||
backing_with(opened.device.clone(), opened.queue.clone(), opened.health.clone())
|
||||
}
|
||||
|
||||
/// The device's own caps, and a backing that reads the loss from `health`.
|
||||
pub(crate) fn backing_with(device: wgpu::Device, queue: wgpu::Queue, health: DeviceHealth) -> (DeviceCaps, Backing) {
|
||||
let caps = craft_gpu_device::device_caps(&device);
|
||||
(caps, Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), health, pending: Vec::new() }))
|
||||
}
|
||||
|
||||
/// The adapter `craft-gpu-device` would open for `Preference::Auto`, with its advertised
|
||||
/// limits and no features (no device was opened to grant any).
|
||||
pub(crate) fn probe_caps_on(instance: &wgpu::Instance) -> DeviceCaps {
|
||||
let (adapters, _) = craft_gpu_device::list(instance, None);
|
||||
match craft_gpu_device::pick(&adapters, None, &Preference::Auto) {
|
||||
Ok((adapter, _)) => DeviceCaps { features: Vec::new(), ..Capabilities::of_adapter(&adapter).into_device_caps() },
|
||||
Err(_) => probe_fallback("wgpu", "no-adapter"),
|
||||
}
|
||||
|
||||
let info = device.adapter_info();
|
||||
let device_limits = device.limits();
|
||||
let caps = DeviceCaps {
|
||||
backend_name: format!("{:?}", info.backend),
|
||||
device_name: info.name,
|
||||
max_storage_buffer_binding_size: device_limits.max_storage_buffer_binding_size,
|
||||
max_buffer_size: device_limits.max_buffer_size,
|
||||
max_texture_dimension_2d: device_limits.max_texture_dimension_2d,
|
||||
features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(),
|
||||
vendor_id: info.vendor,
|
||||
software: info.device_type == wgpu::DeviceType::Cpu,
|
||||
};
|
||||
let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() });
|
||||
Some((caps, backing))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,12 +177,72 @@ struct DeviceBacking {
|
||||
/// matching the staging path and `craft-gpu-null` exactly, with no padding visible. `None`
|
||||
/// once freed: see the `Backing::Staging` doc for why the slot stays rather than shifting.
|
||||
buffers: Vec<Option<(wgpu::Buffer, u64)>>,
|
||||
/// Set by the device-lost callback registered in [`native::create_device`]; checked before
|
||||
/// every call that would otherwise touch the (now invalid) device.
|
||||
lost: std::sync::Arc<std::sync::Mutex<Option<GpuFault>>>,
|
||||
/// The device's health from `craft-gpu-device`, which holds its device-lost callback; its
|
||||
/// loss is checked before every call that would otherwise touch the (now invalid) device.
|
||||
health: craft_gpu_device::DeviceHealth,
|
||||
pending: Vec<PendingRead>,
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
impl DeviceBacking {
|
||||
fn allocation_fault(&self, error: wgpu::Error, operation: &str) -> GpuFault {
|
||||
self.health.caught(&self.device, &error);
|
||||
if let Err(fault) = self.health.device_status() {
|
||||
return fault;
|
||||
}
|
||||
self.prefer_device_loss(GpuFault::Operation(format!("{operation}: {error}")))
|
||||
}
|
||||
|
||||
fn prefer_device_loss(&self, fault: GpuFault) -> GpuFault {
|
||||
if !matches!(fault, GpuFault::DeviceLost(_))
|
||||
&& let Err(loss @ GpuFault::DeviceLost(_)) = self.check_device_valid()
|
||||
{
|
||||
return loss;
|
||||
}
|
||||
fault
|
||||
}
|
||||
|
||||
fn submit_read_copy(&self, commands: wgpu::CommandBuffer, scope: wgpu::ErrorScopeGuard) -> Result<wgpu::SubmissionIndex, GpuFault> {
|
||||
let submission = self.queue.submit(Some(commands));
|
||||
if let Some(error) = pollster::block_on(scope.pop()) {
|
||||
return Err(self.allocation_fault(error, "request_read: device reported an allocation error copying the buffer"));
|
||||
}
|
||||
self.check_device_valid()?;
|
||||
Ok(submission)
|
||||
}
|
||||
|
||||
fn check_device_valid(&self) -> Result<(), GpuFault> {
|
||||
// wgpu-core 30.0.1 checks device validity before rejecting empty buffer usage.
|
||||
// A valid device produces a scoped validation error; device loss bypasses the scope.
|
||||
// Both paths return before HAL allocation or fence waits.
|
||||
// Device owners must synchronize concurrent destroy calls with uploads.
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let scope = self.device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
drop(self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: 0,
|
||||
usage: wgpu::BufferUsages::empty(),
|
||||
mapped_at_creation: false,
|
||||
}));
|
||||
pollster::block_on(scope.pop())
|
||||
}));
|
||||
self.health.probe(&self.device);
|
||||
self.health.device_status()?;
|
||||
match result {
|
||||
Ok(None) => {
|
||||
self.health.confirm_device_lost("the device was destroyed or lost".into());
|
||||
}
|
||||
Err(_) => self.health.record_device_loss("the device stopped responding".into()),
|
||||
Ok(Some(_)) => {}
|
||||
}
|
||||
self.health.device_status()?;
|
||||
if let Some(fault) = self.health.polling_fault() {
|
||||
return Err(fault.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// wgpu's `COPY_BUFFER_ALIGNMENT`: every buffer with copy usage, and every `write_buffer` /
|
||||
/// `copy_buffer_to_buffer` size, must be a multiple of this (4 bytes). Uploading or reading back
|
||||
/// a buffer length that doesn't land on this boundary (`b"xy"`, two bytes) is a validation error
|
||||
@@ -200,6 +257,7 @@ struct PendingRead {
|
||||
request: ReadRequest,
|
||||
handle: HandleId,
|
||||
staging: wgpu::Buffer,
|
||||
submission: wgpu::SubmissionIndex,
|
||||
/// True length to truncate the mapped (padded) bytes back down to.
|
||||
true_len: u64,
|
||||
state: std::sync::Arc<std::sync::Mutex<Option<Result<(), String>>>>,
|
||||
@@ -207,7 +265,7 @@ struct PendingRead {
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
fn resolve_pending(pending: PendingRead) -> ReadOutcome {
|
||||
let PendingRead { request, handle, staging, true_len, state } = pending;
|
||||
let PendingRead { request, handle, staging, true_len, state, .. } = pending;
|
||||
let result = match state.lock() {
|
||||
Ok(mut guard) => match guard.take() {
|
||||
Some(Ok(())) => match staging.get_mapped_range(0..true_len.next_multiple_of(COPY_ALIGN)) {
|
||||
@@ -262,6 +320,38 @@ impl WgpuContext {
|
||||
Self { caps, worker_kind, backing: Backing::Staging(Vec::new()), next_request: 0, ready: Vec::new() }
|
||||
}
|
||||
|
||||
/// A context on a device `craft_gpu_device::open` (or `open_async`) opened, sharing its
|
||||
/// device, queue and [`DeviceHealth`](craft_gpu_device::DeviceHealth). The caps are the
|
||||
/// device's own (`Opened::device_caps`). A loss the health records, from the device-lost
|
||||
/// callback it set or from any other user of the device, is this context's
|
||||
/// `GpuFault::DeviceLost`.
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
pub fn from_opened(worker_kind: WorkerKind, opened: &craft_gpu_device::Opened) -> Self {
|
||||
let (caps, backing) = native::backing_of(opened);
|
||||
Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() }
|
||||
}
|
||||
|
||||
/// A context on a device the caller opened, such as the one egui-wgpu's render state holds.
|
||||
/// `queue` must be the queue opened with `device`.
|
||||
/// `health` is the device's [`DeviceHealth::watch`](craft_gpu_device::DeviceHealth::watch);
|
||||
/// wgpu keeps one device-lost callback per device, so this context sets none of its own. The
|
||||
/// caps are the device's own: the features and limits it was opened with, whatever they are.
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
pub fn with_device(worker_kind: WorkerKind, device: wgpu::Device, queue: wgpu::Queue, health: craft_gpu_device::DeviceHealth) -> Self {
|
||||
let (caps, backing) = native::backing_with(device, queue, health);
|
||||
Self { caps, worker_kind, backing, next_request: 0, ready: Vec::new() }
|
||||
}
|
||||
|
||||
/// The health of this context's device, when it has one: share it with the rest of the app,
|
||||
/// and with `craft_gpu_device::Recovery` after a loss.
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
pub fn health(&self) -> Option<&craft_gpu_device::DeviceHealth> {
|
||||
match &self.backing {
|
||||
Backing::Device(d) => Some(&d.health),
|
||||
Backing::Staging(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when this context holds a real device (`request_device` succeeded), false on the
|
||||
/// staging/no-adapter path. Settings UI can use this to show "no GPU" honestly instead of
|
||||
/// implying a device that was never created; tests use it to skip rather than fail when the
|
||||
@@ -283,7 +373,7 @@ impl WgpuContext {
|
||||
pub fn is_device_lost(&self) -> bool {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
return d.lost.lock().map(|g| g.is_some()).unwrap_or(false);
|
||||
return d.health.device_status().is_err();
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -291,7 +381,52 @@ impl WgpuContext {
|
||||
fn take_lost_fault(&self) -> Option<GpuFault> {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
return d.lost.lock().ok().and_then(|g| g.clone());
|
||||
return d.health.device_status().err();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `read_buffer` waits for the requested read's copy submission between polls.
|
||||
/// `DeviceHealth::wait` does not wait once the device reported an error other than out of
|
||||
/// memory, stops after its current 100 ms slice when another user of the device records
|
||||
/// such an error, and fails when its poll fails. Then the read of `request` is dropped and
|
||||
/// fails with that error, instead of polling in a loop until a map that may never complete;
|
||||
/// a loss is left to the next `poll_reads`, which fails every pending read with it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[cfg_attr(not(feature = "adapter-probe"), allow(unused_variables, clippy::unused_self))]
|
||||
fn wait_between_reads(&mut self, request: ReadRequest) -> Option<GpuFault> {
|
||||
#[cfg(feature = "adapter-probe")]
|
||||
if let Backing::Device(d) = &mut self.backing
|
||||
&& (d.health.polling_fault().is_some()
|
||||
|| d.pending.iter().find(|p| p.request == request).is_some_and(|p| !d.health.wait(&d.device, p.submission.clone())))
|
||||
{
|
||||
d.health.probe(&d.device);
|
||||
if d.health.device_status().is_err() {
|
||||
return None;
|
||||
}
|
||||
let fault = d.prefer_device_loss(
|
||||
d.health
|
||||
.polling_fault()
|
||||
.or_else(|| d.health.fault())
|
||||
.map(GpuFault::from)
|
||||
.unwrap_or_else(|| GpuFault::Operation("read_buffer: waiting for the device failed".into())),
|
||||
);
|
||||
if matches!(fault, GpuFault::DeviceLost(_)) {
|
||||
return None;
|
||||
}
|
||||
d.pending.retain(|p| p.request != request);
|
||||
return Some(fault);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Why no new work may go to the device: a loss as `GpuFault::DeviceLost`, and any other
|
||||
/// fault its health recorded (an uncaptured error, or an out-of-memory error the app has not
|
||||
/// cleared with `DeviceHealth::clear_out_of_memory`) as `GpuFault::Operation`.
|
||||
fn take_work_fault(&self) -> Option<GpuFault> {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
return d.health.fault().map(GpuFault::from);
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -308,8 +443,15 @@ impl GpuContext for WgpuContext {
|
||||
|
||||
#[cfg_attr(not(all(not(target_arch = "wasm32"), feature = "adapter-probe")), allow(unused_variables))]
|
||||
fn upload_buffer(&mut self, label: &str, bytes: &[u8]) -> Result<HandleId, GpuFault> {
|
||||
if let Some(fault) = self.take_lost_fault() {
|
||||
return Err(fault);
|
||||
if let Some(fault) = self.take_work_fault() {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if !matches!(fault, GpuFault::DeviceLost(_))
|
||||
&& let Backing::Device(d) = &self.backing
|
||||
&& let Err(loss @ GpuFault::DeviceLost(_)) = d.check_device_valid()
|
||||
{
|
||||
return Err(loss);
|
||||
}
|
||||
return Err(self.take_work_fault().unwrap_or(fault));
|
||||
}
|
||||
match &mut self.backing {
|
||||
Backing::Staging(buffers) => {
|
||||
@@ -322,10 +464,10 @@ impl GpuContext for WgpuContext {
|
||||
let true_len = bytes.len() as u64;
|
||||
let padded_len = true_len.next_multiple_of(COPY_ALIGN);
|
||||
if padded_len > self.caps.max_buffer_size {
|
||||
return Err(GpuFault::InvalidJob(format!(
|
||||
return Err(d.prefer_device_loss(GpuFault::InvalidJob(format!(
|
||||
"upload_buffer: {true_len} bytes (padded to {padded_len}) exceeds the device's max_buffer_size {}",
|
||||
self.caps.max_buffer_size
|
||||
)));
|
||||
))));
|
||||
}
|
||||
// The size check above only catches a request past the device's advertised
|
||||
// maximum; it proves nothing about whether the device can actually allocate
|
||||
@@ -345,7 +487,8 @@ impl GpuContext for WgpuContext {
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
if let Some(err) = pollster::block_on(create_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error creating the buffer: {err}")));
|
||||
// The scope kept it from the device's health; every user of the device sees it.
|
||||
return Err(d.allocation_fault(err, "upload_buffer: device reported an allocation error creating the buffer"));
|
||||
}
|
||||
// write_buffer makes its own staging allocation to carry `bytes` to the device, a
|
||||
// second allocation that can also run out of memory; it gets its own scope rather
|
||||
@@ -367,8 +510,10 @@ impl GpuContext for WgpuContext {
|
||||
// is still a submission as far as that flush is concerned, so it is enough.
|
||||
d.queue.submit(std::iter::empty());
|
||||
if let Some(err) = pollster::block_on(write_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("upload_buffer: device reported an allocation error writing the buffer: {err}")));
|
||||
return Err(d.allocation_fault(err, "upload_buffer: device reported an allocation error writing the buffer"));
|
||||
}
|
||||
// Loss bypasses error scopes and its callback can wait for pending queue work.
|
||||
d.check_device_valid()?;
|
||||
let id = u32::try_from(d.buffers.len()).map_err(|_| GpuFault::Operation("too many buffers".into()))?;
|
||||
d.buffers.push(Some((buffer, true_len)));
|
||||
Ok(HandleId(id))
|
||||
@@ -394,8 +539,26 @@ impl GpuContext for WgpuContext {
|
||||
}
|
||||
|
||||
fn request_read(&mut self, handle: HandleId) -> Result<ReadRequest, GpuFault> {
|
||||
if let Some(fault) = self.take_lost_fault() {
|
||||
return Err(fault);
|
||||
if let Some(fault) = self.take_work_fault() {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if !matches!(fault, GpuFault::DeviceLost(_))
|
||||
&& let Backing::Device(d) = &self.backing
|
||||
&& let Err(loss @ GpuFault::DeviceLost(_)) = d.check_device_valid()
|
||||
{
|
||||
return Err(loss);
|
||||
}
|
||||
return Err(self.take_work_fault().unwrap_or(fault));
|
||||
}
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
d.buffers
|
||||
.get(handle.0 as usize)
|
||||
.and_then(Option::as_ref)
|
||||
.ok_or_else(|| d.prefer_device_loss(GpuFault::InvalidJob("bad handle".into())))?;
|
||||
d.check_device_valid()?;
|
||||
if let Some(fault) = self.take_work_fault() {
|
||||
return Err(fault);
|
||||
}
|
||||
}
|
||||
match &mut self.backing {
|
||||
Backing::Staging(buffers) => {
|
||||
@@ -409,8 +572,11 @@ impl GpuContext for WgpuContext {
|
||||
}
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
Backing::Device(d) => {
|
||||
let (buffer, true_len) =
|
||||
d.buffers.get(handle.0 as usize).and_then(Option::as_ref).ok_or_else(|| GpuFault::InvalidJob("bad handle".into()))?;
|
||||
let (buffer, true_len) = d
|
||||
.buffers
|
||||
.get(handle.0 as usize)
|
||||
.and_then(Option::as_ref)
|
||||
.ok_or_else(|| d.prefer_device_loss(GpuFault::InvalidJob("bad handle".into())))?;
|
||||
let true_len = *true_len;
|
||||
if true_len == 0 {
|
||||
// An empty buffer has nothing to copy or map (wgpu refuses an empty map
|
||||
@@ -443,17 +609,14 @@ impl GpuContext for WgpuContext {
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
if let Some(err) = pollster::block_on(create_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("request_read: device reported an allocation error creating the staging buffer: {err}")));
|
||||
return Err(d.allocation_fault(err, "request_read: device reported an allocation error creating the staging buffer"));
|
||||
}
|
||||
// The copy and its submission get their own scope rather than reusing the one
|
||||
// already closed above, same split as upload_buffer's create vs. write.
|
||||
let copy_scope = d.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let mut encoder = d.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("craft-gpu-wgpu.read-copy") });
|
||||
encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, copy_len);
|
||||
d.queue.submit(Some(encoder.finish()));
|
||||
if let Some(err) = pollster::block_on(copy_scope.pop()) {
|
||||
return Err(GpuFault::Operation(format!("request_read: device reported an allocation error copying the buffer: {err}")));
|
||||
}
|
||||
let submission = d.submit_read_copy(encoder.finish(), copy_scope)?;
|
||||
let state = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
{
|
||||
let state = std::sync::Arc::clone(&state);
|
||||
@@ -466,7 +629,7 @@ impl GpuContext for WgpuContext {
|
||||
let id = self.next_request;
|
||||
self.next_request = self.next_request.wrapping_add(1);
|
||||
let request = ReadRequest(id);
|
||||
d.pending.push(PendingRead { request, handle, staging, true_len, state });
|
||||
d.pending.push(PendingRead { request, handle, staging, submission, true_len, state });
|
||||
Ok(request)
|
||||
}
|
||||
}
|
||||
@@ -506,16 +669,32 @@ impl GpuContext for WgpuContext {
|
||||
let mut outcomes = std::mem::take(&mut self.ready);
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
if let Backing::Device(d) = &mut self.backing {
|
||||
if let Some(fault) = d.lost.lock().ok().and_then(|g| g.clone()) {
|
||||
// A non-blocking poll that also runs after an error other than a loss was recorded,
|
||||
// and records a loss instead of panicking when the device is gone.
|
||||
d.health.probe(&d.device);
|
||||
let fault = d.health.polling_fault().map(GpuFault::from);
|
||||
if let Some(fault) = fault {
|
||||
let fault = d.prefer_device_loss(fault);
|
||||
outcomes.extend(d.pending.drain(..).map(|p| ReadOutcome { request: p.request, handle: p.handle, result: Err(fault.clone()) }));
|
||||
return outcomes;
|
||||
}
|
||||
let _ = d.device.poll(wgpu::PollType::Poll);
|
||||
let mut remaining = Vec::with_capacity(d.pending.len());
|
||||
for pending in d.pending.drain(..) {
|
||||
let mut remaining: Vec<PendingRead> = Vec::with_capacity(d.pending.len());
|
||||
let mut pending_reads = std::mem::take(&mut d.pending).into_iter();
|
||||
while let Some(pending) = pending_reads.next() {
|
||||
let is_ready = pending.state.lock().map(|g| g.is_some()).unwrap_or(false);
|
||||
if is_ready {
|
||||
outcomes.push(resolve_pending(pending));
|
||||
let mut outcome = resolve_pending(pending);
|
||||
outcome.result = outcome.result.map_err(|fault| d.prefer_device_loss(fault));
|
||||
if let Err(fault @ GpuFault::DeviceLost(_)) = &outcome.result {
|
||||
outcomes.extend(remaining.into_iter().chain(pending_reads).map(|p| ReadOutcome {
|
||||
request: p.request,
|
||||
handle: p.handle,
|
||||
result: Err(fault.clone()),
|
||||
}));
|
||||
outcomes.push(outcome);
|
||||
return outcomes;
|
||||
}
|
||||
outcomes.push(outcome);
|
||||
} else {
|
||||
remaining.push(pending);
|
||||
}
|
||||
@@ -547,9 +726,8 @@ impl GpuContext for WgpuContext {
|
||||
// Block on the GPU between polls instead of busy-spinning the CPU. A no-op when
|
||||
// `backing` is `Staging` (nothing to wait for; the request already resolved above)
|
||||
// or when wgpu is itself WebGPU under the hood, which self-polls.
|
||||
#[cfg(feature = "adapter-probe")]
|
||||
if let Backing::Device(d) = &self.backing {
|
||||
let _ = d.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
if let Some(fault) = self.wait_between_reads(request) {
|
||||
return Err(fault);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,10 +341,16 @@ fn device_status_surfaces_loss_even_with_nothing_pending() {
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
#[test]
|
||||
fn every_context_and_probe_shares_one_wgpu_instance() {
|
||||
let first = crate::native::instance();
|
||||
let again = std::thread::spawn(crate::native::instance).join().expect("instance() on another thread");
|
||||
let first = crate::native::instance().expect("the noop backend is compiled");
|
||||
let again = std::thread::spawn(crate::native::instance).join().expect("instance() on another thread").expect("the noop backend is compiled");
|
||||
assert_eq!(first, again, "a second call, from another thread, must return the same instance");
|
||||
assert_eq!(first, crate::native::instance(), "a later call must return the same instance");
|
||||
assert_eq!(Some(first), crate::native::instance(), "a later call must return the same instance");
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
#[test]
|
||||
fn no_compiled_backend_returns_no_instance() {
|
||||
assert!(crate::native::instance_with_backends(wgpu::Backends::empty()).is_none());
|
||||
}
|
||||
|
||||
/// Same two guarantees on a real device: empty buffers round-trip (the readback resolves without
|
||||
@@ -377,3 +383,557 @@ fn real_device_empty_buffer_and_interleaved_read_buffer_behave_like_staging() {
|
||||
}
|
||||
assert!(seen_a, "a's completion must still arrive through poll_reads after b's read_buffer");
|
||||
}
|
||||
|
||||
/// Devices from `craft-gpu-device`, on wgpu's noop backend, so these run without a GPU.
|
||||
#[cfg(all(not(target_arch = "wasm32"), feature = "adapter-probe"))]
|
||||
mod device_from_craft_gpu_device {
|
||||
use craft_gpu::{GpuContext, GpuFault, WorkerKind};
|
||||
use craft_gpu_device::{DeviceHealth, Fault, Preference, Request};
|
||||
|
||||
use crate::{Backing, WgpuContext, native};
|
||||
|
||||
/// An instance whose only adapter is wgpu's noop one, which wgpu 30 lists as a software
|
||||
/// adapter.
|
||||
fn noop() -> wgpu::Instance {
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = wgpu::Backends::NOOP;
|
||||
desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, ..Default::default() };
|
||||
wgpu::Instance::new(desc)
|
||||
}
|
||||
|
||||
fn opened() -> craft_gpu_device::Opened {
|
||||
craft_gpu_device::open(&noop(), None, &Preference::Software, &Request::default()).expect("the noop adapter opens")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_copy_rejected_after_device_destruction_reports_loss() {
|
||||
let opened = opened();
|
||||
let ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
d.check_device_valid().expect("a valid device");
|
||||
let scope = opened.device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let commands = opened.device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()).finish();
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
|
||||
assert!(matches!(d.submit_read_copy(commands, scope), Err(GpuFault::DeviceLost(_))));
|
||||
assert!(opened.health.device_lost());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_allocation_fault_returns_loss_discovered_by_caught() {
|
||||
for destroyed in [false, true] {
|
||||
let opened = opened();
|
||||
let ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
if destroyed {
|
||||
opened.device.destroy();
|
||||
}
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
let error = wgpu::Error::OutOfMemory { source: Box::new(std::io::Error::other("allocation failed")) };
|
||||
let fault = d.allocation_fault(error, "allocation");
|
||||
if destroyed {
|
||||
assert!(matches!(fault, GpuFault::DeviceLost(_)), "{fault:?}");
|
||||
assert!(opened.health.device_lost());
|
||||
} else {
|
||||
assert!(matches!(fault, GpuFault::Operation(_)), "{fault:?}");
|
||||
assert!(opened.health.fault().is_some_and(|fault| fault.is_out_of_memory()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_allocation_fault_detects_loss_before_callback_delivery() {
|
||||
for validation in [false, true] {
|
||||
let opened = opened();
|
||||
let ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
if validation {
|
||||
opened.health.mark(Fault::Error("Validation Error".into()));
|
||||
}
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
let error = wgpu::Error::OutOfMemory { source: Box::new(std::io::Error::other("allocation failed")) };
|
||||
|
||||
let fault = d.allocation_fault(error, "allocation");
|
||||
assert!(matches!(fault, GpuFault::DeviceLost(_)), "{fault:?}");
|
||||
assert!(opened.health.device_lost());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_device_is_the_one_craft_gpu_device_opens() {
|
||||
let (caps, backing) = native::create_device_on(&noop()).expect("the noop adapter opens");
|
||||
let Backing::Device(d) = &backing else { panic!("a device backing") };
|
||||
assert_eq!(caps, craft_gpu_device::device_caps(&d.device));
|
||||
assert!(caps.software, "{caps:?}");
|
||||
assert!(d.health.is_ok() && d.health.device_status().is_ok());
|
||||
// no adapter at all: the staging path
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = wgpu::Backends::NOOP;
|
||||
assert!(native::create_device_on(&wgpu::Instance::new(desc)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_probe_reports_the_adapter_craft_gpu_device_picks() {
|
||||
let opened = opened();
|
||||
let caps = native::probe_caps_on(&noop());
|
||||
assert_eq!(caps.device_name, opened.candidate.name);
|
||||
assert!(caps.software && caps.features.is_empty(), "{caps:?}");
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = wgpu::Backends::NOOP;
|
||||
assert_eq!(native::probe_caps_on(&wgpu::Instance::new(desc)).device_name, "no-adapter");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_context_on_an_opened_device_reads_the_loss_from_its_health() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
assert!(ctx.has_device());
|
||||
assert_eq!(ctx.caps(), opened.device_caps());
|
||||
assert_eq!(ctx.device_status(), Ok(()));
|
||||
// a loss another user of the device records is this context's loss too
|
||||
opened.health.mark(Fault::Lost("the driver reset the GPU".into()));
|
||||
assert!(ctx.health().is_some_and(|h| h.device_status().is_err()));
|
||||
assert_eq!(ctx.device_status(), Err(GpuFault::DeviceLost("the driver reset the GPU".into())));
|
||||
assert!(ctx.is_device_lost());
|
||||
assert!(matches!(ctx.upload_buffer("after-loss", b"x"), Err(GpuFault::DeviceLost(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_destroyed_device_is_lost_through_the_health_that_watches_it() {
|
||||
let opened = opened();
|
||||
let health = DeviceHealth::watch(&opened.device);
|
||||
let mut ctx = WgpuContext::with_device(WorkerKind::DedicatedWorker, opened.device.clone(), opened.queue.clone(), health.clone());
|
||||
assert_eq!(ctx.caps(), opened.device_caps());
|
||||
opened.device.destroy();
|
||||
let _ = ctx.poll_reads();
|
||||
assert!(health.device_status().is_err(), "{health:?}");
|
||||
assert!(matches!(ctx.device_status(), Err(GpuFault::DeviceLost(_))));
|
||||
assert!(matches!(ctx.request_read(craft_gpu::HandleId(0)), Err(GpuFault::DeviceLost(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_upload_to_a_destroyed_shared_device_fails_without_a_poll_first() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
opened.device.destroy();
|
||||
assert!(matches!(ctx.upload_buffer("after-destroy", b"abcd"), Err(GpuFault::DeviceLost(_))));
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.buffers.is_empty(), "no handle is kept for the failed upload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_read_detects_loss_before_the_callback_updates_health() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("empty", b"").expect("upload");
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
let next_request = ctx.next_request;
|
||||
assert!(matches!(ctx.request_read(handle), Err(GpuFault::DeviceLost(_))));
|
||||
assert_eq!(ctx.next_request, next_request);
|
||||
assert!(ctx.ready.is_empty());
|
||||
assert!(opened.health.device_lost());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonempty_read_detects_loss_before_the_callback_updates_health() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("nonempty", b"abcd").expect("upload");
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
let next_request = ctx.next_request;
|
||||
assert!(matches!(ctx.request_read(handle), Err(GpuFault::DeviceLost(_))));
|
||||
assert_eq!(ctx.next_request, next_request);
|
||||
assert!(ctx.ready.is_empty());
|
||||
assert!(opened.health.device_lost());
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_upload_to_a_destroyed_device_fails_when_the_loss_waits_for_pending_work() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let work_pending = Arc::new(AtomicBool::new(true));
|
||||
let delivered = Arc::new(AtomicBool::new(false));
|
||||
let loss_pending = Arc::new(AtomicBool::new(false));
|
||||
let flag = Arc::clone(&loss_pending);
|
||||
// The noop queue finishes immediately. This gate emulates work that stays pending
|
||||
// through every upload poll, with loss delivery controlled by the test.
|
||||
opened.device.set_device_lost_callback(move |_, _| {
|
||||
flag.store(true, Ordering::Release);
|
||||
});
|
||||
let deliver_loss = || {
|
||||
if !work_pending.load(Ordering::Acquire) && loss_pending.swap(false, Ordering::AcqRel) {
|
||||
let health = opened.health.clone();
|
||||
let delivered = Arc::clone(&delivered);
|
||||
opened.queue.on_submitted_work_done(move || {
|
||||
health.mark(Fault::Lost("destroyed".into()));
|
||||
delivered.store(true, Ordering::Release);
|
||||
});
|
||||
}
|
||||
};
|
||||
opened.queue.submit([]);
|
||||
opened.device.destroy();
|
||||
assert!(!delivered.load(Ordering::Acquire));
|
||||
deliver_loss();
|
||||
assert_eq!(ctx.device_status(), Ok(()));
|
||||
assert!(matches!(ctx.upload_buffer("after-destroy", b"abcd"), Err(GpuFault::DeviceLost(_))));
|
||||
assert!(opened.health.device_lost());
|
||||
assert!(work_pending.load(Ordering::Acquire));
|
||||
assert!(!delivered.load(Ordering::Acquire), "the upload must detect loss before callback delivery");
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.buffers.is_empty(), "no handle is kept for the failed upload");
|
||||
work_pending.store(false, Ordering::Release);
|
||||
assert!(loss_pending.load(Ordering::Acquire), "the device-lost callback must run");
|
||||
deliver_loss();
|
||||
assert!(!delivered.load(Ordering::Acquire));
|
||||
ctx.poll_reads();
|
||||
assert!(delivered.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_loss_overrides_an_earlier_work_fault_before_callback_delivery() {
|
||||
for message in [craft_gpu_device::OUT_OF_MEMORY, "Validation Error"] {
|
||||
for upload in [false, true] {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("request_read");
|
||||
opened.health.mark(Fault::Error(message.into()));
|
||||
// The noop queue completes immediately. The test defers the callback's health update until after the call.
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.fault(), Some(Fault::Error(message.into())));
|
||||
let next_request = ctx.next_request;
|
||||
let result = if upload { ctx.upload_buffer("after-destroy", b"abcd").map(|_| ()) } else { ctx.request_read(handle).map(|_| ()) };
|
||||
assert!(matches!(result, Err(GpuFault::DeviceLost(_))), "{result:?}");
|
||||
assert!(opened.health.device_lost());
|
||||
assert_eq!(ctx.next_request, next_request);
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert_eq!(d.buffers.len(), 1);
|
||||
assert_eq!(d.pending.len(), 1);
|
||||
assert_eq!(d.pending[0].request, request);
|
||||
assert!(ctx.ready.is_empty());
|
||||
opened.health.mark(Fault::Lost("destroyed".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_rechecks_out_of_memory_reported_during_the_validity_probe() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("before", b"abcd").expect("upload");
|
||||
let health = opened.health.clone();
|
||||
opened.queue.on_submitted_work_done(move || {
|
||||
health.mark(Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()));
|
||||
});
|
||||
assert_eq!(opened.health.fault(), None);
|
||||
let next_request = ctx.next_request;
|
||||
|
||||
assert_eq!(ctx.request_read(handle), Err(GpuFault::Operation(craft_gpu_device::OUT_OF_MEMORY.into())));
|
||||
assert!(opened.health.fault().is_some_and(|fault| fault.is_out_of_memory()));
|
||||
assert_eq!(ctx.next_request, next_request);
|
||||
assert!(ctx.ready.is_empty());
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_work_preserves_out_of_memory_precedence_over_validation_errors() {
|
||||
for oom_first in [true, false] {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("before", b"abcd").expect("upload");
|
||||
let faults = [Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()), Fault::Error("Validation Error".into())];
|
||||
for index in if oom_first { [0, 1] } else { [1, 0] } {
|
||||
opened.health.mark(faults[index].clone());
|
||||
}
|
||||
assert_eq!(ctx.upload_buffer("oom", b"x"), Err(GpuFault::Operation(craft_gpu_device::OUT_OF_MEMORY.into())));
|
||||
assert_eq!(ctx.request_read(handle), Err(GpuFault::Operation(craft_gpu_device::OUT_OF_MEMORY.into())));
|
||||
assert_eq!(ctx.device_status(), Ok(()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_work_goes_to_a_device_whose_health_recorded_an_error() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("before", b"abcd").expect("upload on a healthy device");
|
||||
// an out-of-memory error stops new work until the app clears it
|
||||
opened.health.mark(Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()));
|
||||
assert!(matches!(ctx.upload_buffer("oom", b"x"), Err(GpuFault::Operation(_))));
|
||||
assert!(matches!(ctx.request_read(handle), Err(GpuFault::Operation(_))));
|
||||
assert_eq!(ctx.device_status(), Ok(()), "only a loss is a device_status fault");
|
||||
ctx.free_buffer(handle);
|
||||
opened.health.clear_out_of_memory(opened.health.out_of_memory_count());
|
||||
let handle = ctx.upload_buffer("after", b"abcd").expect("upload once the error is cleared");
|
||||
assert_eq!(ctx.buffer_len(handle), Ok(4));
|
||||
// another error stops it for good
|
||||
opened.health.mark(Fault::Error("Validation Error".into()));
|
||||
assert_eq!(ctx.upload_buffer("validation", b"x"), Err(GpuFault::Operation("Validation Error".into())));
|
||||
assert_eq!(ctx.device_status(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_waiting_when_the_device_reports_an_error_fails_instead_of_polling_forever() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("request_read");
|
||||
opened.health.mark(Fault::Error("Validation Error".into()));
|
||||
assert_eq!(ctx.wait_between_reads(request), Some(GpuFault::Operation("Validation Error".into())));
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.iter().all(|p| p.request != request), "the failed read is dropped");
|
||||
// a loss is left to poll_reads, which fails every pending read with it
|
||||
let other = ctx.request_read(handle);
|
||||
assert!(other.is_err());
|
||||
opened.health.mark(Fault::Lost("gone".into()));
|
||||
assert_eq!(ctx.wait_between_reads(request), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiting_for_a_read_does_not_submit_more_queue_work() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
opened.queue.submit([]);
|
||||
|
||||
let probe = craft_gpu_device::open(&noop(), None, &Preference::Software, &Request::default()).expect("the noop adapter opens");
|
||||
// The probe supplies an index just beyond this device's submitted work.
|
||||
let next_index = loop {
|
||||
let index = probe.queue.submit([]);
|
||||
match opened.device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(std::time::Duration::ZERO) }) {
|
||||
Err(wgpu::PollError::WrongSubmissionIndex(..)) => break index,
|
||||
Ok(_) => {}
|
||||
Err(err) => panic!("unexpected poll error: {err}"),
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(ctx.wait_between_reads(request), None);
|
||||
// An extra submission would make the probe index valid.
|
||||
assert!(matches!(
|
||||
opened.device.poll(wgpu::PollType::Wait { submission_index: Some(next_index), timeout: Some(std::time::Duration::ZERO) }),
|
||||
Err(wgpu::PollError::WrongSubmissionIndex(..))
|
||||
));
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
assert_eq!(outcomes[0].result, Ok(b"abcd".to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_waits_for_its_copy_after_out_of_memory() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
opened.health.mark(Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()));
|
||||
|
||||
assert_eq!(ctx.wait_between_reads(request), None);
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
let pending = d.pending.iter().find(|p| p.request == request).expect("pending read");
|
||||
assert!(matches!(*pending.state.lock().expect("map state"), Some(Ok(()))), "the wait completes the map despite out of memory");
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
assert_eq!(outcomes[0].result, Ok(b"abcd".to_vec()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_read_submission_detects_loss_before_callback_delivery() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
let rejected = opened.queue.submit([]);
|
||||
let Backing::Device(d) = &mut ctx.backing else { panic!("a device backing") };
|
||||
d.pending.iter_mut().find(|p| p.request == request).expect("pending read").submission = rejected;
|
||||
|
||||
assert_eq!(ctx.wait_between_reads(request), None);
|
||||
assert!(opened.health.device_lost());
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.iter().any(|p| p.request == request));
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
assert!(matches!(outcomes[0].result, Err(GpuFault::DeviceLost(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_waiting_with_out_of_memory_and_a_validation_error_fails_with_the_validation_error() {
|
||||
for oom_first in [true, false] {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("request_read");
|
||||
let faults = [Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()), Fault::Error("Validation Error".into())];
|
||||
for index in if oom_first { [0, 1] } else { [1, 0] } {
|
||||
opened.health.mark(faults[index].clone());
|
||||
}
|
||||
assert_eq!(ctx.wait_between_reads(request), Some(GpuFault::Operation("Validation Error".into())));
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.iter().all(|p| p.request != request), "the failed read is dropped");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_staging_context_has_no_health() {
|
||||
let ctx = WgpuContext::with_caps(WorkerKind::Main, craft_gpu::DeviceCaps::default());
|
||||
assert!(ctx.health().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pending_read_fails_when_validation_and_out_of_memory_coexist() {
|
||||
for oom_first in [true, false] {
|
||||
let device = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &device);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
let faults = [Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()), Fault::Error("Validation Error".into())];
|
||||
for index in if oom_first { [0, 1] } else { [1, 0] } {
|
||||
device.health.mark(faults[index].clone());
|
||||
}
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
assert_eq!(outcomes[0].result, Err(GpuFault::Operation("Validation Error".into())));
|
||||
assert!(ctx.poll_reads().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polling_pending_reads_prefers_loss_before_callback_delivery() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let first = ctx.request_read(handle).expect("first read");
|
||||
let second = ctx.request_read(handle).expect("second read");
|
||||
opened.health.mark(Fault::Error("Validation Error".into()));
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 2);
|
||||
assert!(outcomes.iter().any(|outcome| outcome.request == first));
|
||||
assert!(outcomes.iter().any(|outcome| outcome.request == second));
|
||||
for outcome in outcomes {
|
||||
assert_eq!(outcome.handle, handle);
|
||||
assert!(matches!(outcome.result, Err(GpuFault::DeviceLost(_))));
|
||||
}
|
||||
assert!(opened.health.device_lost());
|
||||
assert!(ctx.poll_reads().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_errors_prefer_loss_before_callback_delivery() {
|
||||
for operation in 0..4 {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
let Backing::Device(d) = &mut ctx.backing else { panic!("a device backing") };
|
||||
d.pending[0].state = std::sync::Arc::new(std::sync::Mutex::new(Some(Err("mapping failed".into()))));
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
|
||||
let result = match operation {
|
||||
0 => {
|
||||
ctx.caps.max_buffer_size = 0;
|
||||
ctx.upload_buffer("oversized", b"abcd").map(|_| ())
|
||||
}
|
||||
1 => ctx.buffer_len(craft_gpu::HandleId(u32::MAX)).map(|_| ()),
|
||||
2 => ctx.request_read(craft_gpu::HandleId(u32::MAX)).map(|_| ()),
|
||||
_ => {
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 1);
|
||||
assert_eq!(outcomes[0].request, request);
|
||||
outcomes.into_iter().next().expect("read outcome").result.map(|_| ())
|
||||
}
|
||||
};
|
||||
if operation == 1 {
|
||||
assert_eq!(result, Err(GpuFault::InvalidJob("bad handle".into())));
|
||||
assert!(!opened.health.device_lost());
|
||||
} else {
|
||||
assert!(matches!(result, Err(GpuFault::DeviceLost(_))), "{result:?}");
|
||||
assert!(opened.health.device_lost());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_error_revealing_loss_completes_all_pending_reads_once() {
|
||||
let opened = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &opened);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let first = ctx.request_read(handle).expect("first read");
|
||||
let second = ctx.request_read(handle).expect("second read");
|
||||
let third = ctx.request_read(handle).expect("third read");
|
||||
let Backing::Device(d) = &mut ctx.backing else { panic!("a device backing") };
|
||||
for pending in &mut d.pending {
|
||||
pending.state = std::sync::Arc::new(std::sync::Mutex::new(None));
|
||||
}
|
||||
*d.pending[1].state.lock().expect("map state") = Some(Err("mapping failed".into()));
|
||||
opened.device.set_device_lost_callback(|_, _| {});
|
||||
opened.device.destroy();
|
||||
assert_eq!(opened.health.device_status(), Ok(()));
|
||||
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 3);
|
||||
let loss = opened.health.device_status().expect_err("device loss");
|
||||
assert!(matches!(loss, GpuFault::DeviceLost(_)));
|
||||
for request in [first, second, third] {
|
||||
let outcome = outcomes.iter().find(|outcome| outcome.request == request).expect("read outcome");
|
||||
assert_eq!(outcome.handle, handle);
|
||||
assert_eq!(outcome.result, Err(loss.clone()));
|
||||
}
|
||||
let Backing::Device(d) = &ctx.backing else { panic!("a device backing") };
|
||||
assert!(d.pending.is_empty());
|
||||
assert!(ctx.poll_reads().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polling_faults_complete_all_pending_reads_once() {
|
||||
let device = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &device);
|
||||
let handle = ctx.upload_buffer("pending", b"abcd").expect("upload");
|
||||
let first = ctx.request_read(handle).expect("first read");
|
||||
let second = ctx.request_read(handle).expect("second read");
|
||||
device.health.mark(Fault::Error("Validation Error".into()));
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert_eq!(outcomes.len(), 2);
|
||||
assert!(outcomes.iter().any(|outcome| outcome.request == first));
|
||||
assert!(outcomes.iter().any(|outcome| outcome.request == second));
|
||||
for outcome in outcomes {
|
||||
assert_eq!(outcome.handle, handle);
|
||||
assert_eq!(outcome.result, Err(GpuFault::Operation("Validation Error".into())));
|
||||
}
|
||||
assert!(ctx.poll_reads().is_empty(), "failed requests complete only once");
|
||||
|
||||
let device = opened();
|
||||
let mut ctx = WgpuContext::from_opened(WorkerKind::Main, &device);
|
||||
let handle = ctx.upload_buffer("oom", b"abcd").expect("upload");
|
||||
let request = ctx.request_read(handle).expect("read");
|
||||
device.health.mark(Fault::Error(craft_gpu_device::OUT_OF_MEMORY.into()));
|
||||
let outcomes = ctx.poll_reads();
|
||||
assert!(outcomes.iter().all(|outcome| outcome.request == request && outcome.result.is_ok()));
|
||||
let Backing::Device(backing) = &ctx.backing else { panic!("device backing") };
|
||||
assert_eq!(outcomes.len() + backing.pending.len(), 1, "out of memory does not discard or fail the read");
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ icu_datetime = { version = "~2.3", default-features = false, features = ["serde"
|
||||
icu_time = { version = "~2.3", default-features = false }
|
||||
icu_provider = { version = "~2.3", default-features = false, features = ["sync"] }
|
||||
icu_provider_adapters = { version = "~2.3", default-features = false }
|
||||
icu_provider_blob = { version = "~2.3", default-features = false }
|
||||
icu_provider_blob = { version = "~2.3", default-features = false, features = ["alloc"] }
|
||||
writeable = "0.6"
|
||||
log = "0.4"
|
||||
sys-locale = "0.3"
|
||||
@@ -34,10 +34,17 @@ icu_collator = { version = "~2.3.1", default-features = false, features = ["serd
|
||||
unicode-bidi = "0.3"
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
brotli-decompressor = { version = "6", default-features = false, features = ["std"] }
|
||||
sys-locale = { version = "0.3", features = ["js"] }
|
||||
# The browser's `Date` supplies the local offset.
|
||||
chrono = { workspace = true, features = ["clock", "wasmbind"] }
|
||||
|
||||
[build-dependencies]
|
||||
brotli = { version = "9", default-features = false, features = ["std"] }
|
||||
|
||||
[dev-dependencies]
|
||||
brotli-decompressor = { version = "6", default-features = false, features = ["std"] }
|
||||
|
||||
# The regional format (Region::system); safe registry reads, MIT OR Apache-2.0.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-registry = "0.6"
|
||||
|
||||
@@ -123,11 +123,13 @@ The app keeps its `tl!` macro, its language setting (`"auto"` → `I18N.system_l
|
||||
(`1.234 Dateien`, `١٬٢٣٤ ملفًا`); for names written into documents or files (`Copy 1234`), use
|
||||
`trn_plain`, which writes `0`–`9` without grouping or isolate marks.
|
||||
- **CLDR data:** decimal symbols, digits and plural rules (`data/numbers.postcard`, about 10 KB),
|
||||
percent patterns (`data/locales.rs`) and date data (`data/dates.postcard`, about 340 KB) cover
|
||||
percent patterns (`data/locales.rs`) and date data (`data/dates.postcard`, about 430 KB) cover
|
||||
every CLDR locale; `data/generate.sh` rebuilds all three from CLDR 48.2.1. The ICU4X crates are
|
||||
pinned to one minor version (`~2.3`), the one the data is generated for. The ICU4X code and the
|
||||
number data add about 90 KB to a stripped release build and 80 KB to wasm; the date data is
|
||||
extra.
|
||||
pinned to one minor version (`~2.3`), the one the data is generated for. Native builds embed the
|
||||
static provider blobs. Browser builds embed lossless Brotli copies and restore each provider
|
||||
once on first use, preserving every locale and rule. The build writes packed copies only to
|
||||
`OUT_DIR`; the checked-in source data and its generation commands are unchanged. Tests compare
|
||||
every decoded byte with the source blobs and load the result as an owned ICU provider.
|
||||
- **Dates:** `DateFormat` (`I18n::dates`, `set_dates`, `reset_dates`, as `I18n::format` is for
|
||||
numbers) writes dates and times for the region's time locale and clock in the `Short`, `Medium`,
|
||||
`Long` and `Full` lengths, month and weekday names (`NameLength`), the first day of the week and
|
||||
@@ -165,4 +167,5 @@ The app keeps its `tl!` macro, its language setting (`"auto"` → `I18N.system_l
|
||||
- **Sorting** (`Collator`, feature `collate`): ICU4X collation for the locales craft-i18n ships,
|
||||
Persian and Hindi, with digits compared by value (`Layer 2` before `Layer 10`) and `-u-co-pinyin`
|
||||
/ `-u-co-stroke` for Chinese. The data (754 KB) is regenerated by `data/generate-collation.sh`;
|
||||
the feature adds about 1 MB to a release binary or wasm module (320 KB gzipped).
|
||||
native builds embed it directly, while browser builds use the same lossless packing as the
|
||||
number and date providers.
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Pack the existing locale data losslessly for browser builds; native providers stay static.
|
||||
|
||||
use std::io::Write as _;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = pack() {
|
||||
println!("cargo::error=packing locale data: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn pack() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let out = PathBuf::from(std::env::var_os("OUT_DIR").ok_or("OUT_DIR is missing")?);
|
||||
let mut declarations = String::new();
|
||||
for name in ["numbers", "dates", "collation"] {
|
||||
let input = format!("data/{name}.postcard");
|
||||
println!("cargo::rerun-if-changed={input}");
|
||||
let bytes = std::fs::read(&input)?;
|
||||
if bytes.is_empty() || bytes.len() > 2 * 1024 * 1024 {
|
||||
return Err(format!("{input} is outside the browser locale-data size budget").into());
|
||||
}
|
||||
let mut compressed = Vec::new();
|
||||
{
|
||||
let mut encoder = brotli::CompressorWriter::new(&mut compressed, 4096, 11, 22);
|
||||
encoder.write_all(&bytes)?;
|
||||
}
|
||||
std::fs::write(out.join(format!("{name}.br")), compressed)?;
|
||||
if name == "collation" {
|
||||
declarations.push_str("#[cfg(any(test, feature = \"collate\"))]\n");
|
||||
}
|
||||
declarations.push_str(&format!(
|
||||
"const {}: (&[u8], usize) = (include_bytes!(concat!(env!(\"OUT_DIR\"), \"/{name}.br\")), {});\n",
|
||||
name.to_ascii_uppercase(),
|
||||
bytes.len()
|
||||
));
|
||||
}
|
||||
std::fs::write(out.join("locale_blobs.rs"), declarations)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Preserve every locale byte while avoiding raw provider blobs in browser binaries.
|
||||
|
||||
use icu_provider::DataError;
|
||||
use icu_provider_blob::BlobDataProvider;
|
||||
|
||||
#[cfg(any(test, target_arch = "wasm32"))]
|
||||
include!(concat!(env!("OUT_DIR"), "/locale_blobs.rs"));
|
||||
|
||||
pub(crate) fn numbers() -> Result<BlobDataProvider, DataError> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
owned(NUMBERS)
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/numbers.postcard"))
|
||||
}
|
||||
|
||||
pub(crate) fn dates() -> Result<BlobDataProvider, DataError> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
owned(DATES)
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/dates.postcard"))
|
||||
}
|
||||
|
||||
#[cfg(feature = "collate")]
|
||||
pub(crate) fn collation() -> Result<BlobDataProvider, DataError> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
owned(COLLATION)
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/collation.postcard"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn owned((bytes, len): (&[u8], usize)) -> Result<BlobDataProvider, DataError> {
|
||||
let bytes = unpack(bytes, len).ok_or_else(|| DataError::custom("Invalid compressed locale data"))?;
|
||||
BlobDataProvider::try_new_from_blob(bytes.into_boxed_slice())
|
||||
}
|
||||
|
||||
#[cfg(any(test, target_arch = "wasm32"))]
|
||||
fn unpack(bytes: &[u8], len: usize) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
// Generated blobs are currently below 1 MiB. Bound allocation and decoding even for corrupt metadata.
|
||||
if len == 0 || len > 2 * 1024 * 1024 {
|
||||
return None;
|
||||
}
|
||||
let mut decoded = Vec::new();
|
||||
decoded.try_reserve_exact(len).ok()?;
|
||||
brotli_decompressor::Decompressor::new(bytes, 4096).take(len as u64 + 1).read_to_end(&mut decoded).ok()?;
|
||||
(decoded.len() == len).then_some(decoded)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn packed_catalogs_preserve_every_locale_byte_and_load_as_owned_providers() {
|
||||
for (packed, original) in [
|
||||
(NUMBERS, include_bytes!("../data/numbers.postcard").as_slice()),
|
||||
(DATES, include_bytes!("../data/dates.postcard").as_slice()),
|
||||
(COLLATION, include_bytes!("../data/collation.postcard").as_slice()),
|
||||
] {
|
||||
let decoded = unpack(packed.0, packed.1).unwrap();
|
||||
assert_eq!(decoded, original);
|
||||
assert!(packed.0.len() < original.len());
|
||||
BlobDataProvider::try_new_from_blob(decoded.into_boxed_slice()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_or_wrong_sized_catalogs_are_unavailable() {
|
||||
assert!(unpack(b"not compressed locale data", NUMBERS.1).is_none());
|
||||
assert!(unpack(&NUMBERS.0[..NUMBERS.0.len() / 2], NUMBERS.1).is_none());
|
||||
for len in [0, NUMBERS.1 - 1, NUMBERS.1 + 1, usize::MAX] {
|
||||
assert!(unpack(NUMBERS.0, len).is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,9 +34,9 @@ impl Collator {
|
||||
let mut prefs: CollatorPreferences = Locale::try_from_str(&bcp47(locale)).unwrap_or(Locale::UNKNOWN).into();
|
||||
prefs.numeric_ordering = Some(CollationNumericOrdering::True);
|
||||
let options = CollatorOptions::default();
|
||||
let collator = Data::new().ok().and_then(|data| {
|
||||
icu_collator::Collator::try_new_unstable(&data, prefs, options)
|
||||
.or_else(|_| icu_collator::Collator::try_new_unstable(&data, CollatorPreferences::default(), options))
|
||||
let collator = Data::shared().as_ref().ok().and_then(|data| {
|
||||
icu_collator::Collator::try_new_unstable(data, prefs, options)
|
||||
.or_else(|_| icu_collator::Collator::try_new_unstable(data, CollatorPreferences::default(), options))
|
||||
.ok()
|
||||
});
|
||||
Collator(collator)
|
||||
@@ -83,8 +83,13 @@ fn bcp47(locale: &str) -> String {
|
||||
struct Data(LocaleFallbackProvider<BlobDataProvider>);
|
||||
|
||||
impl Data {
|
||||
fn shared() -> &'static Result<Data, DataError> {
|
||||
static DATA: std::sync::OnceLock<Result<Data, DataError>> = std::sync::OnceLock::new();
|
||||
DATA.get_or_init(Self::new)
|
||||
}
|
||||
|
||||
fn new() -> Result<Data, DataError> {
|
||||
let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/collation.postcard"))?;
|
||||
let blob = crate::blob::collation()?;
|
||||
Ok(Data(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned())))
|
||||
}
|
||||
}
|
||||
|
||||
+23
-3
@@ -226,6 +226,19 @@ fn prefix_links(n: &[u8]) -> Vec<usize> {
|
||||
links
|
||||
}
|
||||
|
||||
// Each step of `Folded::matches` through the haystack on this thread: one per byte read and one
|
||||
// per failure link followed.
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
static SEARCH_STEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn count_search_step() {
|
||||
#[cfg(test)]
|
||||
SEARCH_STEPS.with(|steps| steps.set(steps.get().saturating_add(1)));
|
||||
}
|
||||
|
||||
/// Folded text and where each part came from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Folded {
|
||||
@@ -296,7 +309,9 @@ impl Folded {
|
||||
return Some(0..0);
|
||||
}
|
||||
while let Some(&b) = hay.get(at) {
|
||||
count_search_step();
|
||||
while k > 0 && n[k] != b {
|
||||
count_search_step();
|
||||
k = links[k - 1];
|
||||
}
|
||||
if n[k] == b {
|
||||
@@ -330,10 +345,15 @@ mod tests {
|
||||
let haystack = format!("{}a", "a\u{301}".repeat(100_000));
|
||||
let needle = format!("{}a", "a\u{301}".repeat(50_000));
|
||||
let folded = f.fold(&haystack);
|
||||
let start = std::time::Instant::now();
|
||||
let found = folded.find(&f.fold(&needle));
|
||||
let folded_needle = f.fold(&needle);
|
||||
SEARCH_STEPS.with(|steps| steps.set(0));
|
||||
let found = folded.find(&folded_needle);
|
||||
assert_eq!(found, Some(haystack.len() - needle.len()..haystack.len()));
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
// One pass reads each haystack byte once and follows at most as many links as it read
|
||||
// bytes; searching again from each turned-down occurrence rereads the needle each time.
|
||||
let steps = SEARCH_STEPS.with(std::cell::Cell::get);
|
||||
let bound = 2 * folded.as_str().len();
|
||||
assert!(steps <= bound, "{steps} search steps for a {}-byte haystack", folded.as_str().len());
|
||||
}
|
||||
#[test]
|
||||
fn source_ranges_round_trip() {
|
||||
|
||||
@@ -38,6 +38,8 @@ pub use bidi::{file_name, isolate, ltr, path, strip_isolates};
|
||||
pub use message::MessageMatch;
|
||||
use message::{KEPT_VALUE, MAX_MESSAGE_LEN, MESSAGE_DEPTH, Template, insert_template, sort_templates};
|
||||
|
||||
mod blob;
|
||||
|
||||
/// The CLDR number, plural and date data for every CLDR locale, from `data/generate.sh`.
|
||||
mod data {
|
||||
use std::sync::OnceLock;
|
||||
@@ -53,7 +55,7 @@ mod data {
|
||||
static PROVIDER: OnceLock<Option<LocaleFallbackProvider<BlobDataProvider>>> = OnceLock::new();
|
||||
PROVIDER
|
||||
.get_or_init(|| {
|
||||
let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/numbers.postcard")).ok()?;
|
||||
let blob = crate::blob::numbers().ok()?;
|
||||
Some(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned()))
|
||||
})
|
||||
.as_ref()
|
||||
@@ -65,7 +67,7 @@ mod data {
|
||||
static PROVIDER: OnceLock<Option<LocaleFallbackProvider<BlobDataProvider>>> = OnceLock::new();
|
||||
PROVIDER
|
||||
.get_or_init(|| {
|
||||
let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/dates.postcard")).ok()?;
|
||||
let blob = crate::blob::dates().ok()?;
|
||||
Some(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned()))
|
||||
})
|
||||
.as_ref()
|
||||
|
||||
@@ -12,7 +12,26 @@ workspace = true
|
||||
|
||||
[features]
|
||||
corpus = []
|
||||
default = []
|
||||
# Every codec below is on by default; a build that never reads or writes a format can turn
|
||||
# `default-features` off and list the ones it needs. A format left out is still detected, and
|
||||
# reading or writing it returns `CodecError::Unsupported` naming the feature.
|
||||
default = ["dds", "dicom", "dpx", "exr", "fits", "iff", "jp2", "jpegls", "jxl-encode", "pnm", "tga", "tiff", "webp", "xpm"]
|
||||
dds = []
|
||||
dicom = []
|
||||
# DPX and Cineon.
|
||||
dpx = []
|
||||
# OpenEXR, including deep data, Cryptomatte and the streaming reader.
|
||||
exr = ["dep:exr"]
|
||||
fits = []
|
||||
iff = []
|
||||
jpegls = []
|
||||
# Lossless JPEG XL export (zune-jpegxl). Decode is the separate `jxl` feature.
|
||||
jxl-encode = ["dep:zune-jpegxl"]
|
||||
pnm = []
|
||||
tga = ["image/tga"]
|
||||
tiff = ["image/tiff"]
|
||||
webp = ["dep:image-webp"]
|
||||
xpm = []
|
||||
# Opt in to threaded AVIF encoding without enabling AVIF (or assembly) by itself.
|
||||
threads = ["ravif?/threading", "rav1e?/threading"]
|
||||
sgi = []
|
||||
@@ -28,44 +47,46 @@ avif-decode = ["dep:craft-video", "craft-video/av1-decode"]
|
||||
# `Image::source_profile` and `Image::to_display_rgba8`: convert an image's colors from its ICC
|
||||
# profile or CICP description into a display profile with craft-cms.
|
||||
cms = ["dep:craft-cms"]
|
||||
# JPEG 2000 decode via hayro-jpeg2000; default-on to preserve existing app support.
|
||||
jp2 = ["dep:hayro-jpeg2000"]
|
||||
|
||||
[dependencies]
|
||||
craft-dds = { workspace = true }
|
||||
crc32fast = "1.5"
|
||||
thiserror = { workspace = true }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "gif", "bmp", "tga", "ico", "qoi", "hdr"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "bmp", "ico", "qoi", "hdr"] }
|
||||
png = "0.18"
|
||||
tiff = { version = "0.11", default-features = false, features = ["deflate", "fax", "jpeg", "lzw"] }
|
||||
exr = { version = "1.73", default-features = false }
|
||||
exr = { version = "1.73", default-features = false, optional = true }
|
||||
half = "2"
|
||||
serde_json = { workspace = true }
|
||||
flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] }
|
||||
image-webp = "0.2"
|
||||
image-webp = { version = "0.2", optional = true }
|
||||
zune-jpeg = "0.5"
|
||||
zune-core = "0.5"
|
||||
jpeg-encoder = "0.7.1"
|
||||
craft-jpeg = { workspace = true }
|
||||
craft-metadata = { workspace = true }
|
||||
craft-tiff = { workspace = true, features = ["plain-rgba16"] }
|
||||
zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] }
|
||||
zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"], optional = true }
|
||||
craft-cms = { workspace = true, optional = true }
|
||||
craft-heif = { workspace = true, optional = true }
|
||||
craft-jxl = { workspace = true, optional = true, features = ["decode"] }
|
||||
ravif = { version = "0.13", default-features = false, optional = true }
|
||||
rav1e = { version = "0.8", default-features = false, optional = true }
|
||||
avif-serialize = { version = "0.8", optional = true }
|
||||
hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] }
|
||||
hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"], optional = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# DDS encodes rows of blocks on several threads, as the other parallel codecs here do on native targets.
|
||||
craft-dds = { workspace = true, features = ["parallel"] }
|
||||
rayon = { workspace = true }
|
||||
craft-video = { workspace = true, optional = true }
|
||||
exr = { version = "1.73", default-features = false, features = ["rayon"] }
|
||||
exr = { version = "1.73", default-features = false, features = ["rayon"], optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
|
||||
sha2 = { version = "0.10", default-features = false, features = ["std"] }
|
||||
craft-media-testkit = { workspace = true }
|
||||
|
||||
|
||||
@@ -58,12 +58,52 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "<
|
||||
| Cineon | yes | yes | U16 (10-bit code values read and written exactly through U16) | Gray, RGB | no | no | no | no | no | no | no | built in |
|
||||
| DICOM | yes | **no** | U8, U16 | Gray, RGB | no | no | no | no | no | no | n/a | built in |
|
||||
| Amiga IFF (ILBM/PBM) | yes | yes (24-bit ILBM) | U8 | RGB, RGBA | yes (1-bit mask plane on write) | no | no | no | no | no | no | built in |
|
||||
| JPEG 2000 (`.jp2`, `.j2k`) | with feature `jp2` (default) | **no** | U8 | Gray, GrayA, RGB, RGBA, CMYK | yes | yes | no | no | no | no | no | `hayro-jpeg2000` |
|
||||
| Sun Raster (`.ras`) | with feature `sunraster` (incl. RLE and colour maps) | with feature `sunraster` (uncompressed) | U8 | Gray, RGB, RGBA | yes | no | no | no | no | no | no | `sunraster` (off by default) |
|
||||
| SGI (`.sgi`, `.rgb`, `.bw`) | with feature `sgi` | with feature `sgi` (RLE) | U8, U16 | Gray, Gray+A, RGB, RGBA | yes | no | no | no | no | no | no | `sgi` (off by default) |
|
||||
| JPEG-LS (`.jls`) | yes (any NEAR; one scan per component) | yes (lossless) | U8, U16 | Gray, RGB | no | no | no | no | no | no | no | built in |
|
||||
| AVIF | with feature `avif-decode` (native only) | only with feature `avif` | U8, U16 (10/12-bit decodes to U16; PQ/HLG to linear F32) | RGB, RGBA | yes (auxiliary alpha) | read (`colr` prof/rICC) | read | read | no | no | yes | `craft-video` AV1 decoder; `image` + `ravif` to write |
|
||||
| HEIF/HEIC | with feature `heif` | **no** | U8, U16 (10/12-bit decodes to U16) | RGB, RGBA | yes (auxiliary alpha) | yes (`colr` prof) | yes | yes | no | no | n/a | `heic-rs` |
|
||||
|
||||
### Leaving codecs out
|
||||
|
||||
Each codec below sits behind a Cargo feature that is on by default, preserving the default read
|
||||
and write capabilities shown in the matrix. A build that never handles some formats turns `default-features`
|
||||
off and lists the ones it needs; unused codec backends are removed from optimized builds.
|
||||
TIFF metadata readers and EXIF writing remain available without TIFF pixel support.
|
||||
|
||||
For a minimal build, depend directly on `craft-image-codecs` with `default-features = false`.
|
||||
The `craft` facade's generated codec selectors are additive: its base `image-codecs` feature
|
||||
retains the default codec set for existing facade consumers.
|
||||
|
||||
| Feature | Formats |
|
||||
|---|---|
|
||||
| `dds` | DDS |
|
||||
| `dicom` | DICOM |
|
||||
| `dpx` | DPX, Cineon |
|
||||
| `exr` | OpenEXR, with deep data, Cryptomatte and `exr_stream` (the `exr` dependency) |
|
||||
| `fits` | FITS |
|
||||
| `iff` | Amiga IFF |
|
||||
| `jp2` | JPEG 2000 decode (`hayro-jpeg2000`) |
|
||||
| `jpegls` | JPEG-LS |
|
||||
| `jxl-encode` | JPEG XL export (the `zune-jpegxl` dependency); decode is the separate `jxl` feature |
|
||||
| `pnm` | Netpbm |
|
||||
| `tga` | TGA (the `image` crate's TGA decoder) |
|
||||
| `tiff` | TIFF and BigTIFF pixel decoding and encoding |
|
||||
| `webp` | WebP, with the VP8 encoder (the `image-webp` dependency) |
|
||||
| `xpm` | XPM |
|
||||
|
||||
PNG, JPEG, GIF, BMP, ICO, QOI, Radiance HDR and PCX are always built. A format left
|
||||
out is still detected; reading or writing it returns `CodecError::Unsupported` naming the feature,
|
||||
and its `caps` say it can be neither read nor written. The functions specific to a left-out format
|
||||
(`exr_info`, `decode_webp_frames`, `webp_encoding`, `xpm_named_color_rgb`...) are not compiled in.
|
||||
TIFF is an exception: its metadata APIs and public pixel API types remain available; pixel
|
||||
entry points return the named unsupported-feature error when `tiff` is disabled.
|
||||
|
||||
```toml
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "<commit>", default-features = false, features = ["webp"] }
|
||||
```
|
||||
|
||||
"Native" means the data is stored and read back without conversion. Anything else is converted by
|
||||
the encode plan, and `fidelity_warnings` reports the conversion when it loses information:
|
||||
|
||||
|
||||
@@ -248,6 +248,23 @@ fn read_le24(bytes: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_le_bytes([b[0], b[1], b[2], 0]))
|
||||
}
|
||||
|
||||
fn tiff_stored_size(bytes: &[u8], limits: &crate::Limits) -> Result<(u32, u32), CodecError> {
|
||||
let format = Format::Tiff;
|
||||
// Header inspection remains available without the optional pixel backend.
|
||||
use crate::codecs::tiff_ifd::{Entry, File, TAG_HEIGHT, TAG_WIDTH};
|
||||
let malformed = || CodecError::malformed(format, "invalid first TIFF directory");
|
||||
let file = File::parse(bytes).ok_or_else(malformed)?;
|
||||
let entries = file.entry_count(file.first_ifd).ok_or_else(malformed)?;
|
||||
if entries.saturating_mul(std::mem::size_of::<Entry>() as u64) > limits.max_alloc {
|
||||
return Err(CodecError::LimitExceeded("TIFF directory exceeds max_alloc".into()));
|
||||
}
|
||||
let directory = file.ifd(file.first_ifd).ok_or_else(malformed)?;
|
||||
let side = |tag| file.tag_uint(&directory, tag).and_then(|v| u32::try_from(v).ok()).ok_or_else(malformed);
|
||||
let (width, height) = (side(TAG_WIDTH)?, side(TAG_HEIGHT)?);
|
||||
limits.check_size(width, height)?;
|
||||
Ok((width, height))
|
||||
}
|
||||
|
||||
/// Probe the stored dimensions of the first PNG, JPEG, BMP or TIFF image, without decoding
|
||||
/// pixels or applying orientation. TIFF uses the first directory even if it is a thumbnail.
|
||||
/// The caller's limits bound both the header decoder and the declared output dimensions.
|
||||
@@ -257,6 +274,9 @@ pub fn probe_stored_size(bytes: &[u8], limits: &crate::Limits) -> Result<(u32, u
|
||||
if !matches!(format, Format::Png | Format::Jpeg | Format::Bmp | Format::Tiff) {
|
||||
return Err(CodecError::unsupported(format, "stored-size probe is not available for this format"));
|
||||
}
|
||||
if format == Format::Tiff && !cfg!(feature = "tiff") {
|
||||
return tiff_stored_size(bytes, limits);
|
||||
}
|
||||
// The JPEG header reader owns a copy of its input before applying image limits.
|
||||
if format == Format::Jpeg && u64::try_from(bytes.len()).map_or(true, |len| len > limits.max_alloc) {
|
||||
return Err(CodecError::malformed(format, "JPEG input exceeds the allocation budget"));
|
||||
@@ -322,8 +342,27 @@ mod stored_size_tests {
|
||||
let limits = crate::Limits::new(100, 100, 10_000, 1 << 20);
|
||||
for format in [image::ImageFormat::Png, image::ImageFormat::Jpeg, image::ImageFormat::Bmp, image::ImageFormat::Tiff] {
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
image::write_buffer_with_format(&mut out, &[10; 18], 3, 2, image::ExtendedColorType::Rgb8, format).unwrap();
|
||||
if format == image::ImageFormat::Tiff {
|
||||
tiff::encoder::TiffEncoder::new(&mut out).unwrap().write_image::<tiff::encoder::colortype::RGB8>(3, 2, &[10; 18]).unwrap();
|
||||
} else {
|
||||
image::write_buffer_with_format(&mut out, &[10; 18], 3, 2, image::ExtendedColorType::Rgb8, format).unwrap();
|
||||
}
|
||||
assert_eq!(probe_stored_size(&out.into_inner(), &limits).unwrap(), (3, 2), "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiff_header_probe_keeps_dimensions_and_allocation_bounded_without_pixels() {
|
||||
let bytes = craft_tiff::plain::encode_rgba16(2, 3, &[0; 24]).unwrap();
|
||||
assert_eq!(tiff_stored_size(&bytes, &crate::Limits::default()).unwrap(), (2, 3));
|
||||
for limits in [
|
||||
crate::Limits { max_width: 1, ..crate::Limits::default() },
|
||||
crate::Limits { max_height: 2, ..crate::Limits::default() },
|
||||
crate::Limits { max_pixels: 5, ..crate::Limits::default() },
|
||||
crate::Limits { max_alloc: 1, ..crate::Limits::default() },
|
||||
] {
|
||||
assert!(matches!(tiff_stored_size(&bytes, &limits), Err(CodecError::LimitExceeded(_))));
|
||||
}
|
||||
assert!(tiff_stored_size(&bytes[..8], &crate::Limits::default()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -2,33 +2,48 @@ pub(crate) mod avif;
|
||||
#[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))]
|
||||
pub(crate) mod avif_decode;
|
||||
pub(crate) mod bmp;
|
||||
#[cfg(feature = "dds")]
|
||||
pub(crate) mod dds;
|
||||
#[cfg(feature = "exr")]
|
||||
pub(crate) mod deep_exr;
|
||||
#[cfg(feature = "dicom")]
|
||||
pub(crate) mod dicom;
|
||||
#[cfg(feature = "dpx")]
|
||||
pub(crate) mod dpx;
|
||||
#[cfg(feature = "exr")]
|
||||
pub(crate) mod exr;
|
||||
#[cfg(feature = "exr")]
|
||||
pub(crate) mod exr_cryptomatte;
|
||||
#[cfg(feature = "fits")]
|
||||
pub(crate) mod fits;
|
||||
pub(crate) mod gif_frames;
|
||||
pub(crate) mod gif_palette;
|
||||
pub(crate) mod heif;
|
||||
#[cfg(feature = "iff")]
|
||||
pub(crate) mod iff;
|
||||
#[cfg(feature = "jp2")]
|
||||
pub(crate) mod jp2;
|
||||
pub(crate) mod jpeg;
|
||||
#[cfg(feature = "jpegls")]
|
||||
pub(crate) mod jpegls;
|
||||
pub(crate) mod jxl;
|
||||
pub(crate) mod pcx;
|
||||
pub(crate) mod png;
|
||||
#[cfg(feature = "pnm")]
|
||||
pub(crate) mod pnm;
|
||||
#[cfg(feature = "sgi")]
|
||||
pub(crate) mod sgi;
|
||||
#[cfg(feature = "sunraster")]
|
||||
pub(crate) mod sunraster;
|
||||
#[cfg(feature = "tga")]
|
||||
pub(crate) mod tga;
|
||||
pub(crate) mod tiff;
|
||||
pub(crate) mod tiff_exif;
|
||||
pub(crate) mod tiff_ifd;
|
||||
pub(crate) mod via_image;
|
||||
#[cfg(feature = "webp")]
|
||||
pub(crate) mod vp8;
|
||||
#[cfg(feature = "webp")]
|
||||
pub(crate) mod webp;
|
||||
#[cfg(feature = "xpm")]
|
||||
pub(crate) mod xpm;
|
||||
@@ -9,7 +9,7 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::error::CodecError;
|
||||
use crate::format::Format;
|
||||
use crate::format::{Format, is_dicom};
|
||||
use crate::image::{ChannelLayout, Image, SampleType};
|
||||
use crate::options::Limits;
|
||||
|
||||
@@ -21,11 +21,6 @@ fn bad(msg: impl std::fmt::Display) -> CodecError {
|
||||
CodecError::malformed(F, msg)
|
||||
}
|
||||
|
||||
/// A DICOM file begins with a 128-byte preamble and the `DICM` magic.
|
||||
pub(crate) fn is_dicom(b: &[u8]) -> bool {
|
||||
b.get(128..132) == Some(b"DICM")
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Endian {
|
||||
big: bool,
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
use crate::Format;
|
||||
use crate::error::CodecError;
|
||||
use crate::fidelity::Plan;
|
||||
use crate::format::is_cineon;
|
||||
use crate::image::{ChannelLayout, DecodeWarning, Image, SampleType};
|
||||
use crate::options::{DpxBits, EncodeOptions, Limits};
|
||||
|
||||
@@ -357,11 +358,6 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
|
||||
// 10-bit samples packed into each 32-bit word, lines on a word boundary — the same layout as
|
||||
// DPX's 10-bit packing method A, so the unpacking and packing are shared.
|
||||
|
||||
/// The Cineon magic number (`802A5FD7` hex), big-endian.
|
||||
pub(crate) fn is_cineon(b: &[u8]) -> bool {
|
||||
b.get(..4) == Some(&[0x80, 0x2A, 0x5F, 0xD7])
|
||||
}
|
||||
|
||||
/// The EXIF orientation (1–8) for a Cineon header's orientation code (the same 0–7 order as DPX).
|
||||
pub(crate) fn cineon_orientation(b: &[u8]) -> u16 {
|
||||
let Some(code) = b.get(192).copied() else { return 1 };
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
use crate::error::CodecError;
|
||||
use crate::fidelity::Plan;
|
||||
use crate::format::Format;
|
||||
use crate::format::{Format, looks_like_iff};
|
||||
use crate::image::{ChannelLayout, Image, SampleType};
|
||||
use crate::options::Limits;
|
||||
|
||||
@@ -37,11 +37,6 @@ fn be16(b: &[u8], at: usize) -> Option<u16> {
|
||||
Some(u16::from_be_bytes(s))
|
||||
}
|
||||
|
||||
/// `FORM` + a bitmap type (`ILBM` interleaved, `PBM ` chunky) at offset 8.
|
||||
pub(crate) fn looks_like_iff(b: &[u8]) -> bool {
|
||||
b.get(0..4) == Some(b"FORM") && matches!(b.get(8..12), Some(b"ILBM" | b"PBM "))
|
||||
}
|
||||
|
||||
/// Bitplanes of a "deep" ILBM: red, green and blue, 8 each, least significant bit first.
|
||||
const DEEP_PLANES: u8 = 24;
|
||||
|
||||
|
||||
@@ -11,12 +11,11 @@
|
||||
|
||||
use crate::error::CodecError;
|
||||
use crate::fidelity::Plan;
|
||||
use crate::format::Format;
|
||||
use crate::format::{Format, SOF55, looks_like_jpegls};
|
||||
use crate::image::{ChannelLayout, Image, SampleType};
|
||||
use crate::options::Limits;
|
||||
|
||||
const F: Format = Format::JpegLs;
|
||||
const SOF55: u8 = 0xF7;
|
||||
const LSE: u8 = 0xF8;
|
||||
const RESET_DEFAULT: i32 = 64;
|
||||
const MIN_C: i32 = -128;
|
||||
@@ -32,67 +31,6 @@ fn bad(reason: impl std::fmt::Display) -> CodecError {
|
||||
CodecError::malformed(F, reason)
|
||||
}
|
||||
|
||||
/// What the marker segments after a JPEG SOI lead to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum JpegFrame {
|
||||
/// An SOF55 frame header: JPEG-LS.
|
||||
Ls,
|
||||
/// Another frame header, a scan header, an EOI, or a byte that is not a marker where one
|
||||
/// should be.
|
||||
Other,
|
||||
/// The bytes end before a frame or scan header. The next step reads the bytes up to this
|
||||
/// length.
|
||||
Short(usize),
|
||||
}
|
||||
|
||||
/// Walks the marker segments of `b` from its SOI up to the first frame or scan header. `None`
|
||||
/// when `b` does not start with an SOI. Each step moves forward at least one byte, so the walk
|
||||
/// takes at most `b.len()` steps and reaches the frame header after any number of segments.
|
||||
pub(crate) fn jpeg_frame(b: &[u8]) -> Option<JpegFrame> {
|
||||
jpeg_frame_from(b, &mut 0)
|
||||
}
|
||||
|
||||
/// [`jpeg_frame`], started at `*pos`. A `*pos` of 0 starts at the SOI. Any other value is the
|
||||
/// offset of the marker where an earlier walk of a shorter prefix of the same file stopped, and the
|
||||
/// walk does not read the bytes before it. The walk leaves `*pos` at the marker it stopped at, so
|
||||
/// walking longer and longer prefixes of one file this way reads each marker segment once.
|
||||
pub(crate) fn jpeg_frame_from(b: &[u8], pos: &mut usize) -> Option<JpegFrame> {
|
||||
if *pos == 0 {
|
||||
if !b.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
*pos = 2;
|
||||
}
|
||||
loop {
|
||||
let (Some(&prefix), Some(&marker)) = (b.get(*pos), b.get(*pos + 1)) else {
|
||||
return Some(if b.get(*pos).is_none_or(|&p| p == 0xFF) { JpegFrame::Short(*pos + 2) } else { JpegFrame::Other });
|
||||
};
|
||||
if prefix != 0xFF {
|
||||
return Some(JpegFrame::Other);
|
||||
}
|
||||
match marker {
|
||||
SOF55 => return Some(JpegFrame::Ls),
|
||||
// `FF 00` is a stuffed zero, not a marker.
|
||||
0x00 | 0xDA | 0xD9 => return Some(JpegFrame::Other),
|
||||
// A DRI segment (`0xDD`) may precede an SOF55 frame header, so it takes the
|
||||
// length-prefixed path below.
|
||||
0xC0..=0xCF | 0xDB | 0xDC | 0xDE | 0xDF => return Some(JpegFrame::Other),
|
||||
0x01 | 0xD0..=0xD7 | 0xFF => *pos += if marker == 0xFF { 1 } else { 2 },
|
||||
_ => {
|
||||
let Some(len) = b.get(*pos + 2..*pos + 4).map(|l| usize::from(u16::from_be_bytes([l[0], l[1]]))) else {
|
||||
return Some(JpegFrame::Short(*pos + 4));
|
||||
};
|
||||
*pos += 2 + len;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `b` is a JPEG-LS file: an SOI followed by marker segments up to an SOF55 frame header.
|
||||
pub(crate) fn looks_like_jpegls(b: &[u8]) -> bool {
|
||||
jpeg_frame(b) == Some(JpegFrame::Ls)
|
||||
}
|
||||
|
||||
/// The coding parameters of one scan, derived as T.87 section C.2 specifies.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Params {
|
||||
@@ -814,6 +752,7 @@ fn finish(frame: Option<Frame>, planes: Vec<Vec<u16>>, scans: usize) -> Result<I
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::format::{JpegFrame, jpeg_frame, jpeg_frame_from};
|
||||
|
||||
fn noise_u16(n: usize, seed: &mut u32, mask: u32) -> Vec<u16> {
|
||||
(0..n)
|
||||
|
||||
@@ -5,15 +5,21 @@
|
||||
//! Gray+alpha sources are expanded losslessly to RGBA by the export plan.
|
||||
//! The flat export pipeline converts tagged RGB documents to sRGB first.
|
||||
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
use zune_core::{bit_depth::BitDepth, colorspace::ColorSpace, options::EncoderOptions as ZuneOptions};
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
use zune_jpegxl::JxlSimpleEncoder;
|
||||
|
||||
use crate::error::CodecError;
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
use crate::fidelity::Plan;
|
||||
use crate::format::Format;
|
||||
use crate::image::{ChannelLayout, Image, SampleType};
|
||||
use crate::image::Image;
|
||||
#[cfg(any(feature = "jxl", feature = "jxl-encode"))]
|
||||
use crate::image::{ChannelLayout, SampleType};
|
||||
|
||||
const F: Format = Format::Jxl;
|
||||
|
||||
@@ -26,6 +32,7 @@ const F: Format = Format::Jxl;
|
||||
// This deliberately verifies the pinned encoder's header layout rather than
|
||||
// trying to parse or rewrite arbitrary JPEG XL codestreams. A different header
|
||||
// must fail closed, not produce a file that silently corrupts transparency.
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
fn correct_16_bit_alpha_header(bytes: &[u8], width: u32, height: u32) -> Result<Vec<u8>, CodecError> {
|
||||
fn read(bytes: &[u8], pos: &mut usize, count: usize) -> Option<u32> {
|
||||
let mut value = 0u32;
|
||||
@@ -113,6 +120,7 @@ fn correct_16_bit_alpha_header(bytes: &[u8], width: u32, height: u32) -> Result<
|
||||
Ok(fixed)
|
||||
}
|
||||
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
pub(crate) fn encode(image: &Image, plan: Plan) -> Result<Vec<u8>, CodecError> {
|
||||
let image = image.converted(plan.layout, plan.sample);
|
||||
let space = match image.layout() {
|
||||
@@ -225,7 +233,7 @@ fn unpremultiply(pixels: &mut [f32], layout: ChannelLayout) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, feature = "jxl-encode"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
|
||||
@@ -259,6 +259,9 @@ use PhotometricInterpretation as PI;
|
||||
|
||||
/// Encode plain classic RGBA16 TIFF for callers that need the legacy file layout.
|
||||
pub fn encode_plain_rgba16(width: u32, height: u32, samples: &[u16]) -> Result<Vec<u8>, CodecError> {
|
||||
if !cfg!(feature = "tiff") {
|
||||
return Err(CodecError::feature_missing(F, "tiff"));
|
||||
}
|
||||
craft_tiff::plain::encode_rgba16(width, height, samples).map_err(|error| CodecError::encode(F, error))
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32, u16), Co
|
||||
/// carries the page's metadata, a [`DecodeWarning::MorePages`] when the file holds more
|
||||
/// full-resolution pages, and a [`DecodeWarning::Truncated`] when image data is cut off.
|
||||
pub(crate) fn decode_page(bytes: &[u8], page: Option<usize>, limits: &Limits) -> Result<Image, CodecError> {
|
||||
if !cfg!(feature = "tiff") {
|
||||
return Err(CodecError::feature_missing(F, "tiff"));
|
||||
}
|
||||
let (file, dir, more) = open_page(bytes, page)?;
|
||||
let mut img = decode_ifd(&file, &dir, limits)?;
|
||||
let extra_samples = std::mem::take(&mut img.meta.extra_samples);
|
||||
@@ -107,6 +110,9 @@ impl<'a> TiffBands<'a> {
|
||||
/// against `limits`; on 64-bit targets its `max_alloc` bounds each group of bands, not the
|
||||
/// whole image.
|
||||
pub fn open(bytes: &'a [u8], page: Option<usize>, limits: &Limits) -> Result<Self, CodecError> {
|
||||
if !cfg!(feature = "tiff") {
|
||||
return Err(CodecError::feature_missing(F, "tiff"));
|
||||
}
|
||||
let (file, dir, more) = open_page(bytes, page)?;
|
||||
// On 32-bit targets the whole image must still fit `max_alloc`, as it did before: the
|
||||
// document holding it shares the same small address space (wasm32: 4 GiB).
|
||||
@@ -911,7 +917,7 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, feature = "tiff"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{EncodeOptions, ExtraSample, Format};
|
||||
|
||||
@@ -539,6 +539,9 @@ fn check_extra_planes(img: &Image) -> Result<(), CodecError> {
|
||||
}
|
||||
|
||||
pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Vec<u8>, CodecError> {
|
||||
if !cfg!(feature = "tiff") {
|
||||
return Err(CodecError::feature_missing(F, "tiff"));
|
||||
}
|
||||
// Check the source planes before `converted`, which brings them to the plan's sample type
|
||||
// with the image but deliberately leaves a wrong-sized plane alone: past that point a bad
|
||||
// plane would be reinterpreted in the new width rather than rejected.
|
||||
|
||||
@@ -353,6 +353,7 @@ pub(crate) fn encode(f: Format, src: &Image, plan: Plan, opts: &EncodeOptions) -
|
||||
}
|
||||
let img = src.converted(plan.layout, plan.sample);
|
||||
// Targa is written by our encoder: the image crate's RLE packets cross scanlines (#6382).
|
||||
#[cfg(feature = "tga")]
|
||||
if f == Format::Tga {
|
||||
return super::tga::encode(&img);
|
||||
}
|
||||
|
||||
@@ -28,4 +28,8 @@ impl CodecError {
|
||||
pub(crate) fn unsupported(format: Format, reason: impl Into<String>) -> Self {
|
||||
CodecError::Unsupported { format, reason: reason.into() }
|
||||
}
|
||||
/// `format`'s codec is behind the Cargo feature `feature`, which this build leaves out.
|
||||
pub(crate) fn feature_missing(format: Format, feature: &str) -> Self {
|
||||
CodecError::unsupported(format, format!("this build leaves out the {feature} feature"))
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,10 @@
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::codecs::{dds, dpx};
|
||||
#[cfg(feature = "dds")]
|
||||
use crate::codecs::dds;
|
||||
#[cfg(feature = "dpx")]
|
||||
use crate::codecs::dpx;
|
||||
use crate::format::{Format, caps};
|
||||
use crate::image::{ChannelLayout, Image, SampleType};
|
||||
use crate::options::{DdsCompression, EncodeOptions};
|
||||
@@ -170,6 +173,7 @@ pub(crate) fn plan(image: &Image, format: Format, opts: &EncodeOptions) -> Plan
|
||||
}
|
||||
// DPX has no luma + alpha descriptor: gray with alpha is written as luma, alpha dropped.
|
||||
// The sample type follows the chosen bits (U8 for 8, U16 for 10, 12 and 16).
|
||||
#[cfg(feature = "dpx")]
|
||||
Format::Dpx => Plan {
|
||||
layout: if layout == ChannelLayout::GrayA { ChannelLayout::Gray } else { pick_layout(layout, c.layouts, c.alpha) },
|
||||
sample: dpx::plan_sample(opts.dpx_bits, sample),
|
||||
@@ -180,7 +184,12 @@ pub(crate) fn plan(image: &Image, format: Format, opts: &EncodeOptions) -> Plan
|
||||
// BC4, red and green for BC5 (written from RGB, blue dropped), RGBA for BC1 to BC3.
|
||||
// Uncompressed keeps gray and RGB.
|
||||
Format::Dds if opts.dds.compression.is_block() => {
|
||||
Plan { layout: opts.dds.compression.layout().map_or(ChannelLayout::Rgba, dds::channel_layout), sample: SampleType::U8 }
|
||||
#[cfg(feature = "dds")]
|
||||
let layout = opts.dds.compression.layout().map_or(ChannelLayout::Rgba, dds::channel_layout);
|
||||
// Without the `dds` feature no DDS is written.
|
||||
#[cfg(not(feature = "dds"))]
|
||||
let layout = ChannelLayout::Rgba;
|
||||
Plan { layout, sample: SampleType::U8 }
|
||||
}
|
||||
_ => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: pick_sample(sample, c.depths) },
|
||||
}
|
||||
@@ -218,8 +227,15 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOption
|
||||
};
|
||||
// DPX at 10 or 12 bits and Cineon keep fewer bits than their U16 plan: float samples always
|
||||
// lose precision there, 16-bit ones unless they are already code values at that depth.
|
||||
if let Some(bits) = dpx::packed_bits(format, opts).filter(|_| ss != SampleType::U8) {
|
||||
if ss.is_float() || !dpx::keeps_u16_samples(&image.converted(p.layout, SampleType::U16), bits) {
|
||||
// Without the `dpx` feature no DPX or Cineon is written, so nothing is packed.
|
||||
#[cfg(feature = "dpx")]
|
||||
let packed = dpx::packed_bits(format, opts)
|
||||
.filter(|_| ss != SampleType::U8)
|
||||
.map(|bits| (bits, ss.is_float() || !dpx::keeps_u16_samples(&image.converted(p.layout, SampleType::U16), bits)));
|
||||
#[cfg(not(feature = "dpx"))]
|
||||
let packed: Option<(u8, bool)> = None;
|
||||
if let Some((bits, reduced)) = packed {
|
||||
if reduced {
|
||||
w.push(W::BitsReduced { from: ss, bits });
|
||||
}
|
||||
} else if lossy_depth {
|
||||
@@ -276,11 +292,20 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOption
|
||||
w.push(W::MetadataTooLarge { what: "XMP", bytes: xmp.len() });
|
||||
}
|
||||
}
|
||||
if m.dpi.is_some() && (!c.dpi || (format == Format::WebP && !crate::codecs::webp::keeps_dpi(image))) {
|
||||
// Without the feature, WebP and DPX are not written (see `c.write` above).
|
||||
#[cfg(feature = "webp")]
|
||||
let webp_drops_dpi = format == Format::WebP && !crate::codecs::webp::keeps_dpi(image);
|
||||
#[cfg(not(feature = "webp"))]
|
||||
let webp_drops_dpi = false;
|
||||
if m.dpi.is_some() && (!c.dpi || webp_drops_dpi) {
|
||||
w.push(W::DpiDropped);
|
||||
}
|
||||
#[cfg(feature = "dpx")]
|
||||
let dpx_key = |k: &str| dpx::KEYS.contains(&k);
|
||||
#[cfg(not(feature = "dpx"))]
|
||||
let dpx_key = |_: &str| false;
|
||||
// DPX keeps its own header fields, not free-form text.
|
||||
let text_kept = |k: &str| c.text && (format != Format::Dpx || crate::codecs::dpx::KEYS.contains(&k));
|
||||
let text_kept = |k: &str| c.text && (format != Format::Dpx || dpx_key(k));
|
||||
if m.text.iter().any(|(k, _)| !text_kept(k)) {
|
||||
w.push(W::TextDropped);
|
||||
}
|
||||
|
||||
@@ -103,9 +103,10 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[
|
||||
),
|
||||
(
|
||||
Format::Jxl,
|
||||
"Lossless JPEG XL export uses the pure-Rust zune-jpegxl encoder in every build; JPEG XL decode \
|
||||
(craft-jxl on jxl-oxide, pure Rust) is behind the non-default `jxl` feature, which official \
|
||||
builds enable. Without the feature JPEG XL is written but not read.",
|
||||
"Lossless JPEG XL export uses the pure-Rust zune-jpegxl encoder behind the default \
|
||||
`jxl-encode` feature; JPEG XL decode (craft-jxl on jxl-oxide, pure Rust) is behind the \
|
||||
non-default `jxl` feature, which official builds enable. With only one of them JPEG XL is \
|
||||
written but not read, or read but not written.",
|
||||
),
|
||||
(
|
||||
Format::Heif,
|
||||
@@ -276,8 +277,36 @@ impl Format {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Cargo feature holding `format`'s codec, when this build leaves it out.
|
||||
pub(crate) fn missing_feature(format: Format) -> Option<&'static str> {
|
||||
let (feature, enabled) = match format {
|
||||
Format::Dds => ("dds", cfg!(feature = "dds")),
|
||||
Format::Dicom => ("dicom", cfg!(feature = "dicom")),
|
||||
Format::Dpx | Format::Cineon => ("dpx", cfg!(feature = "dpx")),
|
||||
Format::OpenExr => ("exr", cfg!(feature = "exr")),
|
||||
Format::Fits => ("fits", cfg!(feature = "fits")),
|
||||
Format::Iff => ("iff", cfg!(feature = "iff")),
|
||||
Format::Jp2 => ("jp2", cfg!(feature = "jp2")),
|
||||
Format::JpegLs => ("jpegls", cfg!(feature = "jpegls")),
|
||||
Format::Pnm => ("pnm", cfg!(feature = "pnm")),
|
||||
Format::Sgi => ("sgi", cfg!(feature = "sgi")),
|
||||
Format::SunRaster => ("sunraster", cfg!(feature = "sunraster")),
|
||||
Format::Tga => ("tga", cfg!(feature = "tga")),
|
||||
Format::Tiff => ("tiff", cfg!(feature = "tiff")),
|
||||
Format::WebP => ("webp", cfg!(feature = "webp")),
|
||||
Format::Xpm => ("xpm", cfg!(feature = "xpm")),
|
||||
_ => return None,
|
||||
};
|
||||
(!enabled).then_some(feature)
|
||||
}
|
||||
|
||||
/// Capability table. `read`/`write` reflect the current build's features.
|
||||
pub fn caps(format: Format) -> FormatCaps {
|
||||
let caps = format_caps(format);
|
||||
if missing_feature(format).is_some() { FormatCaps { read: false, write: false, ..caps } } else { caps }
|
||||
}
|
||||
|
||||
fn format_caps(format: Format) -> FormatCaps {
|
||||
let base = FormatCaps {
|
||||
read: true,
|
||||
write: true,
|
||||
@@ -335,7 +364,13 @@ pub fn caps(format: Format) -> FormatCaps {
|
||||
// `text`: the DPX header fields only (see `fidelity_warnings_with`).
|
||||
Format::Dpx => FormatCaps { depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb, L::Rgba], text: true, ..base },
|
||||
// GrayA is widened to RGBA at the same depth; the 16-bit alpha header is corrected.
|
||||
Format::Jxl => FormatCaps { read: cfg!(feature = "jxl"), depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb, L::Rgba], ..base },
|
||||
Format::Jxl => FormatCaps {
|
||||
read: cfg!(feature = "jxl"),
|
||||
write: cfg!(feature = "jxl-encode"),
|
||||
depths: &[S::U8, S::U16],
|
||||
layouts: &[L::Gray, L::Rgb, L::Rgba],
|
||||
..base
|
||||
},
|
||||
Format::Cineon => FormatCaps { depths: &[S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base },
|
||||
Format::Dicom => FormatCaps { read: true, write: false, depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base },
|
||||
Format::Iff => FormatCaps { depths: &[S::U8], layouts: &[L::Rgb, L::Rgba], alpha: true, ..base },
|
||||
@@ -350,7 +385,13 @@ pub fn caps(format: Format) -> FormatCaps {
|
||||
FormatCaps { read: cfg!(feature = "sgi"), write: cfg!(feature = "sgi"), depths: &[S::U8, S::U16], layouts: RGB_GRAY, alpha: true, ..base }
|
||||
}
|
||||
Format::JpegLs => FormatCaps { depths: &[S::U8, S::U16], layouts: &[L::Gray, L::Rgb], alpha: false, ..base },
|
||||
Format::Jp2 => FormatCaps { read: true, write: false, layouts: &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk, L::CmykA], icc: true, ..base },
|
||||
Format::Jp2 => FormatCaps {
|
||||
read: cfg!(feature = "jp2"),
|
||||
write: false,
|
||||
layouts: &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk, L::CmykA],
|
||||
icc: true,
|
||||
..base
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,7 +437,6 @@ impl PrefixDetector {
|
||||
/// The answer [`detect_prefix`] gives for `bytes`. The `bytes` of each call must start with
|
||||
/// the `bytes` of the previous call on this detector.
|
||||
pub fn detect(&mut self, bytes: &[u8]) -> Detection {
|
||||
use crate::codecs::jpegls::{JpegFrame, jpeg_frame_from};
|
||||
match jpeg_frame_from(bytes, &mut self.jpeg_pos) {
|
||||
Some(JpegFrame::Short(len)) => Detection::NeedBytes(len),
|
||||
Some(JpegFrame::Ls) => Detection::Format(Format::JpegLs),
|
||||
@@ -419,7 +459,7 @@ pub fn detect(bytes: &[u8]) -> Option<Format> {
|
||||
if b.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
return Some(Format::Png);
|
||||
}
|
||||
if crate::codecs::jpegls::looks_like_jpegls(b) {
|
||||
if looks_like_jpegls(b) {
|
||||
return Some(Format::JpegLs);
|
||||
}
|
||||
if b.starts_with(&[0xFF, 0xD8, 0xFF]) {
|
||||
@@ -475,13 +515,13 @@ pub fn detect(bytes: &[u8]) -> Option<Format> {
|
||||
if b.starts_with(b"SDPX") || b.starts_with(b"XPDS") {
|
||||
return Some(Format::Dpx);
|
||||
}
|
||||
if crate::codecs::dpx::is_cineon(b) {
|
||||
if is_cineon(b) {
|
||||
return Some(Format::Cineon);
|
||||
}
|
||||
if crate::codecs::dicom::is_dicom(b) {
|
||||
if is_dicom(b) {
|
||||
return Some(Format::Dicom);
|
||||
}
|
||||
if crate::codecs::iff::looks_like_iff(b) {
|
||||
if looks_like_iff(b) {
|
||||
return Some(Format::Iff);
|
||||
}
|
||||
if b.starts_with(b"SIMPLE =") {
|
||||
@@ -507,6 +547,85 @@ pub fn detect(bytes: &[u8]) -> Option<Format> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The JPEG-LS frame marker.
|
||||
pub(crate) const SOF55: u8 = 0xF7;
|
||||
|
||||
/// What the marker segments after a JPEG SOI lead to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum JpegFrame {
|
||||
/// An SOF55 frame header: JPEG-LS.
|
||||
Ls,
|
||||
/// Another frame header, a scan header, an EOI, or a byte that is not a marker where one
|
||||
/// should be.
|
||||
Other,
|
||||
/// The bytes end before a frame or scan header. The next step reads the bytes up to this
|
||||
/// length.
|
||||
Short(usize),
|
||||
}
|
||||
|
||||
/// Walks the marker segments of `b` from its SOI up to the first frame or scan header. `None`
|
||||
/// when `b` does not start with an SOI. Each step moves forward at least one byte, so the walk
|
||||
/// takes at most `b.len()` steps and reaches the frame header after any number of segments.
|
||||
pub(crate) fn jpeg_frame(b: &[u8]) -> Option<JpegFrame> {
|
||||
jpeg_frame_from(b, &mut 0)
|
||||
}
|
||||
|
||||
/// [`jpeg_frame`], started at `*pos`. A `*pos` of 0 starts at the SOI. Any other value is the
|
||||
/// offset of the marker where an earlier walk of a shorter prefix of the same file stopped, and the
|
||||
/// walk does not read the bytes before it. The walk leaves `*pos` at the marker it stopped at, so
|
||||
/// walking longer and longer prefixes of one file this way reads each marker segment once.
|
||||
pub(crate) fn jpeg_frame_from(b: &[u8], pos: &mut usize) -> Option<JpegFrame> {
|
||||
if *pos == 0 {
|
||||
if !b.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
*pos = 2;
|
||||
}
|
||||
loop {
|
||||
let (Some(&prefix), Some(&marker)) = (b.get(*pos), b.get(*pos + 1)) else {
|
||||
return Some(if b.get(*pos).is_none_or(|&p| p == 0xFF) { JpegFrame::Short(*pos + 2) } else { JpegFrame::Other });
|
||||
};
|
||||
if prefix != 0xFF {
|
||||
return Some(JpegFrame::Other);
|
||||
}
|
||||
match marker {
|
||||
SOF55 => return Some(JpegFrame::Ls),
|
||||
// `FF 00` is a stuffed zero, not a marker.
|
||||
0x00 | 0xDA | 0xD9 => return Some(JpegFrame::Other),
|
||||
// A DRI segment (`0xDD`) may precede an SOF55 frame header, so it takes the
|
||||
// length-prefixed path below.
|
||||
0xC0..=0xCF | 0xDB | 0xDC | 0xDE | 0xDF => return Some(JpegFrame::Other),
|
||||
0x01 | 0xD0..=0xD7 | 0xFF => *pos += if marker == 0xFF { 1 } else { 2 },
|
||||
_ => {
|
||||
let Some(len) = b.get(*pos + 2..*pos + 4).map(|l| usize::from(u16::from_be_bytes([l[0], l[1]]))) else {
|
||||
return Some(JpegFrame::Short(*pos + 4));
|
||||
};
|
||||
*pos += 2 + len;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `b` is a JPEG-LS file: an SOI followed by marker segments up to an SOF55 frame header.
|
||||
pub(crate) fn looks_like_jpegls(b: &[u8]) -> bool {
|
||||
jpeg_frame(b) == Some(JpegFrame::Ls)
|
||||
}
|
||||
|
||||
/// A DICOM file begins with a 128-byte preamble and the `DICM` magic.
|
||||
pub(crate) fn is_dicom(b: &[u8]) -> bool {
|
||||
b.get(128..132) == Some(b"DICM")
|
||||
}
|
||||
|
||||
/// The Cineon magic number (`802A5FD7` hex), big-endian.
|
||||
pub(crate) fn is_cineon(b: &[u8]) -> bool {
|
||||
b.get(..4) == Some(&[0x80, 0x2A, 0x5F, 0xD7])
|
||||
}
|
||||
|
||||
/// `FORM` + a bitmap type (`ILBM` interleaved, `PBM ` chunky) at offset 8.
|
||||
pub(crate) fn looks_like_iff(b: &[u8]) -> bool {
|
||||
b.get(0..4) == Some(b"FORM") && matches!(b.get(8..12), Some(b"ILBM" | b"PBM "))
|
||||
}
|
||||
|
||||
/// The major brand and complete compatible brands in a leading ISO-BMFF `ftyp` box.
|
||||
///
|
||||
/// Pass at most the bytes the caller wants to inspect. A missing box or incomplete major
|
||||
|
||||
@@ -283,6 +283,7 @@ impl fmt::Display for DecodeWarning {
|
||||
}
|
||||
|
||||
/// One channel of a [`DeepImage`]: the samples of every pixel, one flat list in pixel order.
|
||||
#[cfg(feature = "exr")]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DeepChannel {
|
||||
/// The channel name as in the file (e.g. `R`, `G`, `B`, `A`, `Z`).
|
||||
@@ -298,6 +299,7 @@ pub struct DeepChannel {
|
||||
/// Deep image data (OpenEXR `deepscanline`/`deeptile`): a variable-length list of samples
|
||||
/// per pixel, each with its own colour, alpha and depth. All channels share the same sample
|
||||
/// layout, so a sample is one index into every channel.
|
||||
#[cfg(feature = "exr")]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct DeepImage {
|
||||
pub width: u32,
|
||||
@@ -317,6 +319,7 @@ pub struct DeepImage {
|
||||
pub counts: Vec<u64>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "exr")]
|
||||
impl DeepImage {
|
||||
/// A channel by its exact name.
|
||||
pub fn channel(&self, name: &str) -> Option<&DeepChannel> {
|
||||
@@ -337,6 +340,7 @@ impl DeepImage {
|
||||
|
||||
/// One channel of an [`ExrPartInfo`]: the name as in the file (a Maya/Arnold AOV layer
|
||||
/// keeps its prefix, e.g. `diffuse.R`) and the sample type that part stores it with.
|
||||
#[cfg(feature = "exr")]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ExrChannelInfo {
|
||||
pub name: String,
|
||||
@@ -347,6 +351,7 @@ pub struct ExrChannelInfo {
|
||||
/// header facts only, no pixel data. [`crate::exr_info`] lists them, and the index is
|
||||
/// what [`crate::decode_exr_part`] decodes; [`crate::decode_as_with`] opens the part
|
||||
/// the ranking in [`ExrPartInfo::color_rank`] prefers.
|
||||
#[cfg(feature = "exr")]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ExrPartInfo {
|
||||
/// Index into the part list, in file order.
|
||||
@@ -370,6 +375,7 @@ pub struct ExrPartInfo {
|
||||
pub channels: Vec<ExrChannelInfo>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "exr")]
|
||||
impl ExrPartInfo {
|
||||
/// How much this part looks like a colour image the plain [`Image`] decode can show:
|
||||
/// 4 RGBA, 3 RGB, 2 YA, 1 Y or any-single-channel, 0 anything else (e.g. `Z` beside `A`).
|
||||
@@ -384,6 +390,7 @@ impl ExrPartInfo {
|
||||
/// One selection policy for header ranking/probing and flat decoding: never synthesize
|
||||
/// RGB(A) or YA from separate layers. OpenEXR layers use the full prefix before the last
|
||||
/// dot, including nested layers; a leading or trailing dot alone does not name a layer.
|
||||
#[cfg(feature = "exr")]
|
||||
pub(crate) fn exr_color_channels<'a>(names: impl IntoIterator<Item = &'a str>) -> Option<(ChannelLayout, Vec<usize>)> {
|
||||
#[derive(Default)]
|
||||
struct Group {
|
||||
@@ -442,6 +449,7 @@ pub(crate) fn exr_color_channels<'a>(names: impl IntoIterator<Item = &'a str>) -
|
||||
}
|
||||
|
||||
/// Strip an optional `layer.` prefix from a channel name (`diffuse.R` → `R`).
|
||||
#[cfg(feature = "exr")]
|
||||
pub(crate) fn base_channel_name(name: &str) -> &str {
|
||||
name.rsplit('.').next().unwrap_or(name)
|
||||
}
|
||||
@@ -450,6 +458,7 @@ pub(crate) fn base_channel_name(name: &str) -> &str {
|
||||
/// material IDs with coverage, as written by Arnold, V-Ray, Redshift, Mantra/Karma or Cycles.
|
||||
/// Header facts plus the parsed manifest; the samples come from
|
||||
/// [`crate::decode_cryptomatte`].
|
||||
#[cfg(feature = "exr")]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CryptomatteLayer {
|
||||
/// The part (see [`crate::exr_info`]) the channels and attributes live in.
|
||||
@@ -470,6 +479,7 @@ pub struct CryptomatteLayer {
|
||||
pub channels: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "exr")]
|
||||
impl CryptomatteLayer {
|
||||
/// The manifest name for an ID value, when the manifest lists it.
|
||||
pub fn name_of(&self, id: f32) -> Option<&str> {
|
||||
@@ -480,6 +490,7 @@ impl CryptomatteLayer {
|
||||
/// Decoded Cryptomatte samples: per pixel the (ID, coverage) pairs with coverage above zero,
|
||||
/// sorted by descending coverage. The IDs are the float values as stored (compared by value,
|
||||
/// never by bit pattern, like the reference readers).
|
||||
#[cfg(feature = "exr")]
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CryptomatteBuffer {
|
||||
pub width: u32,
|
||||
@@ -487,6 +498,7 @@ pub struct CryptomatteBuffer {
|
||||
pub pixels: Vec<Vec<(f32, f32)>>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "exr")]
|
||||
impl CryptomatteBuffer {
|
||||
/// The pairs of one pixel; empty for a pixel covered by nothing.
|
||||
pub fn at(&self, x: u32, y: u32) -> &[(f32, f32)] {
|
||||
|
||||
+129
-79
@@ -9,7 +9,7 @@
|
||||
//! tells the UI exactly what an export will lose.
|
||||
//! * APIs use bytes or caller-provided readers, with no ambient filesystem access,
|
||||
//! and build for `wasm32-unknown-unknown`. Byte decoders enforce [`Limits`];
|
||||
//! [`exr_stream`] instead bounds metadata and one decoded compression block.
|
||||
//! `exr_stream` instead bounds metadata and one decoded compression block.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
@@ -23,6 +23,7 @@ mod codecs;
|
||||
mod display;
|
||||
mod error;
|
||||
pub mod exif_color;
|
||||
#[cfg(feature = "exr")]
|
||||
pub mod exr_stream;
|
||||
mod fidelity;
|
||||
mod format;
|
||||
@@ -47,6 +48,7 @@ pub use crate::allocation::{probe_allocation_size, probe_stored_size};
|
||||
pub use crate::cicp::Cicp;
|
||||
pub use crate::cicp::ContentLightLevel;
|
||||
pub use crate::codecs::avif::{HDR_REFERENCE_WHITE_NITS, HdrTransfer, encode_avif_hdr, encode_avif_with_speed};
|
||||
#[cfg(feature = "exr")]
|
||||
pub use crate::codecs::exr_cryptomatte::{cryptomatte_id, cryptomatte_key, cryptomatte_preview_color};
|
||||
pub use crate::codecs::gif_frames::{AnimationFrame, MAX_GIF_FRAMES};
|
||||
pub use crate::codecs::jpeg::validate_jpeg_rgba8;
|
||||
@@ -65,10 +67,9 @@ pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_
|
||||
pub use crate::format::{
|
||||
ASYMMETRIC_EXCEPTIONS, Detection, Format, FormatCaps, PrefixDetector, caps, detect, detect_prefix, from_extension, ftyp_brands,
|
||||
};
|
||||
pub use crate::image::{
|
||||
ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, ExtraSample, Image,
|
||||
MAX_EXTRA_SAMPLES, Metadata, SampleType, convert_samples,
|
||||
};
|
||||
pub use crate::image::{ChannelLayout, DecodeWarning, ExtraSample, Image, MAX_EXTRA_SAMPLES, Metadata, SampleType, convert_samples};
|
||||
#[cfg(feature = "exr")]
|
||||
pub use crate::image::{CryptomatteBuffer, CryptomatteLayer, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo};
|
||||
pub use crate::inspection::{RasterColorType, RasterInspection, ToneClass, classify_tone, embedded_icc, inspect_raster};
|
||||
pub use crate::options::{
|
||||
DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, Limits, PngCompression, PngStereo,
|
||||
@@ -77,14 +78,58 @@ pub use crate::options::{
|
||||
pub use crate::orientation::{OrientSteps, exif_orientation, upright_exif, upright_xmp};
|
||||
pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};
|
||||
pub use crate::resolution_probe::file_resolution;
|
||||
pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding};
|
||||
pub use crate::source_settings::jpeg_quality;
|
||||
#[cfg(feature = "webp")]
|
||||
pub use crate::source_settings::{WebpEncoding, webp_encoding};
|
||||
pub use half::f16;
|
||||
|
||||
#[cfg(feature = "dds")]
|
||||
use crate::codecs::dds;
|
||||
#[cfg(feature = "dicom")]
|
||||
use crate::codecs::dicom;
|
||||
#[cfg(feature = "dpx")]
|
||||
use crate::codecs::dpx;
|
||||
#[cfg(feature = "exr")]
|
||||
use crate::codecs::exr;
|
||||
#[cfg(feature = "fits")]
|
||||
use crate::codecs::fits;
|
||||
#[cfg(feature = "iff")]
|
||||
use crate::codecs::iff;
|
||||
#[cfg(feature = "jp2")]
|
||||
use crate::codecs::jp2;
|
||||
#[cfg(feature = "jpegls")]
|
||||
use crate::codecs::jpegls;
|
||||
#[cfg(feature = "pnm")]
|
||||
use crate::codecs::pnm;
|
||||
#[cfg(feature = "sgi")]
|
||||
use crate::codecs::sgi;
|
||||
#[cfg(feature = "sunraster")]
|
||||
use crate::codecs::sunraster;
|
||||
use crate::codecs::{bmp, dds, dicom, dpx, exr, fits, heif, iff, jp2, jpeg, jpegls, jxl, pcx, png, pnm, tiff, via_image, webp, xpm};
|
||||
#[cfg(feature = "webp")]
|
||||
use crate::codecs::webp;
|
||||
#[cfg(feature = "xpm")]
|
||||
use crate::codecs::xpm;
|
||||
use crate::codecs::{bmp, heif, jpeg, jxl, pcx, png, tiff, via_image};
|
||||
|
||||
/// `$codec` in a build with the Cargo feature `$feature`, else the error naming that feature.
|
||||
macro_rules! gated {
|
||||
($feature:literal, $format:expr, $codec:expr) => {{
|
||||
#[cfg(feature = $feature)]
|
||||
let result = $codec;
|
||||
#[cfg(not(feature = $feature))]
|
||||
let result = Err(CodecError::feature_missing($format, $feature));
|
||||
result
|
||||
}};
|
||||
}
|
||||
|
||||
/// The error for a format `caps` says this build can't handle: the missing feature when one is
|
||||
/// the reason, else `reason`.
|
||||
fn unavailable(format: Format, reason: &str) -> CodecError {
|
||||
match format::missing_feature(format) {
|
||||
Some(feature) => CodecError::feature_missing(format, feature),
|
||||
None => CodecError::unsupported(format, reason),
|
||||
}
|
||||
}
|
||||
|
||||
/// Detect the format and decode with default [`Limits`].
|
||||
pub fn decode(bytes: &[u8]) -> Result<Image, CodecError> {
|
||||
@@ -122,47 +167,38 @@ pub fn decode_as(format: Format, bytes: &[u8]) -> Result<Image, CodecError> {
|
||||
pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Result<Image, CodecError> {
|
||||
// HEIF without the `heif` feature: its decoder stub says what is missing from this build.
|
||||
if !caps(format).read && !matches!(format, Format::Heif | Format::Jxl) {
|
||||
return Err(CodecError::unsupported(format, "decoding is not available for this format"));
|
||||
return Err(unavailable(format, "decoding is not available for this format"));
|
||||
}
|
||||
let l = &opts.limits;
|
||||
let img = match format {
|
||||
Format::Png => png::decode(bytes, l),
|
||||
Format::Jpeg => jpeg::decode(bytes, l),
|
||||
Format::Tiff => tiff::decode(bytes, l),
|
||||
Format::WebP => webp::decode(bytes, l),
|
||||
Format::Pnm => pnm::decode(bytes, l),
|
||||
Format::WebP => gated!("webp", format, webp::decode(bytes, l)),
|
||||
Format::Pnm => gated!("pnm", format, pnm::decode(bytes, l)),
|
||||
Format::Pcx => pcx::decode(bytes, l),
|
||||
Format::Xpm => xpm::decode(bytes, l),
|
||||
Format::Dds => dds::decode(bytes, l),
|
||||
Format::Fits => fits::decode(bytes, l),
|
||||
Format::Dpx => dpx::decode(bytes, l),
|
||||
Format::Cineon => dpx::decode_cineon(bytes, l),
|
||||
Format::Dicom => dicom::decode(bytes, l),
|
||||
Format::Iff => iff::decode(bytes, l),
|
||||
Format::SunRaster => {
|
||||
#[cfg(feature = "sunraster")]
|
||||
{
|
||||
sunraster::decode(bytes, l)
|
||||
}
|
||||
#[cfg(not(feature = "sunraster"))]
|
||||
{
|
||||
Err(CodecError::unsupported(format, "Sun Raster support requires the sunraster feature"))
|
||||
}
|
||||
}
|
||||
Format::Sgi => {
|
||||
#[cfg(feature = "sgi")]
|
||||
{
|
||||
sgi::decode(bytes, l)
|
||||
}
|
||||
#[cfg(not(feature = "sgi"))]
|
||||
{
|
||||
Err(CodecError::unsupported(format, "SGI support requires the sgi feature"))
|
||||
}
|
||||
}
|
||||
Format::JpegLs => jpegls::decode(bytes, l),
|
||||
Format::OpenExr => exr::decode(bytes, l),
|
||||
Format::Xpm => gated!("xpm", format, xpm::decode(bytes, l)),
|
||||
Format::Dds => gated!("dds", format, dds::decode(bytes, l)),
|
||||
Format::Fits => gated!("fits", format, fits::decode(bytes, l)),
|
||||
Format::Dpx => gated!("dpx", format, dpx::decode(bytes, l)),
|
||||
Format::Cineon => gated!("dpx", format, dpx::decode_cineon(bytes, l)),
|
||||
Format::Dicom => gated!("dicom", format, dicom::decode(bytes, l)),
|
||||
Format::Iff => gated!("iff", format, iff::decode(bytes, l)),
|
||||
Format::SunRaster => gated!("sunraster", format, sunraster::decode(bytes, l)),
|
||||
Format::Sgi => gated!("sgi", format, sgi::decode(bytes, l)),
|
||||
Format::JpegLs => gated!("jpegls", format, jpegls::decode(bytes, l)),
|
||||
Format::OpenExr => gated!("exr", format, exr::decode(bytes, l)),
|
||||
Format::Heif => heif::decode(bytes, l, opts.keep_orientation),
|
||||
Format::Jp2 => jp2::decode(bytes, l),
|
||||
Format::Jp2 => {
|
||||
#[cfg(feature = "jp2")]
|
||||
{
|
||||
jp2::decode(bytes, l)
|
||||
}
|
||||
#[cfg(not(feature = "jp2"))]
|
||||
{
|
||||
Err(CodecError::unsupported(format, "JPEG 2000 support requires the jp2 feature"))
|
||||
}
|
||||
}
|
||||
Format::Jxl => jxl::decode(bytes, l),
|
||||
#[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))]
|
||||
Format::Avif => codecs::avif_decode::decode(bytes, l, opts.keep_orientation),
|
||||
@@ -242,7 +278,9 @@ fn finish_format(format: Format, bytes: &[u8], mut img: Image, opts: &DecodeOpti
|
||||
let o = match format {
|
||||
Format::Tiff => tiff::orientation(bytes, None),
|
||||
Format::Heif | Format::Avif => 1,
|
||||
#[cfg(feature = "dpx")]
|
||||
Format::Dpx => dpx::orientation(bytes),
|
||||
#[cfg(feature = "dpx")]
|
||||
Format::Cineon => dpx::cineon_orientation(bytes),
|
||||
_ => img.meta.exif.as_deref().map_or(1, exif_orientation),
|
||||
};
|
||||
@@ -279,7 +317,7 @@ pub fn decode_png_rows<E: From<CodecError>>(
|
||||
pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> {
|
||||
let format = detect(bytes).ok_or(CodecError::UnknownFormat)?;
|
||||
if !caps(format).read {
|
||||
return Err(CodecError::unsupported(format, "decoding is not available for this format"));
|
||||
return Err(unavailable(format, "decoding is not available for this format"));
|
||||
}
|
||||
let l = &Limits::default();
|
||||
let (w, h, exif) = match format {
|
||||
@@ -289,8 +327,8 @@ pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> {
|
||||
let (w, h, o) = tiff::probe(bytes, l)?;
|
||||
return Ok(if (5..=8).contains(&o) { (h, w) } else { (w, h) });
|
||||
}
|
||||
Format::WebP => webp::probe(bytes, l)?,
|
||||
Format::OpenExr => exr::probe(bytes, l).map(|(w, h)| (w, h, None))?,
|
||||
Format::WebP => gated!("webp", format, webp::probe(bytes, l))?,
|
||||
Format::OpenExr => gated!("exr", format, exr::probe(bytes, l).map(|(w, h)| (w, h, None)))?,
|
||||
#[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))]
|
||||
Format::Avif => codecs::avif_decode::probe(bytes, l).map(|(w, h)| (w, h, None))?,
|
||||
#[cfg(not(all(feature = "avif-decode", not(target_arch = "wasm32"))))]
|
||||
@@ -346,6 +384,7 @@ pub fn pcx_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
}
|
||||
|
||||
/// The X11 color-name lookup used by XPM files, expressed as normalized sRGB.
|
||||
#[cfg(feature = "xpm")]
|
||||
pub fn xpm_named_color_rgb(name: &str) -> Option<[f32; 3]> {
|
||||
let rgb = codecs::xpm::exact_x11_name(name)?;
|
||||
Some(rgb.map(|channel| f32::from(channel) / 255.0))
|
||||
@@ -409,6 +448,7 @@ pub fn decode_gif_frames(bytes: &[u8], opts: &DecodeOptions) -> Result<Vec<Anima
|
||||
/// reads it), each a full picture of the canvas with its duration and the file's ICC profile.
|
||||
/// [`decode`] keeps the first frame only. See [`MAX_GIF_FRAMES`] and `opts.limits` for what is
|
||||
/// refused.
|
||||
#[cfg(feature = "webp")]
|
||||
pub fn decode_webp_frames(bytes: &[u8], opts: &DecodeOptions) -> Result<Vec<AnimationFrame>, CodecError> {
|
||||
match crate::codecs::webp::decode_frames(bytes, &opts.limits)? {
|
||||
Some(frames) => Ok(frames),
|
||||
@@ -418,6 +458,7 @@ pub fn decode_webp_frames(bytes: &[u8], opts: &DecodeOptions) -> Result<Vec<Anim
|
||||
|
||||
/// Whether `bytes` is an animated WebP of more than one frame (which [`decode`] opens as its
|
||||
/// first frame, with a warning, and [`decode_webp_frames`] reads whole).
|
||||
#[cfg(feature = "webp")]
|
||||
pub fn webp_is_animated(bytes: &[u8]) -> bool {
|
||||
crate::codecs::webp::is_animated(bytes)
|
||||
}
|
||||
@@ -427,11 +468,29 @@ pub fn webp_is_animated(bytes: &[u8]) -> bool {
|
||||
/// DPX elements and FITS HDU payloads.
|
||||
/// Pixels are not decoded; derived TIFF thumbnails do not require preservation here.
|
||||
/// Other formats return false; this does not establish preservation of other format-specific data.
|
||||
/// A format whose codec this build leaves out is refused with [`CodecError::Unsupported`].
|
||||
pub fn has_unretained_source_data(bytes: &[u8]) -> Result<bool, CodecError> {
|
||||
match detect(bytes) {
|
||||
let detected = detect(bytes);
|
||||
if let Some(format) = detected {
|
||||
// Encoder-only builds cannot establish whether decoding would discard source data.
|
||||
// Keep this separate from missing_feature, which also controls write capabilities.
|
||||
let missing = match format {
|
||||
Format::Jxl if !cfg!(feature = "jxl") => Some("jxl"),
|
||||
Format::Heif if !cfg!(feature = "heif") => Some("heif"),
|
||||
Format::Avif if !cfg!(feature = "avif-decode") => Some("avif-decode"),
|
||||
Format::Avif if cfg!(target_arch = "wasm32") => {
|
||||
return Err(CodecError::unsupported(format, "AVIF decoding requires the avif-decode feature on a native target"));
|
||||
}
|
||||
_ => format::missing_feature(format),
|
||||
};
|
||||
if let Some(feature) = missing {
|
||||
return Err(CodecError::feature_missing(format, feature));
|
||||
}
|
||||
}
|
||||
match detected {
|
||||
Some(Format::Gif) => via_image::gif_has_more_frames(bytes).ok_or_else(|| CodecError::malformed(Format::Gif, "cannot inspect every frame")),
|
||||
Some(Format::Png) => png::has_additional_images(bytes),
|
||||
Some(Format::WebP) => Ok(webp_is_animated(bytes)),
|
||||
Some(Format::WebP) => gated!("webp", Format::WebP, Ok(webp_is_animated(bytes))),
|
||||
Some(Format::Tiff) => {
|
||||
let info = tiff_info(bytes)?;
|
||||
if !info.complete {
|
||||
@@ -450,9 +509,9 @@ pub fn has_unretained_source_data(bytes: &[u8]) -> Result<bool, CodecError> {
|
||||
.ok_or_else(|| CodecError::malformed(Format::Ico, "truncated image count"))?;
|
||||
Ok(u16::from_le_bytes(count) > 1)
|
||||
}
|
||||
Some(Format::Dds) => dds::has_additional_images(bytes),
|
||||
Some(Format::Dpx) => dpx::has_additional_images(bytes),
|
||||
Some(Format::Fits) => fits::has_additional_images(bytes),
|
||||
Some(Format::Dds) => gated!("dds", Format::Dds, dds::has_additional_images(bytes)),
|
||||
Some(Format::Dpx) => gated!("dpx", Format::Dpx, dpx::has_additional_images(bytes)),
|
||||
Some(Format::Fits) => gated!("fits", Format::Fits, fits::has_additional_images(bytes)),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
@@ -501,12 +560,14 @@ fn finish_decode(img: Image, o: u16, opts: &DecodeOptions) -> Result<Image, Code
|
||||
/// (name, view, size, channels, deep/tiled), what a multi-part chooser — a Maya/Arnold
|
||||
/// render writes one part per AOV — offers. The indices are what [`decode_exr_part`]
|
||||
/// takes; [`decode_as_with`] opens the part with the highest [`ExrPartInfo::color_rank`].
|
||||
#[cfg(feature = "exr")]
|
||||
pub fn exr_info(bytes: &[u8], limits: &Limits) -> Result<Vec<ExrPartInfo>, CodecError> {
|
||||
exr::info(bytes, limits)
|
||||
}
|
||||
|
||||
/// Decodes part `part` (an index into [`exr_info`]'s list) of an OpenEXR file.
|
||||
/// Deep parts stay with [`decode_deep_exr`]; a file that has any is refused here.
|
||||
#[cfg(feature = "exr")]
|
||||
pub fn decode_exr_part(bytes: &[u8], part: usize, opts: &DecodeOptions) -> Result<Image, CodecError> {
|
||||
let img = exr::decode_part(bytes, part, &opts.limits)?;
|
||||
finish_decode(img, 1, opts)
|
||||
@@ -516,6 +577,7 @@ pub fn decode_exr_part(bytes: &[u8], part: usize, opts: &DecodeOptions) -> Resul
|
||||
/// with coverage, as written by Arnold, V-Ray, Redshift, Mantra/Karma and Cycles) from the
|
||||
/// headers alone: name, metadata key, channels and the parsed embedded manifest. The
|
||||
/// samples come from [`decode_cryptomatte`]; names hash to IDs with [`cryptomatte_id`].
|
||||
#[cfg(feature = "exr")]
|
||||
pub fn cryptomatte_layers(bytes: &[u8], limits: &Limits) -> Result<Vec<CryptomatteLayer>, CodecError> {
|
||||
codecs::exr_cryptomatte::layers(bytes, limits)
|
||||
}
|
||||
@@ -523,6 +585,7 @@ pub fn cryptomatte_layers(bytes: &[u8], limits: &Limits) -> Result<Vec<Cryptomat
|
||||
/// Decodes the samples of the Cryptomatte layer called `layer_name` (a
|
||||
/// [`CryptomatteLayer::name`]): per pixel its (ID, coverage) pairs, coverage above zero,
|
||||
/// sorted by descending coverage.
|
||||
#[cfg(feature = "exr")]
|
||||
pub fn decode_cryptomatte(bytes: &[u8], layer_name: &str, limits: &Limits) -> Result<CryptomatteBuffer, CodecError> {
|
||||
codecs::exr_cryptomatte::decode(bytes, layer_name, limits)
|
||||
}
|
||||
@@ -530,6 +593,7 @@ pub fn decode_cryptomatte(bytes: &[u8], layer_name: &str, limits: &Limits) -> Re
|
||||
/// Decodes the named channels of one part (exact names as the file stores them, e.g.
|
||||
/// `diffuse.R`) into an image: R/G/B (plus A when named) give Rgba, a lone Y gives Gray.
|
||||
/// This renders a channel group without the part's other channels in the way.
|
||||
#[cfg(feature = "exr")]
|
||||
pub fn decode_exr_channels(bytes: &[u8], part: usize, names: &[&str], opts: &DecodeOptions) -> Result<Image, CodecError> {
|
||||
let img = exr::decode_channels(bytes, part, names, &opts.limits)?;
|
||||
finish_decode(img, 1, opts)
|
||||
@@ -539,6 +603,7 @@ pub fn decode_exr_channels(bytes: &[u8], part: usize, names: &[&str], opts: &Dec
|
||||
/// (colour, alpha and Z per sample), for callers that composite deep data themselves —
|
||||
/// [`decode_as_with`] instead flattens a deep file into a normal [`Image`] with a
|
||||
/// [`DecodeWarning::DeepFlattened`]. `Err(Unsupported)` when the file has no deep part.
|
||||
#[cfg(feature = "exr")]
|
||||
pub fn decode_deep_exr(bytes: &[u8], limits: &Limits) -> Result<DeepImage, CodecError> {
|
||||
codecs::exr::check_previews(bytes)?;
|
||||
let mut cur = std::io::Cursor::new(bytes);
|
||||
@@ -551,7 +616,10 @@ pub fn decode_deep_exr(bytes: &[u8], limits: &Limits) -> Result<DeepImage, Codec
|
||||
/// format, oversize image) return an error.
|
||||
pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result<Vec<u8>, CodecError> {
|
||||
if !caps(format).write {
|
||||
return Err(CodecError::unsupported(format, "encoding is not available in this build"));
|
||||
return Err(match format {
|
||||
Format::Jxl if !cfg!(feature = "jxl-encode") => CodecError::feature_missing(format, "jxl-encode"),
|
||||
_ => unavailable(format, "encoding is not available in this build"),
|
||||
});
|
||||
}
|
||||
if image.width() == 0 || image.height() == 0 {
|
||||
return Err(CodecError::InvalidImage("cannot encode an empty image".into()));
|
||||
@@ -566,41 +634,23 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result<Vec
|
||||
Format::Png => png::encode(image, plan, opts),
|
||||
Format::Jpeg => jpeg::encode(image, plan, opts),
|
||||
Format::Tiff => tiff::encode(image, plan, opts),
|
||||
Format::WebP => webp::encode(image, plan, opts),
|
||||
Format::Pnm => pnm::encode(image, plan, opts),
|
||||
Format::WebP => gated!("webp", format, webp::encode(image, plan, opts)),
|
||||
Format::Pnm => gated!("pnm", format, pnm::encode(image, plan, opts)),
|
||||
Format::Pcx => Err(CodecError::unsupported(format, "PCX is import-only; save as PNG instead")),
|
||||
Format::Xpm => Err(CodecError::unsupported(format, "XPM is import-only; save as PNG instead")),
|
||||
Format::Dds => dds::encode(image, plan, opts),
|
||||
Format::Fits => fits::encode(image, plan, opts),
|
||||
Format::Dpx => dpx::encode(image, plan, opts),
|
||||
Format::Cineon => dpx::encode_cineon(image, plan),
|
||||
Format::Dds => gated!("dds", format, dds::encode(image, plan, opts)),
|
||||
Format::Fits => gated!("fits", format, fits::encode(image, plan, opts)),
|
||||
Format::Dpx => gated!("dpx", format, dpx::encode(image, plan, opts)),
|
||||
Format::Cineon => gated!("dpx", format, dpx::encode_cineon(image, plan)),
|
||||
Format::Dicom => Err(CodecError::unsupported(format, "DICOM is import-only; save as TIFF or PNG instead")),
|
||||
Format::Iff => iff::encode(image, plan),
|
||||
Format::SunRaster => {
|
||||
#[cfg(feature = "sunraster")]
|
||||
{
|
||||
sunraster::encode(image, plan)
|
||||
}
|
||||
#[cfg(not(feature = "sunraster"))]
|
||||
{
|
||||
Err(CodecError::unsupported(format, "Sun Raster support requires the sunraster feature"))
|
||||
}
|
||||
}
|
||||
Format::Sgi => {
|
||||
#[cfg(feature = "sgi")]
|
||||
{
|
||||
sgi::encode(image, plan)
|
||||
}
|
||||
#[cfg(not(feature = "sgi"))]
|
||||
{
|
||||
Err(CodecError::unsupported(format, "SGI support requires the sgi feature"))
|
||||
}
|
||||
}
|
||||
Format::JpegLs => jpegls::encode(image, plan),
|
||||
Format::OpenExr => exr::encode(image, plan, opts),
|
||||
Format::Iff => gated!("iff", format, iff::encode(image, plan)),
|
||||
Format::SunRaster => gated!("sunraster", format, sunraster::encode(image, plan)),
|
||||
Format::Sgi => gated!("sgi", format, sgi::encode(image, plan)),
|
||||
Format::JpegLs => gated!("jpegls", format, jpegls::encode(image, plan)),
|
||||
Format::OpenExr => gated!("exr", format, exr::encode(image, plan, opts)),
|
||||
Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")),
|
||||
Format::Jp2 => Err(CodecError::unsupported(format, "JPEG 2000 is import-only; save as PNG or TIFF instead")),
|
||||
Format::Jxl => jxl::encode(image, plan),
|
||||
Format::Jxl => gated!("jxl-encode", format, jxl::encode(image, plan)),
|
||||
// The `image` crate leaves a BMP's resolution fields 0; Photoshop fills them in. They are
|
||||
// part of the header, not metadata, so they are written whatever `embed_metadata` says.
|
||||
Format::Bmp => via_image::encode(format, image, plan, opts).map(|mut bytes| {
|
||||
|
||||
@@ -317,6 +317,7 @@ impl Default for EncodeOptions {
|
||||
/// A zero-filled buffer of `len` elements, allocated fallibly: an allocation failure becomes
|
||||
/// [`CodecError::LimitExceeded`] instead of aborting the process (which `catch_unwind` cannot
|
||||
/// stop).
|
||||
#[cfg(any(feature = "exr", feature = "iff", feature = "webp"))]
|
||||
pub(crate) fn alloc_zeroed<T: Copy + Default>(len: usize) -> Result<Vec<T>, CodecError> {
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {len} elements for the image")))?;
|
||||
|
||||
@@ -323,7 +323,12 @@ mod tests {
|
||||
}
|
||||
let mut image = crate::Image::from_u8(2, 2, crate::ChannelLayout::Rgb, vec![80; 12]).unwrap();
|
||||
image.meta.exif = Some(EXIF.to_vec());
|
||||
for format in [Format::Jpeg, Format::Png, Format::WebP] {
|
||||
for format in [
|
||||
Format::Jpeg,
|
||||
Format::Png,
|
||||
#[cfg(feature = "webp")]
|
||||
Format::WebP,
|
||||
] {
|
||||
let encoded = crate::encode(&image, format, &crate::EncodeOptions::default()).unwrap();
|
||||
for at in 0..encoded.len() {
|
||||
for value in [0, 255] {
|
||||
@@ -363,7 +368,12 @@ mod tests {
|
||||
fn explicit_replacements_preserve_raw_orientation_in_real_encodings() {
|
||||
let mut image = crate::Image::from_u8(2, 2, crate::ChannelLayout::Rgb, vec![80; 12]).unwrap();
|
||||
image.meta.exif = Some(EXIF.to_vec());
|
||||
for format in [Format::Jpeg, Format::Png, Format::WebP] {
|
||||
for format in [
|
||||
Format::Jpeg,
|
||||
Format::Png,
|
||||
#[cfg(feature = "webp")]
|
||||
Format::WebP,
|
||||
] {
|
||||
let mut bytes = crate::encode(&image, format, &crate::EncodeOptions::default()).unwrap();
|
||||
let normal = crate::decode_as_with(format, &bytes, &crate::DecodeOptions { keep_orientation: true, ..Default::default() }).unwrap();
|
||||
assert_eq!(normal.meta.exif.as_deref().map(crate::exif_orientation), Some(1), "default {format:?}");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use super::{MAX_PPI, file_resolution, usable};
|
||||
#[cfg(feature = "webp")]
|
||||
use crate::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
|
||||
|
||||
/// A little- or big-endian classic TIFF whose IFD0 holds XResolution and YResolution
|
||||
@@ -153,6 +154,7 @@ fn png_phys_in_metres_only_before_image_data() {
|
||||
|
||||
/// What the probe reads is what a full decode reports, for each format the encoder writes with
|
||||
/// a resolution.
|
||||
#[cfg(feature = "webp")]
|
||||
#[test]
|
||||
fn agrees_with_decode_for_encoded_files() {
|
||||
let mut img = Image::from_raw(2, 1, ChannelLayout::Rgb, SampleType::U8, vec![10, 20, 30, 40, 50, 60]).unwrap();
|
||||
@@ -165,6 +167,7 @@ fn agrees_with_decode_for_encoded_files() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
#[test]
|
||||
fn webp_without_exif_has_none() {
|
||||
let img = Image::from_raw(1, 1, ChannelLayout::Rgb, SampleType::U8, vec![1, 2, 3]).unwrap();
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
//!
|
||||
//! Everything here reads hostile bytes: every index is checked and a malformed file gives `None`.
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
use crate::codecs::vp8;
|
||||
|
||||
/// ITU-T T.81 Annex K.1, the example luminance quantisation table, in natural (row) order.
|
||||
@@ -146,6 +147,7 @@ fn read_dqt(mut seg: &[u8], tables: &mut [Option<Table>; 4]) {
|
||||
}
|
||||
|
||||
/// How a WebP file's image is compressed.
|
||||
#[cfg(feature = "webp")]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum WebpEncoding {
|
||||
/// VP8L.
|
||||
@@ -157,6 +159,7 @@ pub enum WebpEncoding {
|
||||
|
||||
/// The compression of a WebP file's (first) image, or `None` when it isn't a WebP or holds no
|
||||
/// image chunk.
|
||||
#[cfg(feature = "webp")]
|
||||
pub fn webp_encoding(bytes: &[u8]) -> Option<WebpEncoding> {
|
||||
if bytes.get(..4) != Some(b"RIFF") || bytes.get(8..12) != Some(b"WEBP") {
|
||||
return None;
|
||||
@@ -165,6 +168,7 @@ pub fn webp_encoding(bytes: &[u8]) -> Option<WebpEncoding> {
|
||||
}
|
||||
|
||||
/// The first `VP8 ` or `VP8L` chunk among `chunks`, looking inside animation frames.
|
||||
#[cfg(feature = "webp")]
|
||||
fn find_image_chunk(mut chunks: &[u8], depth: u8) -> Option<WebpEncoding> {
|
||||
while let Some(head) = chunks.get(..8) {
|
||||
let fourcc = head.get(..4)?;
|
||||
@@ -190,6 +194,7 @@ fn find_image_chunk(mut chunks: &[u8], depth: u8) -> Option<WebpEncoding> {
|
||||
|
||||
/// The quality a VP8 key frame's base quantiser index maps back to on our encoder's scale (the
|
||||
/// quality whose index is nearest; the middle one when several share it).
|
||||
#[cfg(feature = "webp")]
|
||||
fn vp8_quality(frame: &[u8]) -> Option<u8> {
|
||||
let qi = vp8_base_quantizer(frame)?;
|
||||
let distance = |q: u8| vp8::quantizer_index(q).abs_diff(qi);
|
||||
@@ -202,6 +207,7 @@ fn vp8_quality(frame: &[u8]) -> Option<u8> {
|
||||
/// The base quantiser index of a VP8 key frame: `y_ac_qi` from its frame header (RFC 6386
|
||||
/// §9.2–9.6, §19.2), averaged over the segments when segmentation sets absolute quantisers or
|
||||
/// adjusted by their mean delta otherwise.
|
||||
#[cfg(feature = "webp")]
|
||||
fn vp8_base_quantizer(frame: &[u8]) -> Option<u8> {
|
||||
let tag = frame.get(..3)?;
|
||||
// Bit 0 clear: a key frame, which carries the start code and dimensions.
|
||||
@@ -260,6 +266,7 @@ fn vp8_base_quantizer(frame: &[u8]) -> Option<u8> {
|
||||
}
|
||||
|
||||
/// RFC 6386 §7's boolean decoder, reading zeros past the end of its data.
|
||||
#[cfg(feature = "webp")]
|
||||
struct BoolDecoder<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
@@ -270,6 +277,7 @@ struct BoolDecoder<'a> {
|
||||
overrun: usize,
|
||||
}
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
impl<'a> BoolDecoder<'a> {
|
||||
fn new(data: &'a [u8]) -> Self {
|
||||
let mut d = BoolDecoder { data, pos: 0, value: 0, range: 255, bit_count: 0, overrun: 0 };
|
||||
|
||||
@@ -89,8 +89,9 @@ mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn reads_first_directory_and_enforces_limits_and_bounds() {
|
||||
let image = crate::Image::from_u8(2, 3, crate::ChannelLayout::Rgb, vec![42; 18]).unwrap();
|
||||
let bytes = crate::encode(&image, crate::Format::Tiff, &crate::EncodeOptions::default()).unwrap();
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
tiff::encoder::TiffEncoder::new(&mut out).unwrap().write_image::<tiff::encoder::colortype::RGB8>(2, 3, &[42; 18]).unwrap();
|
||||
let bytes = out.into_inner();
|
||||
assert_eq!(header(&bytes, 6).unwrap(), (2, 3, 1));
|
||||
let info = decode_info(&bytes, 6).unwrap();
|
||||
assert_eq!((info.width, info.height, info.bit_depth), (2, 3, 8));
|
||||
|
||||
@@ -4,6 +4,7 @@ use crate::{CodecError, Format};
|
||||
|
||||
/// Stored width, height and EXIF orientation without decoding pixels. The image payload must
|
||||
/// fit in the input, but its compressed contents are not validated. Uses the default decode limits.
|
||||
#[cfg(feature = "webp")]
|
||||
pub fn header(bytes: &[u8]) -> Result<(u32, u32, u16), CodecError> {
|
||||
let err = |s: &str| CodecError::malformed(Format::WebP, s);
|
||||
let mut p = 12usize;
|
||||
@@ -51,7 +52,7 @@ pub fn has_alpha(bytes: &[u8]) -> Result<bool, CodecError> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, feature = "webp"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
|
||||
@@ -183,6 +183,7 @@ fn apng_warns_and_keeps_the_first_frame() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
fn chunk(id: &[u8; 4], data: &[u8]) -> Vec<u8> {
|
||||
let mut c = id.to_vec();
|
||||
c.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
@@ -193,12 +194,14 @@ fn chunk(id: &[u8; 4], data: &[u8]) -> Vec<u8> {
|
||||
c
|
||||
}
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
fn u24(v: u32) -> [u8; 3] {
|
||||
let b = v.to_le_bytes();
|
||||
[b[0], b[1], b[2]]
|
||||
}
|
||||
|
||||
/// An animated WebP: each frame is a full-canvas lossless still wrapped in an ANMF chunk.
|
||||
#[cfg(feature = "webp")]
|
||||
fn animated_webp(frames: &[Image]) -> Vec<u8> {
|
||||
let mut body = b"WEBP".to_vec();
|
||||
let mut vp8x = vec![0x02, 0, 0, 0]; // animation flag
|
||||
@@ -224,6 +227,7 @@ fn animated_webp(frames: &[Image]) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
#[test]
|
||||
fn animated_webp_warns_and_keeps_the_first_frame() {
|
||||
let frames: Vec<Image> = COLOURS.iter().map(|&c| solid(c)).collect();
|
||||
@@ -240,6 +244,7 @@ fn animated_webp_warns_and_keeps_the_first_frame() {
|
||||
}
|
||||
|
||||
/// A TIFF with one IFD per entry: `(NewSubfileType, sample type)`.
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff(ifds: &[(u32, SampleType)]) -> Vec<u8> {
|
||||
use tiff::encoder::{TiffEncoder, colortype};
|
||||
use tiff::tags::Tag;
|
||||
@@ -268,6 +273,7 @@ fn tiff(ifds: &[(u32, SampleType)]) -> Vec<u8> {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn multi_page_tiff_warns_and_keeps_the_first_page() {
|
||||
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let one = decode(&tiff(&[(0, sample)])).unwrap();
|
||||
@@ -282,6 +288,7 @@ fn multi_page_tiff_warns_and_keeps_the_first_page() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff_thumbnails_and_masks_are_not_pages() {
|
||||
let u8 = SampleType::U8;
|
||||
// A reduced-resolution copy (bit 0) or a transparency mask (bit 2) is part of the page.
|
||||
@@ -309,6 +316,7 @@ fn warnings_survive_orientation() {
|
||||
assert_eq!(img.convert(ChannelLayout::Rgba, SampleType::U16).warnings, img.warnings);
|
||||
}
|
||||
|
||||
#[cfg(feature = "dds")]
|
||||
/// A flagless depth still declares slices the flat reader and writer cannot retain.
|
||||
#[test]
|
||||
fn dds_depth_probe_refuses_unretained_slices_without_volume_flags() {
|
||||
@@ -336,6 +344,7 @@ fn dds_depth_probe_refuses_unretained_slices_without_volume_flags() {
|
||||
#[test]
|
||||
fn additional_images_probe_uses_container_structure_without_decoding_pixels() {
|
||||
use craft_image_codecs::has_unretained_source_data;
|
||||
#[cfg(feature = "webp")]
|
||||
let frames: Vec<_> = COLOURS.iter().take(2).map(|&c| solid(c)).collect();
|
||||
for (bytes, multiple) in [
|
||||
(gif(1), false),
|
||||
@@ -344,14 +353,23 @@ fn additional_images_probe_uses_container_structure_without_decoding_pixels() {
|
||||
(apng(1, false, false), false),
|
||||
(apng(1, false, true), true),
|
||||
(apng(2, true, false), true),
|
||||
#[cfg(feature = "webp")]
|
||||
(animated_webp(&frames[..1]), false),
|
||||
#[cfg(feature = "webp")]
|
||||
(animated_webp(&frames), true),
|
||||
#[cfg(feature = "tiff")]
|
||||
(tiff(&[(0, SampleType::U8)]), false),
|
||||
#[cfg(feature = "tiff")]
|
||||
(tiff(&[(0, SampleType::U8), (2, SampleType::U8)]), true),
|
||||
#[cfg(feature = "tiff")]
|
||||
(tiff(&[(0, SampleType::U8), (1, SampleType::U8)]), false),
|
||||
#[cfg(feature = "tiff")]
|
||||
(tiff(&[(4, SampleType::U8)]), false),
|
||||
#[cfg(feature = "tiff")]
|
||||
(tiff(&[(0, SampleType::U8), (4, SampleType::U8)]), true),
|
||||
#[cfg(feature = "tiff")]
|
||||
(tiff(&[(4, SampleType::U8), (0, SampleType::U8)]), true),
|
||||
#[cfg(feature = "tiff")]
|
||||
(tiff(&[(0, SampleType::U8), (1, SampleType::U8), (4, SampleType::U8)]), true),
|
||||
] {
|
||||
assert_eq!(has_unretained_source_data(&bytes).unwrap(), multiple);
|
||||
@@ -368,6 +386,7 @@ fn additional_images_probe_uses_container_structure_without_decoding_pixels() {
|
||||
assert!(has_unretained_source_data(&broken).is_err(), "junk block after the first frame");
|
||||
assert!(has_unretained_source_data(&two[..two.len() - 1]).unwrap(), "two frames seen, trailer cut off");
|
||||
let image = solid(COLOURS[0]);
|
||||
#[cfg(feature = "dds")]
|
||||
for mipmaps in [false, true] {
|
||||
let mut options = EncodeOptions::default();
|
||||
options.dds.mipmaps = mipmaps;
|
||||
@@ -382,7 +401,9 @@ fn additional_images_probe_uses_container_structure_without_decoding_pixels() {
|
||||
assert!(has_unretained_source_data(&flagless).unwrap());
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "dpx")]
|
||||
let dpx = encode(&image, Format::Dpx, &Default::default()).unwrap();
|
||||
#[cfg(feature = "dpx")]
|
||||
for little in [false, true] {
|
||||
let mut bytes = dpx.clone();
|
||||
if little {
|
||||
@@ -418,6 +439,7 @@ fn additional_images_probe_uses_container_structure_without_decoding_pixels() {
|
||||
assert!(has_unretained_source_data(b"\x89PNG\r\n\x1a\n").is_err());
|
||||
}
|
||||
|
||||
#[cfg(feature = "fits")]
|
||||
/// FITS RGB planes form one image; other cubes and later image HDUs would be discarded.
|
||||
#[test]
|
||||
fn fits_additional_images_probe_distinguishes_color_planes_and_hdus() {
|
||||
@@ -456,6 +478,7 @@ fn fits_additional_images_probe_distinguishes_color_planes_and_hdus() {
|
||||
}
|
||||
|
||||
/// Tables and extension heaps are source data even though the flat image decoder skips them.
|
||||
#[cfg(feature = "fits")]
|
||||
#[test]
|
||||
fn fits_source_probe_preserves_nonimage_payload_and_allows_empty_extensions() {
|
||||
let primary = encode(&solid(COLOURS[0]), Format::Fits, &Default::default()).unwrap();
|
||||
|
||||
@@ -48,24 +48,34 @@ fn feature_config_default_build_formats_all_symmetric() {
|
||||
let expected = [
|
||||
Format::Png,
|
||||
Format::Jpeg,
|
||||
#[cfg(feature = "tiff")]
|
||||
Format::Tiff,
|
||||
#[cfg(feature = "webp")]
|
||||
Format::WebP,
|
||||
Format::Gif,
|
||||
Format::Bmp,
|
||||
#[cfg(feature = "tga")]
|
||||
Format::Tga,
|
||||
Format::Ico,
|
||||
#[cfg(feature = "pnm")]
|
||||
Format::Pnm,
|
||||
Format::Qoi,
|
||||
#[cfg(feature = "exr")]
|
||||
Format::OpenExr,
|
||||
Format::Hdr,
|
||||
#[cfg(feature = "fits")]
|
||||
Format::Fits,
|
||||
#[cfg(feature = "dpx")]
|
||||
Format::Dpx,
|
||||
#[cfg(feature = "dpx")]
|
||||
Format::Cineon,
|
||||
#[cfg(feature = "iff")]
|
||||
Format::Iff,
|
||||
#[cfg(feature = "sunraster")]
|
||||
Format::SunRaster,
|
||||
#[cfg(feature = "sgi")]
|
||||
Format::Sgi,
|
||||
#[cfg(feature = "jpegls")]
|
||||
Format::JpegLs,
|
||||
];
|
||||
for f in expected {
|
||||
@@ -234,7 +244,7 @@ fn detect_magic_cineon() {
|
||||
b[0..4].copy_from_slice(&[0x80, 0x2A, 0x5F, 0xD7]);
|
||||
assert_eq!(detect(&b), Some(Format::Cineon));
|
||||
assert_eq!(from_extension("scan.CIN"), Some(Format::Cineon));
|
||||
assert!(caps(Format::Cineon).read && caps(Format::Cineon).write, "Cineon is read and written");
|
||||
assert_eq!(caps(Format::Cineon).read && caps(Format::Cineon).write, cfg!(feature = "dpx"), "Cineon is read and written");
|
||||
assert!(!ASYMMETRIC_EXCEPTIONS.iter().any(|(f, _)| *f == Format::Cineon));
|
||||
// A bare magic is an error, never a panic.
|
||||
assert!(decode_as(Format::Cineon, &b).is_err());
|
||||
@@ -247,7 +257,7 @@ fn detect_magic_iff() {
|
||||
assert_eq!(detect(b"FORM\0\0\0\x14PBM "), Some(Format::Iff));
|
||||
assert_eq!(from_extension("art.LBM"), Some(Format::Iff));
|
||||
assert_eq!(from_extension("art.ilbm"), Some(Format::Iff));
|
||||
assert!(caps(Format::Iff).read && caps(Format::Iff).write, "IFF is read and written");
|
||||
assert_eq!(caps(Format::Iff).read && caps(Format::Iff).write, cfg!(feature = "iff"), "IFF is read and written");
|
||||
assert!(caps(Format::Iff).alpha);
|
||||
assert!(caps(Format::Iff).layouts.contains(&craft_image_codecs::ChannelLayout::Rgba));
|
||||
assert!(!ASYMMETRIC_EXCEPTIONS.iter().any(|(f, _)| *f == Format::Iff));
|
||||
@@ -273,6 +283,7 @@ fn feature_config_detect_magic_sgi() {
|
||||
assert!(decode_as(Format::Sgi, &[0x01, 0xda]).is_err());
|
||||
}
|
||||
|
||||
#[cfg(feature = "jpegls")]
|
||||
#[test]
|
||||
fn detect_magic_jpeg_ls() {
|
||||
use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, encode};
|
||||
@@ -289,6 +300,7 @@ fn detect_magic_jpeg_ls() {
|
||||
}
|
||||
|
||||
/// `file` with `count` marker segments of `body` bytes each inserted right after its SOI.
|
||||
#[cfg(feature = "jpegls")]
|
||||
fn with_segments(file: &[u8], marker: u8, count: usize, body: usize) -> Vec<u8> {
|
||||
let mut out = file[..2].to_vec();
|
||||
for i in 0..count {
|
||||
@@ -300,6 +312,7 @@ fn with_segments(file: &[u8], marker: u8, count: usize, body: usize) -> Vec<u8>
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(feature = "jpegls")]
|
||||
fn jpeg_ls_file() -> (Image, Vec<u8>) {
|
||||
let img = Image::from_u8(5, 3, ChannelLayout::Gray, (0..15).collect()).unwrap();
|
||||
let bytes = encode(&img, Format::JpegLs, &EncodeOptions::default()).unwrap();
|
||||
@@ -308,6 +321,7 @@ fn jpeg_ls_file() -> (Image, Vec<u8>) {
|
||||
|
||||
/// Grows a prefix of `bytes` as a [`PrefixDetector`] asks, starting from `first` bytes, and checks
|
||||
/// each answer against [`detect_prefix`].
|
||||
#[cfg(feature = "jpegls")]
|
||||
fn detect_by_prefix(bytes: &[u8], first: usize) -> Detection {
|
||||
let mut detector = PrefixDetector::new();
|
||||
let mut len = first.min(bytes.len());
|
||||
@@ -324,6 +338,7 @@ fn detect_by_prefix(bytes: &[u8], first: usize) -> Detection {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "jpegls")]
|
||||
#[test]
|
||||
fn jpeg_ls_after_a_long_comment_needs_the_frame_header() {
|
||||
let (img, plain) = jpeg_ls_file();
|
||||
@@ -338,6 +353,7 @@ fn jpeg_ls_after_a_long_comment_needs_the_frame_header() {
|
||||
assert_eq!(detect_prefix(&bytes), Detection::Format(Format::JpegLs));
|
||||
}
|
||||
|
||||
#[cfg(feature = "jpegls")]
|
||||
#[test]
|
||||
fn jpeg_ls_after_many_segments_is_still_jpeg_ls() {
|
||||
// An ICC profile can span 255 APP2 segments.
|
||||
@@ -352,6 +368,7 @@ fn jpeg_ls_after_many_segments_is_still_jpeg_ls() {
|
||||
assert_eq!(detect_by_prefix(&jpeg, 64), Detection::Format(Format::Jpeg));
|
||||
}
|
||||
|
||||
#[cfg(feature = "jpegls")]
|
||||
#[test]
|
||||
fn a_cut_off_jpeg_asks_for_more_bytes() {
|
||||
let (_, plain) = jpeg_ls_file();
|
||||
@@ -372,6 +389,7 @@ fn a_cut_off_jpeg_asks_for_more_bytes() {
|
||||
assert_eq!(detect_prefix(&[]), Detection::Unknown);
|
||||
}
|
||||
|
||||
#[cfg(feature = "jpegls")]
|
||||
#[test]
|
||||
fn a_restart_interval_before_the_frame_header_is_jpeg_ls() {
|
||||
// A DRI segment may come before the frame header. An interval of 0 turns restarts off.
|
||||
@@ -404,6 +422,7 @@ fn a_restart_interval_before_the_frame_header_is_jpeg_ls() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "jpegls")]
|
||||
#[test]
|
||||
fn the_restart_interval_in_effect_at_the_scan_decides_decoding() {
|
||||
// The 5x3 file's frame header ends at byte 15, where its scan header starts.
|
||||
@@ -430,6 +449,7 @@ fn the_restart_interval_in_effect_at_the_scan_decides_decoding() {
|
||||
assert!(matches!(decode(&with_dri(&[0, 2])), Err(CodecError::Unsupported { .. })));
|
||||
}
|
||||
|
||||
#[cfg(feature = "jpegls")]
|
||||
#[test]
|
||||
fn each_component_scan_uses_the_restart_interval_in_effect_at_it() {
|
||||
// The 5x3 RGB file codes each component in its own scan.
|
||||
@@ -452,6 +472,7 @@ fn each_component_scan_uses_the_restart_interval_in_effect_at_it() {
|
||||
assert!(matches!(decode(&with_dri(3, 2)), Err(CodecError::Unsupported { .. })));
|
||||
}
|
||||
|
||||
#[cfg(feature = "jpegls")]
|
||||
#[test]
|
||||
fn a_restart_marker_after_a_scan_of_one_interval_is_an_error() {
|
||||
// With an interval of 3 lines the 5x3 scan is one interval, which no restart marker follows.
|
||||
@@ -470,6 +491,7 @@ fn a_restart_marker_after_a_scan_of_one_interval_is_an_error() {
|
||||
assert!(decode(&bytes).is_err());
|
||||
}
|
||||
|
||||
#[cfg(feature = "jpegls")]
|
||||
#[test]
|
||||
fn a_restart_marker_after_a_comment_is_an_error_while_an_interval_is_set() {
|
||||
let (img, plain) = jpeg_ls_file();
|
||||
@@ -548,7 +570,8 @@ fn detect_magic_dicom() {
|
||||
assert_eq!(detect(&b), Some(Format::Dicom));
|
||||
assert_eq!(from_extension("scan.DCM"), Some(Format::Dicom));
|
||||
assert_eq!(from_extension("scan.dc3"), Some(Format::Dicom));
|
||||
assert!(caps(Format::Dicom).read && !caps(Format::Dicom).write);
|
||||
assert_eq!(caps(Format::Dicom).read, cfg!(feature = "dicom"));
|
||||
assert!(!caps(Format::Dicom).write);
|
||||
assert!(ASYMMETRIC_EXCEPTIONS.iter().any(|(f, _)| *f == Format::Dicom));
|
||||
// A bare magic is an error, never a panic.
|
||||
assert!(decode_as(Format::Dicom, &b).is_err());
|
||||
@@ -648,3 +671,61 @@ fn feature_config_sun_raster_disabled_by_default() {
|
||||
let image = Image::from_u8(1, 1, ChannelLayout::Gray, vec![42]).unwrap();
|
||||
assert!(encode(&image, Format::SunRaster, &EncodeOptions::default()).is_err());
|
||||
}
|
||||
|
||||
/// A codec the build leaves out still has its files detected, and reading, writing or inspecting
|
||||
/// one is refused with the missing feature named.
|
||||
#[test]
|
||||
fn formats_left_out_of_the_build_are_detected_and_refused_by_name() {
|
||||
let mut dicom = vec![0u8; 128];
|
||||
dicom.extend_from_slice(b"DICM");
|
||||
let samples: [(Format, &str, bool, Vec<u8>); 12] = [
|
||||
(Format::Dds, "dds", cfg!(feature = "dds"), b"DDS \x7c\0\0\0".to_vec()),
|
||||
(Format::Dicom, "dicom", cfg!(feature = "dicom"), dicom),
|
||||
(Format::Dpx, "dpx", cfg!(feature = "dpx"), b"SDPX\0\0\0\0".to_vec()),
|
||||
(Format::Cineon, "dpx", cfg!(feature = "dpx"), vec![0x80, 0x2A, 0x5F, 0xD7, 0, 0, 0, 0]),
|
||||
(Format::OpenExr, "exr", cfg!(feature = "exr"), vec![0x76, 0x2F, 0x31, 0x01, 2, 0, 0, 0]),
|
||||
(Format::Fits, "fits", cfg!(feature = "fits"), b"SIMPLE = T".to_vec()),
|
||||
(Format::Iff, "iff", cfg!(feature = "iff"), b"FORM\0\0\0\x14ILBM".to_vec()),
|
||||
(Format::JpegLs, "jpegls", cfg!(feature = "jpegls"), vec![0xFF, 0xD8, 0xFF, 0xF7, 0, 11]),
|
||||
(Format::Pnm, "pnm", cfg!(feature = "pnm"), b"P6 1 1 255 abc".to_vec()),
|
||||
(Format::WebP, "webp", cfg!(feature = "webp"), b"RIFF\x04\0\0\0WEBP".to_vec()),
|
||||
(Format::Xpm, "xpm", cfg!(feature = "xpm"), b"/* XPM */".to_vec()),
|
||||
(Format::Jxl, "jxl-encode", cfg!(feature = "jxl-encode"), vec![0xFF, 0x0A, 0, 0]),
|
||||
];
|
||||
let image = Image::from_u8(1, 1, ChannelLayout::Rgb, vec![1, 2, 3]).unwrap();
|
||||
let names_feature = |r: Result<_, CodecError>, f: Format, feature: &str| matches!(r, Err(CodecError::Unsupported { format, reason }) if format == f && reason.contains(feature));
|
||||
for (format, feature, enabled, bytes) in samples {
|
||||
assert_eq!(detect(&bytes), Some(format), "{feature}");
|
||||
if enabled {
|
||||
continue;
|
||||
}
|
||||
assert!(!caps(format).write, "{feature}");
|
||||
assert!(names_feature(encode(&image, format, &EncodeOptions::default()).map(drop), format, feature), "{feature}");
|
||||
if format != Format::Jxl {
|
||||
assert!(!caps(format).read, "{feature}");
|
||||
assert!(names_feature(decode(&bytes).map(drop), format, feature), "{feature}");
|
||||
assert!(names_feature(probe_size(&bytes).map(drop), format, feature), "{feature}");
|
||||
assert!(names_feature(has_unretained_source_data(&bytes).map(drop), format, feature), "{feature}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_inspection_requires_the_decoder_even_when_encoding_is_enabled() {
|
||||
// Original synthetic magic headers: inspection must reject a missing decoder before parsing.
|
||||
let cases: &[(Format, &str, bool, &[u8])] = &[
|
||||
(Format::Jxl, "jxl", cfg!(feature = "jxl"), &[0xFF, 0x0A, 0, 0]),
|
||||
(Format::Heif, "heif", cfg!(feature = "heif"), b"\0\0\0\x14ftypheic\0\0\0\0heic"),
|
||||
(Format::Avif, "avif-decode", cfg!(feature = "avif-decode"), b"\0\0\0\x14ftypavif\0\0\0\0avif"),
|
||||
];
|
||||
for &(format, feature, enabled, bytes) in cases {
|
||||
assert_eq!(detect(bytes), Some(format));
|
||||
if !enabled {
|
||||
assert!(
|
||||
matches!(has_unretained_source_data(bytes), Err(CodecError::Unsupported { format: found, reason })
|
||||
if found == format && reason.contains(feature)),
|
||||
"{format:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ fn png_u16_rgba_is_clean() {
|
||||
assert!(warns(&test_image(ChannelLayout::Rgba, SampleType::U16), Format::Png).is_empty());
|
||||
}
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff_is_clean_for_all_integer_and_f32_layouts() {
|
||||
for l in ChannelLayout::ALL {
|
||||
for s in [SampleType::U8, SampleType::U16, SampleType::F32, SampleType::F16] {
|
||||
@@ -64,6 +65,7 @@ fn cmyk_to_png_converted() {
|
||||
let w = warns(&test_image(ChannelLayout::Cmyk, SampleType::U8), Format::Png);
|
||||
assert!(w.contains(&W::CmykConverted { to: ChannelLayout::Rgb }));
|
||||
}
|
||||
#[cfg(feature = "webp")]
|
||||
#[test]
|
||||
fn cmyka_to_webp_converted_keeps_alpha() {
|
||||
let w = warns(&test_image(ChannelLayout::CmykA, SampleType::U8), Format::WebP);
|
||||
@@ -104,6 +106,7 @@ fn exif_xmp_dpi_text_dropped_for_qoi() {
|
||||
assert!(w.contains(&x), "{x:?}");
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "webp")]
|
||||
/// WebP keeps the resolution in EXIF (#2399); only free-form text has nowhere to go.
|
||||
#[test]
|
||||
fn webp_drops_text_only() {
|
||||
@@ -131,28 +134,33 @@ fn in_range_float_not_clipped() {
|
||||
let w = warns(&test_image(ChannelLayout::Rgb, SampleType::F32), Format::Png);
|
||||
assert!(!w.contains(&W::RangeClipped));
|
||||
}
|
||||
#[cfg(feature = "fits")]
|
||||
#[test]
|
||||
fn hdr_float_to_fits_clips() {
|
||||
let img = Image::from_f32(2, 1, ChannelLayout::Gray, &[0.5, 3.0]).unwrap();
|
||||
assert!(warns(&img, Format::Fits).contains(&W::RangeClipped));
|
||||
assert!(!warns(&test_image(ChannelLayout::Gray, SampleType::F32), Format::Fits).contains(&W::RangeClipped));
|
||||
}
|
||||
#[cfg(all(feature = "exr", feature = "pnm"))]
|
||||
#[test]
|
||||
fn float_to_exr_and_tiff_is_clean() {
|
||||
for f in [Format::OpenExr, Format::Tiff, Format::Pnm] {
|
||||
assert!(warns(&test_image(ChannelLayout::Rgb, SampleType::F32), f).is_empty(), "{f:?}");
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "exr")]
|
||||
#[test]
|
||||
fn f16_to_exr_is_clean() {
|
||||
assert!(warns(&test_image(ChannelLayout::Rgba, SampleType::F16), Format::OpenExr).is_empty());
|
||||
}
|
||||
#[cfg(feature = "exr")]
|
||||
#[test]
|
||||
fn integer_to_exr_is_lossless() {
|
||||
for s in [SampleType::U8, SampleType::U16] {
|
||||
assert!(warns(&test_image(ChannelLayout::Rgb, s), Format::OpenExr).is_empty(), "{s:?}");
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "pnm")]
|
||||
#[test]
|
||||
fn float_pnm_drops_alpha() {
|
||||
let w = warns(&test_image(ChannelLayout::Rgba, SampleType::F32), Format::Pnm);
|
||||
@@ -165,6 +173,7 @@ fn gif_quantizes_and_binarizes() {
|
||||
assert!(w.contains(&W::AlphaBinarized));
|
||||
assert!(!w.contains(&W::LossyCompression));
|
||||
}
|
||||
#[cfg(feature = "iff")]
|
||||
#[test]
|
||||
fn iff_binarizes_alpha_and_reduces_16_bit() {
|
||||
assert_eq!(warns(&test_image(ChannelLayout::Rgba, SampleType::U8), Format::Iff), vec![W::AlphaBinarized]);
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
//! JPEG 2000 decode is default-on: without the `jp2` feature a JP2 file is detected and refused with a
|
||||
//! named reason rather than decoded, so a crate that only reads SVG keeps no JPEG 2000 decoder.
|
||||
|
||||
use craft_image_codecs::*;
|
||||
|
||||
/// JP2 signature box and file type box, and nothing else.
|
||||
const JP2_HEAD: &[u8] = b"\0\0\0\x0cjP \r\n\x87\n\0\0\0\x14ftypjp2 \0\0\0\0jp2 ";
|
||||
|
||||
#[test]
|
||||
fn a_jp2_file_is_detected_without_the_feature() {
|
||||
assert_eq!(detect(JP2_HEAD), Some(Format::Jp2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_jp2_file_is_refused_with_the_feature_named() {
|
||||
let err = decode_with(JP2_HEAD, &DecodeOptions::default()).expect_err("no image in a bare header");
|
||||
if cfg!(feature = "jp2") {
|
||||
// With the feature the bare header reaches the decoder and fails as undecodable.
|
||||
assert!(matches!(err, CodecError::Malformed { .. } | CodecError::InvalidImage(_)), "decodes as far as the decoder: {err:?}");
|
||||
} else {
|
||||
match err {
|
||||
CodecError::Unsupported { format, reason } => {
|
||||
assert_eq!(format, Format::Jp2);
|
||||
assert!(reason.contains("jp2 feature"), "reason names the feature: {reason}");
|
||||
}
|
||||
other => panic!("expected an unsupported format error, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! JPEG XL decode through craft-jxl: lossless round trips, metadata, and hostile containers.
|
||||
#![cfg(feature = "jxl")]
|
||||
// The files are made with our JPEG XL encoder.
|
||||
#![cfg(all(feature = "jxl", feature = "jxl-encode"))]
|
||||
|
||||
use craft_image_codecs::{ChannelLayout, CodecError, DecodeOptions, EncodeOptions, Format, Image, Limits, SampleType, decode, decode_with, encode};
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
//! Lossless JPEG XL export and honest export-only capability reporting.
|
||||
|
||||
use craft_image_codecs::{
|
||||
ASYMMETRIC_EXCEPTIONS, ChannelLayout, CodecError, EncodeOptions, Format, Image, SampleType, caps, decode, detect, encode, from_extension,
|
||||
};
|
||||
use craft_image_codecs::{ASYMMETRIC_EXCEPTIONS, ChannelLayout, CodecError, Format, SampleType, caps, decode, detect, from_extension};
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
use craft_image_codecs::{EncodeOptions, Image, encode};
|
||||
|
||||
#[test]
|
||||
fn feature_config_jpeg_xl_is_export_only_without_the_jxl_feature_and_detects_both_signatures() {
|
||||
let c = caps(Format::Jxl);
|
||||
assert!(c.write);
|
||||
assert_eq!(c.write, cfg!(feature = "jxl-encode"));
|
||||
assert_eq!(c.read, cfg!(feature = "jxl"));
|
||||
assert_eq!(c.depths, &[SampleType::U8, SampleType::U16]);
|
||||
assert_eq!(c.layouts, &[ChannelLayout::Gray, ChannelLayout::Rgb, ChannelLayout::Rgba]);
|
||||
@@ -27,6 +27,7 @@ fn feature_config_jpeg_xl_is_export_only_without_the_jxl_feature_and_detects_bot
|
||||
assert!(matches!(err, Err(CodecError::Malformed { format: Format::Jxl, .. })), "{err:?}");
|
||||
}
|
||||
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
#[test]
|
||||
fn jpeg_xl_encoding_is_deterministic_and_converts_float_to_integer() {
|
||||
let input =
|
||||
@@ -42,6 +43,7 @@ fn jpeg_xl_encoding_is_deterministic_and_converts_float_to_integer() {
|
||||
assert_eq!(detect(&bytes), Some(Format::Jxl));
|
||||
}
|
||||
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn jpeg_xl_decodes_losslessly_with_independent_decoder() {
|
||||
@@ -86,6 +88,7 @@ fn jpeg_xl_decodes_losslessly_with_independent_decoder() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn jpeg_xl_preserves_sixteen_bit_alpha_across_dimension_header_sizes() {
|
||||
@@ -110,6 +113,7 @@ fn jpeg_xl_preserves_sixteen_bit_alpha_across_dimension_header_sizes() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "jxl-encode")]
|
||||
#[test]
|
||||
fn jpeg_xl_rejects_one_pixel_images_without_panicking() {
|
||||
// zune-jpegxl currently requires at least two pixels on each axis.
|
||||
|
||||
@@ -400,6 +400,7 @@ fn png_invalid_optional_text_does_not_spend_an_exhausted_budget() {
|
||||
assert_eq!(image.meta.text[0].1.len(), PNG_TEXT_BUDGET - 1);
|
||||
}
|
||||
|
||||
#[cfg(feature = "pnm")]
|
||||
#[test]
|
||||
fn pnm_bomb_header_rejected() {
|
||||
assert!(is_limit(decode(b"P6\n200000 200000\n255\n\0\0\0")));
|
||||
@@ -442,6 +443,7 @@ fn pnm_header_sizes_that_overflow_usize_are_errors_without_limits() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "pnm")]
|
||||
#[test]
|
||||
fn ascii_pnm_with_the_tightest_layout_still_decodes() {
|
||||
// The capacity bound for #1110 must not cut off files with no slack: PBM digits need no
|
||||
@@ -460,6 +462,7 @@ fn jpeg_bomb_header_rejected() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff_bomb_header_rejected() {
|
||||
// Minimal little-endian TIFF claiming 1_000_000 x 1_000_000 8-bit gray.
|
||||
let mut b = b"II*\0\x08\0\0\0".to_vec();
|
||||
@@ -639,6 +642,7 @@ fn pcx_header_declaring_gigabytes_needs_a_plausible_file_size() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "xpm")]
|
||||
#[test]
|
||||
fn xpm_rows_shorter_than_the_header_declares_are_refused_before_allocating() {
|
||||
let b = b"/* XPM */\nstatic char *x[] = {\n\"30000 30000 1 1\",\n\". c #000000\",\n\".\",\n};\n".to_vec();
|
||||
@@ -648,6 +652,7 @@ fn xpm_rows_shorter_than_the_header_declares_are_refused_before_allocating() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "exr")]
|
||||
#[test]
|
||||
fn exr_header_declaring_gigabytes_needs_a_plausible_file_size() {
|
||||
let mut b = encoded(Format::OpenExr);
|
||||
@@ -658,6 +663,7 @@ fn exr_header_declaring_gigabytes_needs_a_plausible_file_size() {
|
||||
refused_as_implausible(Format::OpenExr, &b);
|
||||
}
|
||||
|
||||
#[cfg(feature = "exr")]
|
||||
#[test]
|
||||
fn a_dwab_exr_gets_a_looser_file_size_bound() {
|
||||
// DWA passes 2^16:1 (a flat 8K frame with 12 alpha-scheme mattes is about 30 KB), so a DWAB
|
||||
@@ -688,7 +694,13 @@ fn a_dwab_exr_gets_a_looser_file_size_bound() {
|
||||
fn highly_compressible_jpeg_and_gif_still_decode() {
|
||||
let side = 2048usize;
|
||||
let img = Image::from_u8(side as u32, side as u32, ChannelLayout::Rgba, vec![255u8; side * side * 4]).unwrap();
|
||||
for f in [Format::Jpeg, Format::Gif, Format::Qoi, Format::OpenExr] {
|
||||
for f in [
|
||||
Format::Jpeg,
|
||||
Format::Gif,
|
||||
Format::Qoi,
|
||||
#[cfg(feature = "exr")]
|
||||
Format::OpenExr,
|
||||
] {
|
||||
let b = encode(&img, f, &EncodeOptions::default()).unwrap();
|
||||
eprintln!("DIAG ratio {f:?}: {} bytes file, {} declared, {}:1", b.len(), side * side * 4, side * side * 4 / b.len());
|
||||
assert_eq!(decode(&b).unwrap().width() as usize, side, "{f:?}");
|
||||
|
||||
@@ -1,22 +1,33 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
mod bmp_resolution;
|
||||
#[cfg(feature = "tiff")]
|
||||
mod camera_raw;
|
||||
mod common;
|
||||
#[cfg(feature = "dds")]
|
||||
mod dds;
|
||||
#[cfg(feature = "dds")]
|
||||
mod dds_oracle;
|
||||
#[cfg(feature = "dds")]
|
||||
mod dds_write;
|
||||
mod decode_warnings;
|
||||
#[cfg(feature = "exr")]
|
||||
mod deep_exr;
|
||||
mod detect_caps;
|
||||
#[cfg(feature = "dpx")]
|
||||
mod dpx;
|
||||
#[cfg(feature = "exr")]
|
||||
mod exr_cryptomatte;
|
||||
#[cfg(feature = "exr")]
|
||||
mod exr_multipart;
|
||||
#[cfg(feature = "exr")]
|
||||
mod exr_stream;
|
||||
mod fidelity;
|
||||
mod gif_frames;
|
||||
mod heif;
|
||||
mod jp2_feature;
|
||||
mod jpeg_inks;
|
||||
#[cfg(feature = "jpegls")]
|
||||
mod jpegls_oracle;
|
||||
mod limits;
|
||||
mod malformed;
|
||||
@@ -24,24 +35,39 @@ mod metadata;
|
||||
mod orientation;
|
||||
mod pcx;
|
||||
mod png_jpeg;
|
||||
#[cfg(feature = "pnm")]
|
||||
mod pnm_headers;
|
||||
#[cfg(target_os = "linux")]
|
||||
#[cfg(all(target_os = "linux", feature = "pnm"))]
|
||||
mod pnm_peak_memory;
|
||||
mod resolution;
|
||||
mod roundtrip;
|
||||
mod source_settings;
|
||||
#[cfg(feature = "tga")]
|
||||
mod tga;
|
||||
#[cfg(feature = "tiff")]
|
||||
mod tiff_bands;
|
||||
#[cfg(feature = "tiff")]
|
||||
mod tiff_bench;
|
||||
#[cfg(feature = "tiff")]
|
||||
mod tiff_exif;
|
||||
mod tiff_feature;
|
||||
#[cfg(feature = "tiff")]
|
||||
mod tiff_lab;
|
||||
#[cfg(feature = "tiff")]
|
||||
mod tiff_pages;
|
||||
#[cfg(feature = "tiff")]
|
||||
mod tiff_photoshop;
|
||||
#[cfg(feature = "tiff")]
|
||||
mod tiff_pyramid;
|
||||
#[cfg(feature = "tiff")]
|
||||
mod tiff_regressions;
|
||||
#[cfg(feature = "tiff")]
|
||||
mod tiff_ycbcr;
|
||||
#[cfg(feature = "webp")]
|
||||
mod webp_frames;
|
||||
#[cfg(feature = "webp")]
|
||||
mod webp_lossy;
|
||||
#[cfg(feature = "xpm")]
|
||||
mod xpm;
|
||||
|
||||
mod jxl_decode;
|
||||
|
||||
@@ -145,6 +145,7 @@ fn pnm_specific_malformations() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "pnm")]
|
||||
#[test]
|
||||
fn pnm_valid_variants() {
|
||||
let img = decode(b"P1\n# comment\n3 2\n1 0 1\n0 1 0\n").unwrap();
|
||||
@@ -263,6 +264,7 @@ fn tiny_tiff(extra: &[(u16, u16, u32, u32)]) -> Vec<u8> {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff_fixture_decodes() {
|
||||
let img = decode_as_with(Format::Tiff, &tiny_tiff(&[]), &tight()).unwrap();
|
||||
assert_eq!((img.width(), img.height()), (1, 1));
|
||||
|
||||
@@ -126,7 +126,7 @@ fn hdr_metadata() {
|
||||
|
||||
#[test]
|
||||
fn metadata_on_16bit_png_and_tiff() {
|
||||
for f in [Format::Png, Format::Tiff] {
|
||||
for f in [Format::Png, Format::Tiff].into_iter().filter(|f| caps(*f).write) {
|
||||
let mut img = test_image(ChannelLayout::Rgba, SampleType::U16);
|
||||
img.icc = Some(sample_icc(512));
|
||||
img.meta.dpi = Some((72.0, 72.0));
|
||||
@@ -138,7 +138,7 @@ fn metadata_on_16bit_png_and_tiff() {
|
||||
|
||||
#[test]
|
||||
fn icc_on_cmyk_tiff_and_jpeg() {
|
||||
for f in [Format::Tiff, Format::Jpeg] {
|
||||
for f in [Format::Tiff, Format::Jpeg].into_iter().filter(|f| caps(*f).write) {
|
||||
let img = test_image(ChannelLayout::Cmyk, SampleType::U8).with_icc(Some(sample_icc(900)));
|
||||
let back = decode(&encode(&img, f, &EncodeOptions::default()).unwrap()).unwrap();
|
||||
assert_eq!(back.layout(), ChannelLayout::Cmyk, "{f:?}");
|
||||
@@ -217,7 +217,14 @@ fn jpeg_with_oversized_metadata_still_encodes() {
|
||||
fn embed_flags_disable_metadata() {
|
||||
let img = rich_image(ChannelLayout::Rgb);
|
||||
let opts = EncodeOptions { embed_icc: false, embed_metadata: false, ..Default::default() };
|
||||
for f in [Format::Png, Format::Jpeg, Format::Tiff, Format::WebP] {
|
||||
for f in [
|
||||
Format::Png,
|
||||
Format::Jpeg,
|
||||
#[cfg(feature = "tiff")]
|
||||
Format::Tiff,
|
||||
#[cfg(feature = "webp")]
|
||||
Format::WebP,
|
||||
] {
|
||||
let back = decode(&encode(&img, f, &opts).unwrap()).unwrap();
|
||||
assert!(back.icc.is_none(), "{f:?}");
|
||||
assert!(back.meta.exif.is_none() && back.meta.xmp.is_none(), "{f:?}");
|
||||
@@ -282,6 +289,7 @@ fn jpeg_dpi_in_jfif() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff_icc_readable_by_oracle() {
|
||||
let img = test_image(ChannelLayout::Rgb, SampleType::U16).with_icc(Some(sample_icc(1234)));
|
||||
let bytes = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
|
||||
@@ -308,6 +316,7 @@ fn metadata_survives_depth_conversion() {
|
||||
assert_eq!(back.meta.xmp, img.meta.xmp);
|
||||
}
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
/// #2399: a WebP export keeps the resolution even when the image has no EXIF (WebP has no
|
||||
/// resolution field of its own, so a minimal EXIF block carries it), lossless and lossy alike,
|
||||
/// and no longer warns that it is dropped.
|
||||
|
||||
@@ -91,6 +91,7 @@ fn png_with_exif(png: &[u8], exif: &[u8]) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff_with_orientation(data: &[u8], w: u32, h: u32, o: u16) -> Vec<u8> {
|
||||
use tiff::encoder::{TiffEncoder, colortype::Gray8};
|
||||
let mut cursor = std::io::Cursor::new(Vec::new());
|
||||
@@ -305,6 +306,7 @@ fn extra_samples_turn_with_the_image() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff_opens_upright_for_every_orientation() {
|
||||
let (w, h) = (4, 7);
|
||||
let up = exact_scene(w, h);
|
||||
@@ -318,6 +320,7 @@ fn tiff_opens_upright_for_every_orientation() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
#[test]
|
||||
fn webp_opens_upright() {
|
||||
let (w, h) = (6, 2);
|
||||
@@ -390,7 +393,14 @@ fn export_writes_orientation_1_and_keeps_pixels() {
|
||||
let mut stale = opened.clone();
|
||||
stale.meta.exif = Some(exif(6, true, false));
|
||||
stale.meta.xmp = Some(r#"<x tiff:Orientation="6"/>"#.into());
|
||||
for format in [Format::Png, Format::Jpeg, Format::WebP, Format::Tiff] {
|
||||
for format in [
|
||||
Format::Png,
|
||||
Format::Jpeg,
|
||||
#[cfg(feature = "webp")]
|
||||
Format::WebP,
|
||||
#[cfg(feature = "tiff")]
|
||||
Format::Tiff,
|
||||
] {
|
||||
let bytes = encode(&stale, format, &EncodeOptions { jpeg_quality: 100, ..Default::default() }).unwrap();
|
||||
let raw = decode_with(&bytes, &DecodeOptions { keep_orientation: true, ..Default::default() }).unwrap();
|
||||
if let Some(e) = &raw.meta.exif {
|
||||
@@ -626,9 +636,12 @@ fn limits_apply_to_the_upright_size() {
|
||||
let flipped = decode_with(&jpeg_with_exif(&jpeg, &exif(3, false, false)), &opts).unwrap();
|
||||
assert_eq!(flipped.dimensions(), (32, 16));
|
||||
// The same holds for a TIFF, whose orientation lives in its own IFD0.
|
||||
let tiff = tiff_with_orientation(&[7; 32 * 16], 32, 16, 8);
|
||||
assert!(matches!(decode_with(&tiff, &opts), Err(CodecError::LimitExceeded(_))));
|
||||
assert_eq!(decode_with(&tiff, &DecodeOptions::default()).unwrap().dimensions(), (16, 32));
|
||||
#[cfg(feature = "tiff")]
|
||||
{
|
||||
let tiff = tiff_with_orientation(&[7; 32 * 16], 32, 16, 8);
|
||||
assert!(matches!(decode_with(&tiff, &opts), Err(CodecError::LimitExceeded(_))));
|
||||
assert_eq!(decode_with(&tiff, &DecodeOptions::default()).unwrap().dimensions(), (16, 32));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -666,14 +679,18 @@ fn feature_config_probe_size_matches_decode() {
|
||||
let probed = [
|
||||
Format::Png,
|
||||
Format::Jpeg,
|
||||
#[cfg(feature = "tiff")]
|
||||
Format::Tiff,
|
||||
#[cfg(feature = "webp")]
|
||||
Format::WebP,
|
||||
Format::Gif,
|
||||
Format::Bmp,
|
||||
#[cfg(feature = "tga")]
|
||||
Format::Tga,
|
||||
Format::Qoi,
|
||||
Format::Hdr,
|
||||
Format::Ico,
|
||||
#[cfg(feature = "exr")]
|
||||
Format::OpenExr,
|
||||
];
|
||||
assert!(probed.iter().all(|f| rw_formats().contains(f)));
|
||||
|
||||
@@ -229,6 +229,7 @@ fn png_output_matches_oracle_all_layouts() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff_output_matches_oracle() {
|
||||
for l in [ChannelLayout::Gray, ChannelLayout::Rgb, ChannelLayout::Rgba] {
|
||||
for s in [SampleType::U8, SampleType::U16] {
|
||||
@@ -241,6 +242,7 @@ fn tiff_output_matches_oracle() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff_f32_output_matches_oracle() {
|
||||
let img = test_image(ChannelLayout::Rgba, SampleType::F32);
|
||||
let b = encode(&img, Format::Tiff, &EncodeOptions { tiff_compression: TiffCompression::None, ..Default::default() }).unwrap();
|
||||
|
||||
@@ -287,14 +287,11 @@ fn truncated_metadata_never_panics_and_falls_back() {
|
||||
let _ = xmp_with_resolution(x, (1.0, 1.0));
|
||||
}
|
||||
|
||||
// Property-like text repeated inside the packet must not trigger a full-suffix rescan
|
||||
// per occurrence (it used to be quadratic). With the cursor advancing past each located
|
||||
// value, this completes well under a second even with many decoys; a timeout here would
|
||||
// indicate the quadratic scan returned. A clean packet still extracts correctly.
|
||||
let start = std::time::Instant::now();
|
||||
// Property-like text repeated inside the packet has no value. craft-metadata's
|
||||
// `repeated_property_text_is_searched_once_for_each_property` counts the bytes this search
|
||||
// reads. A clean packet still extracts correctly.
|
||||
let decoys = " tiff:ResolutionUnit>".repeat(50_000);
|
||||
let _ = xmp_resolution(&decoys);
|
||||
assert!(start.elapsed() < std::time::Duration::from_secs(2), "xmp scan took too long: {:?}", start.elapsed());
|
||||
assert_eq!(xmp_resolution(&decoys), None);
|
||||
let clean = "<tiff:XResolution>300/1</tiff:XResolution><tiff:YResolution>300/1</tiff:YResolution><tiff:ResolutionUnit>2</tiff:ResolutionUnit>";
|
||||
near(xmp_resolution(clean), 300.0);
|
||||
}
|
||||
@@ -409,7 +406,12 @@ fn jpeg_export_writes_one_resolution_everywhere() {
|
||||
fn other_formats_take_the_exif_resolution_when_they_have_none() {
|
||||
let mut img = Image::from_raw(4, 4, ChannelLayout::Rgb, SampleType::U8, vec![90; 48]).unwrap();
|
||||
img.meta.exif = Some(camera_exif(&LE));
|
||||
for fmt in [Format::WebP, Format::Png] {
|
||||
let formats = [
|
||||
#[cfg(feature = "webp")]
|
||||
Format::WebP,
|
||||
Format::Png,
|
||||
];
|
||||
for fmt in formats {
|
||||
// Written at 240 with the 300 ppi EXIF: the EXIF follows the image.
|
||||
img.meta.dpi = Some((240.0, 240.0));
|
||||
let out = encode(&img, fmt, &EncodeOptions::default()).unwrap();
|
||||
@@ -533,7 +535,12 @@ fn exports_drop_the_source_exif_thumbnail() {
|
||||
img.meta.exif = Some(exif.clone());
|
||||
let jpeg = encode(&img, Format::Jpeg, &EncodeOptions::default()).unwrap();
|
||||
assert_eq!(next_ifd(e, &exif_of(&jpeg)), 0, "JPEG");
|
||||
for format in [Format::Png, Format::WebP] {
|
||||
let formats = [
|
||||
Format::Png,
|
||||
#[cfg(feature = "webp")]
|
||||
Format::WebP,
|
||||
];
|
||||
for format in formats {
|
||||
let back = decode(&encode(&img, format, &EncodeOptions::default()).unwrap()).unwrap();
|
||||
let got = back.meta.exif.unwrap_or_else(|| panic!("{format:?} kept no EXIF"));
|
||||
let body = got.strip_prefix(b"Exif\0\0").unwrap_or(&got);
|
||||
|
||||
@@ -159,7 +159,15 @@ mod hdr {
|
||||
fn hdr_values_survive_float_formats() {
|
||||
let vals: Vec<f32> = (0..16 * 8 * 3).map(|i| (i as f32 - 40.0) * 0.37).collect();
|
||||
let img = Image::from_f32(16, 8, ChannelLayout::Rgb, &vals).unwrap();
|
||||
for f in [Format::Tiff, Format::OpenExr, Format::Pnm] {
|
||||
let formats = [
|
||||
#[cfg(feature = "tiff")]
|
||||
Format::Tiff,
|
||||
#[cfg(feature = "exr")]
|
||||
Format::OpenExr,
|
||||
#[cfg(feature = "pnm")]
|
||||
Format::Pnm,
|
||||
];
|
||||
for f in formats {
|
||||
let back = decode(&encode(&img, f, &EncodeOptions::default()).unwrap()).unwrap();
|
||||
assert_eq!(back.to_f32_samples().unwrap(), vals, "{f:?}");
|
||||
}
|
||||
@@ -180,6 +188,7 @@ fn hdr_format_keeps_bright_values_approximately() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "exr")]
|
||||
#[test]
|
||||
fn f16_exr_is_bit_exact() {
|
||||
let vals: Vec<f16> = (0..20 * 10 * 4).map(|i| f16::from_f32(i as f32 * 0.013 - 1.0)).collect();
|
||||
@@ -192,6 +201,7 @@ fn f16_exr_is_bit_exact() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn tiff_all_compressions_lossless() {
|
||||
for layout in ChannelLayout::ALL {
|
||||
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
@@ -214,6 +224,7 @@ fn tiff_all_compressions_lossless() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "tiff")]
|
||||
fn compressed_tiff_does_not_keep_the_uncompressed_reservation() {
|
||||
// The encoder reserves the uncompressed size up front for an uncompressed file (#6607). A
|
||||
// smooth image compresses to a fraction of it, and no returned file holds much spare room.
|
||||
@@ -302,6 +313,7 @@ fn jpeg_format_options_round_trip() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
#[test]
|
||||
fn webp_lossy_request_is_a_lossy_file() {
|
||||
let img = test_image(ChannelLayout::Rgb, SampleType::U8);
|
||||
@@ -347,7 +359,7 @@ fn feature_config_empty_image_rejected() {
|
||||
#[test]
|
||||
fn larger_image_png_tiff_exact() {
|
||||
let img = synth(513, 257, ChannelLayout::Rgba, SampleType::U16, 99, 1.0);
|
||||
for f in [Format::Png, Format::Tiff, Format::Pnm] {
|
||||
for f in [Format::Png, Format::Tiff, Format::Pnm].into_iter().filter(|f| caps(*f).read && caps(*f).write) {
|
||||
let back = decode(&encode(&img, f, &EncodeOptions::default()).unwrap()).unwrap();
|
||||
assert_eq!(back.data(), img.data(), "{f:?}");
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ fn hostile_jpeg_tables_give_no_estimate_and_never_panic() {
|
||||
assert_eq!(jpeg_quality(&png), None);
|
||||
}
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
#[test]
|
||||
fn webp_lossless_and_lossy_are_told_apart() {
|
||||
let img = photo(33, 21, ChannelLayout::Rgb);
|
||||
@@ -87,6 +88,7 @@ fn webp_lossless_and_lossy_are_told_apart() {
|
||||
assert!(matches!(webp_encoding(&bytes), Some(WebpEncoding::Lossy { quality: Some(58..=62) })), "{:?}", webp_encoding(&bytes));
|
||||
}
|
||||
|
||||
#[cfg(feature = "webp")]
|
||||
#[test]
|
||||
fn hostile_webp_never_panics() {
|
||||
let img = photo(24, 24, ChannelLayout::Rgb);
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Original synthetic fixture: one RGBA pixel, written by the independent TIFF structure crate.
|
||||
#[cfg(not(feature = "tiff"))]
|
||||
use craft_image_codecs::*;
|
||||
|
||||
#[cfg(not(feature = "tiff"))]
|
||||
#[test]
|
||||
fn omitted_tiff_pixels_are_refused_but_metadata_remains_readable() {
|
||||
let bytes = craft_tiff::plain::encode_rgba16(1, 1, &[1, 2, 3, u16::MAX]).unwrap();
|
||||
assert_eq!(detect(&bytes), Some(Format::Tiff));
|
||||
assert!(!caps(Format::Tiff).read && !caps(Format::Tiff).write);
|
||||
assert!(tiff_info(&bytes).is_ok());
|
||||
assert_eq!(tiff_probe::header(&bytes, 1).unwrap(), (1, 1, 1));
|
||||
assert_eq!(probe_stored_size(&bytes, &Limits::default()).unwrap(), (1, 1));
|
||||
let image = Image::from_u8(1, 1, ChannelLayout::Rgba, vec![1, 2, 3, 255]).unwrap();
|
||||
let errors = [
|
||||
decode(&bytes).err(),
|
||||
decode_tiff_page(&bytes, 0, &DecodeOptions::default()).err(),
|
||||
TiffBands::open(&bytes, None, &Limits::default()).err(),
|
||||
encode(&image, Format::Tiff, &EncodeOptions::default()).err(),
|
||||
encode_tiff_plain_rgba16(1, 1, &[1, 2, 3, u16::MAX]).err(),
|
||||
];
|
||||
for error in errors {
|
||||
match error.unwrap() {
|
||||
CodecError::Unsupported { format, reason } => {
|
||||
assert_eq!(format, Format::Tiff);
|
||||
assert!(reason.contains("tiff feature"), "{reason}");
|
||||
}
|
||||
other => panic!("expected a named feature error, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,13 @@ craft-host = { workspace = true }
|
||||
craft-tracked = { workspace = true }
|
||||
craft-ui-macros = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
global-hotkey = { version = "0.9", optional = true }
|
||||
|
||||
# The systems where global-hotkey grabs keys through X11.
|
||||
[target.'cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies]
|
||||
x11rb = { version = "0.13.1", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# `serde` for setting `RawInput` fields only the suite's egui fork has.
|
||||
egui = { workspace = true }
|
||||
@@ -32,3 +39,5 @@ tempfile = "3"
|
||||
[features]
|
||||
# The egui key conversions.
|
||||
egui = ["dep:egui", "craft-host/ui"]
|
||||
# System-wide hotkeys (the `global` module); not built for wasm32.
|
||||
global = ["dep:global-hotkey", "dep:x11rb"]
|
||||
+73
-1
@@ -18,7 +18,7 @@ supplies its command catalog, its file-format readers and its UI.
|
||||
`Keymap::with_reserved`, e.g. `reserved::system(platform)` for the operating system's window
|
||||
switching and closing chords. A reserved chord cannot be assigned or bound.
|
||||
- Dependencies: `serde`, `serde_json` and `roxmltree`; `craft-i18n` and `craft-host`; `egui` with the
|
||||
`egui` feature.
|
||||
`egui` feature; `global-hotkey`, and `x11rb` on Linux and the BSDs, with the `global` feature.
|
||||
|
||||
## A catalog and dispatch
|
||||
|
||||
@@ -364,3 +364,75 @@ The Keyboard Shortcuts dialog is `craft_menu::shortcuts`.
|
||||
- `egui`: the egui side. Conversions to and from egui keys and modifiers; `KeyInput::from_egui`;
|
||||
`egui::matches`, which accepts the shifted key egui reports for a Shift binding (`Shift+;`
|
||||
matches `:`).
|
||||
- `global`: `global::GlobalHotkeys`, chords that run a command while another application has the
|
||||
keyboard, such as a record toggle pressed during a full-screen game. It registers them with
|
||||
`RegisterHotKey` on Windows, a Carbon hotkey on macOS and a key grab on the X11 root window
|
||||
on Linux and the BSDs. Not built for wasm32; on other systems (Android, iOS) `new` fails with
|
||||
`GlobalError::Unsupported`.
|
||||
|
||||
```rust,ignore
|
||||
let mut hotkeys = GlobalHotkeys::new()?;
|
||||
hotkeys.set_waker(move || ctx.request_repaint());
|
||||
let refused = hotkeys.replace(bindings); // (CommandRef, Chord) pairs
|
||||
// Once a frame:
|
||||
for event in hotkeys.poll() {
|
||||
app.key(&event.command, event.state); // KeyState::Pressed or KeyState::Released
|
||||
}
|
||||
```
|
||||
|
||||
- One set is open per process at a time (`GlobalError::AlreadyOpen`). Create it on the UI
|
||||
thread: on Windows that thread receives the hotkey messages, and on macOS it must be the main
|
||||
thread.
|
||||
- A chord needs Cmd, Ctrl or Alt unless its key is F1 to F35 (`GlobalError::TypingKey`). Keys
|
||||
typed with Shift (`+`, `:`, `?`) have no key of their own (`GlobalError::Unbindable`). Off
|
||||
macOS, `Cmd+K` and `Ctrl+K` are one hotkey (`GlobalError::Duplicate`). A chord another
|
||||
application holds is `GlobalError::Taken`. Windows registers F1 to F24 and macOS F1 to F20.
|
||||
On X11 the ISO key between left Shift and Z and `\` are one hotkey (`GlobalError::Duplicate`),
|
||||
and `'` cannot be grabbed (`GlobalError::Unbindable`). On Windows a chord with Ctrl and Alt on
|
||||
a letter, digit, symbol or Space key is refused (`GlobalError::AltGr`), since Windows reports AltGr
|
||||
as Ctrl+Alt.
|
||||
- On X11 a symbol chord is grabbed at the key that types the symbol in the current layout. A
|
||||
symbol the layout types only with AltGr is refused (`GlobalError::Unbindable`): with German,
|
||||
`Ctrl+[` would grab Ctrl+8. A symbol typed with Shift is written without Shift, as the keymap
|
||||
matches punctuation: with AZERTY, `Ctrl+.` grabs Ctrl+Shift on the key that types `.`, and
|
||||
`Ctrl+Shift+.` is refused (`GlobalError::Unbindable`). The Latin letters of a second layout
|
||||
group count as that layout's own keys when the key types no letter, digit or symbol in the
|
||||
first group, so with Russian and US `Ctrl+A` grabs the key that types A. With US and French,
|
||||
`Ctrl+A` is refused (`GlobalError::Unbindable`), since the grab would go to the US Q key.
|
||||
Symbols of a second group are refused like AltGr ones.
|
||||
Two chords that land on one key and modifier set are one hotkey (`GlobalError::Duplicate`):
|
||||
with AZERTY, `Ctrl+-` and `Ctrl+6`. So are two chords registered as the same hotkey on
|
||||
different keys: `Ctrl+.` registered with AZERTY, then `Ctrl+Shift+.` after a switch to US.
|
||||
- On X11, when a layout change moves a chord's key, `replace`, `unregister` and `clear`
|
||||
release the key that was grabbed. A grab that no key of the current layout leads to stays
|
||||
until a later change can release it, and its chord is refused meanwhile (`GlobalError::Taken`).
|
||||
When the layout changes while a grab is released, a binding whose grab that release removed
|
||||
is grabbed again, or leaves the set when it cannot be grabbed again.
|
||||
When the keyboard mapping cannot be read, `replace` refuses every binding and keeps the set
|
||||
as it is, except that an empty `replace` still clears the set. The grabs of the chords that
|
||||
leave the set then stay until a later change can release them, and `unregister` returns the
|
||||
error.
|
||||
- On Windows and X11 a letter chord is grabbed at the key that types the letter, as the keymap
|
||||
matches letters on a Latin layout. On macOS it is grabbed at the letter's position on a US
|
||||
keyboard: with AZERTY, `Cmd+A` is the key that types Q.
|
||||
- A held chord gives one `Pressed` and one `Released`. `replace` leaves a binding whose chord
|
||||
and command do not change registered, so a held chord stays held. Unregistering a held chord,
|
||||
or replacing its binding, gives its `Released` at the next `poll`; events the system sent
|
||||
before the change go to the command the chord ran then. On Windows and macOS a press that
|
||||
waits in the app's event queue while the bindings change goes to the new command. On Windows
|
||||
the release of a chord unregistered while held is dropped when it arrives, so it does not end
|
||||
a later hold of the same chord.
|
||||
- At most 256 system events wait between polls (`MAX_QUEUED`); beyond that the oldest are
|
||||
dropped, and after such a loss every chord that was down is released. When more than 256
|
||||
events wait for `poll`, the oldest press whose release also waits is dropped with that
|
||||
release, so every press the app gets has its release. Past 512 waiting events
|
||||
(`MAX_PENDING`) the oldest press is dropped; a release is never dropped. At most 128 chords
|
||||
are registered (`MAX_GLOBAL`).
|
||||
- On X11 each `register` and `unregister` waits for the key-grab thread, which takes one
|
||||
request every 50 ms. `replace` sends the chords it removes in one request and those it adds
|
||||
in another, and adds them one at a time when the system refuses one of them; `clear` sends
|
||||
one request. `new` fails with
|
||||
`GlobalError::Os` when that thread has stopped (a display without the XKEYBOARD extension).
|
||||
- A Wayland session is refused with `GlobalError::Wayland`, since an X11 grab there sees only
|
||||
keys typed into X11 windows. Without an X11 display, `new` fails with
|
||||
`GlobalError::NoDisplay`.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -13,7 +13,9 @@
|
||||
//! user's keyboard layout, for matching, recording and labels. [`editor`] is the model of a
|
||||
//! shortcut editor: undo, a chord recorder, conflict queries and search. With the `egui` feature,
|
||||
//! the `egui` module
|
||||
//! converts to and from egui keys and matches key presses against bindings.
|
||||
//! converts to and from egui keys and matches key presses against bindings. With the `global`
|
||||
//! feature, the `global` module registers chords with the operating system so that they run
|
||||
//! commands while another application has the keyboard.
|
||||
//!
|
||||
//! ```
|
||||
//! use craft_keymap::{Chord, Platform};
|
||||
@@ -143,6 +145,8 @@ mod commands;
|
||||
pub mod editor;
|
||||
#[cfg(feature = "egui")]
|
||||
pub mod egui;
|
||||
#[cfg(all(feature = "global", not(target_arch = "wasm32")))]
|
||||
pub mod global;
|
||||
pub mod import;
|
||||
pub mod keymap;
|
||||
pub mod layout;
|
||||
|
||||
Loaded 100 of 289 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user