Merge current craft-libs main

This commit is contained in:
skylartaylor committed 2026-11-27 18:11:32 +01:00
commit 331d0399da
395 files changed
+15247 -955

No files matched your search

+3 -1
View File
@@ -32,7 +32,9 @@ jobs:
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
linux-env: WGPU_BACKEND=vulkan
windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1
env: CRAFT_PRINT_REQUIRE_QUEUE=0
env: |
CRAFT_PRINT_REQUIRE_QUEUE=0
CRAFT_HOSTILE_DIVISOR=1
setup-command: bash scripts/ci-test-inputs.sh
command: |
python scripts/test-full-validation.py
+4 -2
View File
@@ -1,7 +1,7 @@
name: Nightly full tests
# The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep
# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The
# with CRAFT_HOSTILE_DIVISOR=1 (every member, no sample), and every proptest at its own case count (no PROPTEST_CASES). The
# rest of the workspace's tests run with them, on Linux, with the gate's setup.
on:
schedule:
@@ -26,7 +26,9 @@ jobs:
packages: mesa-vulkan-drivers libvulkan1
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
linux-env: WGPU_BACKEND=vulkan
env: CRAFT_PRINT_REQUIRE_QUEUE=0
env: |
CRAFT_PRINT_REQUIRE_QUEUE=0
CRAFT_HOSTILE_DIVISOR=1
setup-command: bash scripts/ci-test-inputs.sh
cache-paths: .test-inputs/photocraft/corpus
cache-key: photocraft-corpus
Generated
+17 -14
View File
@@ -4674,11 +4674,13 @@ dependencies = [
name = "craft-update"
version = "0.1.0"
dependencies = [
"base64 0.22.1",
"chrono",
"craft-host",
"craft-theme",
"craft-ui",
"dunce",
"ed25519-dalek 2.2.0",
"egui",
"flate2",
"image",
@@ -4691,6 +4693,7 @@ dependencies = [
"sha2 0.10.9",
"tar",
"tempfile",
"toml",
"ureq",
"verifysign",
"winreg",
@@ -5656,7 +5659,7 @@ dependencies = [
[[package]]
name = "ecolor"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
dependencies = [
"bytemuck",
"emath",
@@ -5712,7 +5715,7 @@ dependencies = [
[[package]]
name = "eframe"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
dependencies = [
"ahash",
"bytemuck",
@@ -5747,7 +5750,7 @@ dependencies = [
[[package]]
name = "egui"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
dependencies = [
"accesskit",
"ahash",
@@ -5766,7 +5769,7 @@ dependencies = [
[[package]]
name = "egui-wgpu"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
dependencies = [
"ahash",
"bytemuck",
@@ -5785,7 +5788,7 @@ dependencies = [
[[package]]
name = "egui-winit"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
dependencies = [
"block2 0.6.2",
"bytemuck",
@@ -5805,7 +5808,7 @@ dependencies = [
[[package]]
name = "egui_glow"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
dependencies = [
"bytemuck",
"egui",
@@ -5818,7 +5821,7 @@ dependencies = [
[[package]]
name = "egui_kittest"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
dependencies = [
"eframe",
"egui",
@@ -5895,7 +5898,7 @@ dependencies = [
[[package]]
name = "emath"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
dependencies = [
"bytemuck",
]
@@ -5968,7 +5971,7 @@ dependencies = [
[[package]]
name = "epaint"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
dependencies = [
"ahash",
"bytemuck",
@@ -5994,7 +5997,7 @@ dependencies = [
[[package]]
name = "epaint_default_fonts"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
[[package]]
name = "equator"
@@ -15317,19 +15320,19 @@ dependencies = [
[[patch.unused]]
name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
[[patch.unused]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
+14 -14
View File
@@ -321,20 +321,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
linesweeper = { path = "vendor/linesweeper" }
vello_common = { path = "vendor/vello_common" }
vello_cpu = { path = "vendor/vello_cpu" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
+2 -2
View File
@@ -289,8 +289,8 @@ linesweeper
linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in
vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs,
src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its manifest names
Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
src/segments.rs, src/curve/transverse.rs, src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its
manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
patches and the files left out.
+3 -2
View File
@@ -377,8 +377,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
with a password. Salvages damaged files. Bounded and panic-free on hostile input. What an item
means stays in each app.
- [`craft-quit`](crates/quit/src/lib.rs): native macOS quit, egui close handling and an optional
app menu. Unsaved-document decisions and save prompts stay in each app.
- [`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-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).
+22 -1
View File
@@ -6,7 +6,7 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee
## Core Guarantees: Atomicity vs. Durability
1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; sweeping orphaned staging files is delegated to consuming application recovery routines. The destination file itself is never corrupted.
1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; the application removes orphaned staging files by calling `sweep_temp_files` for the folder (see "Removing Orphaned Staging Files" below). The destination file itself is never corrupted.
2. **Durability & Ordering Boundaries**:
- **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback).
- **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced.
@@ -63,6 +63,27 @@ let path = Path::new("export.png");
write_new(path, b"png bytes...").expect("exclusive write");
```
### Removing Orphaned Staging Files
```rust
use std::path::Path;
use std::time::Duration;
use craft_atomic::sweep_temp_files;
// Removes staging files in scenes/ that were last modified an hour or more ago.
// Returns how many were removed.
let removed = sweep_temp_files(Path::new("scenes"), Duration::from_secs(3600)).unwrap_or(0);
```
`sweep_temp_files` removes only regular files whose names have the staging form, never follows
a symbolic link, and does not search subfolders. A save updates its staging file's modification
time only while it writes bytes, not while it flushes or renames, and removing the staging file
makes that save fail. Choose a minimum age longer than the longest time any save into the folder,
by any process including the calling one, may go without writing, counting the final flush and
rename. On Windows, a write may not update the modification time until the staging file's handle
closes, so choose a minimum age longer than the longest whole save, from the staging file's
creation through the rename. Entries that cannot be removed are left in place.
### Document Permissions and Private Data
The free functions and `WriteOptions::default()` use `NewFilePermissions::PlatformDefault`.
+54 -3
View File
@@ -14,9 +14,9 @@
//! file retains its previous bytes, or it is replaced completely with the new contents. If an error occurs
//! during staging or rename, the target remains unmodified and the staging file is removed in user space.
//! An abnormal process termination (e.g. `SIGKILL`, crash, power loss) bypasses user-space cleanup and
//! leaves the temporary staging file on disk. Sweeping orphaned staging files is the responsibility of the
//! consuming application; the library does not perform background sweeping. The destination file itself is
//! never corrupted.
//! leaves the temporary staging file on disk. The library does not sweep in the background; the consuming
//! application calls [`sweep_temp_files`] for a folder, for example at startup, to remove orphaned staging
//! files. The destination file itself is never corrupted.
//! - **Durability & Ordering Boundaries**:
//! Data persistence across power failures involves two sync points:
//! 1. **Content Flush (`sync_file`)**: The staging file's payload is forced to non-volatile storage
@@ -818,6 +818,57 @@ pub fn temp_name(file: &str) -> String {
format!(".{stem}.{pid}-{n}.craft_tmp")
}
/// Removes staging files that interrupted writes left in `dir`, and returns how many it removed.
///
/// A file is removed when its name has the form [`temp_name`] gives, it is a regular file (a
/// symbolic link is not followed), and it was last modified at least `min_age` ago. The process
/// id in the name is not used to decide, since the system reuses process ids. A save updates its
/// staging file's modification time only while it writes bytes, not while it flushes or renames,
/// and removing the staging file makes that save fail. Pass a `min_age` longer than the longest
/// time any save into `dir`, by any process including the calling one, may go without writing,
/// counting the final flush and rename. On Windows, a write may not update the modification time
/// until the staging file's handle closes, so pass a `min_age` longer than the longest whole save,
/// from the staging file's creation through the rename. Entries that cannot be read or removed are
/// left in place. Subfolders are not searched.
/// On `wasm32` this returns an `Unsupported` error.
pub fn sweep_temp_files(dir: &Path, min_age: std::time::Duration) -> io::Result<usize> {
#[cfg(target_arch = "wasm32")]
{
let _ = (dir, min_age);
Err(io::Error::new(io::ErrorKind::Unsupported, "staging files cannot be swept on this platform"))
}
#[cfg(not(target_arch = "wasm32"))]
{
let now = std::time::SystemTime::now();
let entries = std::fs::read_dir(dir).map_err(|e| io::Error::new(e.kind(), format!("cannot read {}: {e}", dir.display())))?;
let mut removed = 0;
for entry in entries.flatten() {
if !entry.file_name().to_str().is_some_and(is_temp_name) {
continue;
}
let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
let old = meta.modified().ok().and_then(|m| now.duration_since(m).ok()).is_some_and(|age| age >= min_age);
if meta.is_file() && old && std::fs::remove_file(entry.path()).is_ok() {
removed += 1;
}
}
Ok(removed)
}
}
/// Whether `name` has the form [`temp_name`] gives (`.{stem}.{pid}-{n}.craft_tmp`), with a stem
/// of at most [`TEMP_STEM_BYTES`] bytes.
#[cfg(not(target_arch = "wasm32"))]
fn is_temp_name(name: &str) -> bool {
// Decimal digits with no leading zero, as `format!` writes an integer; a lone `0` is allowed.
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0'));
let Some((stem, tail)) = name.strip_prefix('.').and_then(|rest| rest.strip_suffix(".craft_tmp")).and_then(|rest| rest.rsplit_once('.')) else {
return false;
};
let Some((pid, n)) = tail.split_once('-') else { return false };
stem.len() <= TEMP_STEM_BYTES && digits(pid) && digits(n) && pid.parse::<u32>().is_ok() && n.parse::<u64>().is_ok()
}
/// The end of an error message: whether an original file was left as it was.
fn unchanged(existed: bool) -> &'static str {
if existed { "; the original file was not changed" } else { "" }
+76
View File
@@ -582,3 +582,79 @@ fn wasm_atomic_write_returns_unsupported() {
let err = atomic_write(Path::new("dummy.craft"), b"data").unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::Unsupported);
}
#[cfg(target_arch = "wasm32")]
#[test]
fn wasm_sweep_temp_files_returns_unsupported() {
let err = sweep_temp_files(Path::new("scenes"), std::time::Duration::ZERO).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::Unsupported);
}
/// Writes the file `name` in `dir` and dates its modification time `age` in the past.
#[cfg(not(target_arch = "wasm32"))]
fn leftover(dir: &Path, name: &str, age: std::time::Duration) -> io::Result<PathBuf> {
let p = dir.join(name);
std::fs::write(&p, b"interrupted save")?;
File::options().write(true).open(&p)?.set_modified(std::time::SystemTime::now() - age)?;
Ok(p)
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn sweep_removes_only_old_staging_files() -> io::Result<()> {
let d = TempDir::new("sweep_old");
let other = std::process::id().wrapping_add(1);
let hour = std::time::Duration::from_secs(3600);
let orphan = leftover(&d.0, &format!(".scene.json.{other}-0.craft_tmp"), 2 * hour)?;
// A process id the system reused for this process does not protect an old orphan.
let same_pid = leftover(&d.0, &temp_name("scene.json"), 2 * hour)?;
let recent = leftover(&d.0, &format!(".scene.json.{other}-1.craft_tmp"), std::time::Duration::ZERO)?;
let document = leftover(&d.0, "scene.json", 2 * hour)?;
assert_eq!(sweep_temp_files(&d.0, hour)?, 2);
assert!(!orphan.exists() && !same_pid.exists());
assert!(recent.exists() && document.exists());
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn sweep_keeps_files_it_did_not_name_and_folders() -> io::Result<()> {
let d = TempDir::new("sweep_lookalike");
let other = std::process::id().wrapping_add(1);
let old = std::time::Duration::from_secs(7200);
let orphan = leftover(&d.0, &format!(".a.b.{other}-7.craft_tmp"), old)?;
let kept = [
leftover(&d.0, "notes.craft_tmp", old)?,
leftover(&d.0, &format!("scene.json.{other}-7.craft_tmp"), old)?,
leftover(&d.0, ".scene.json.12-x.craft_tmp", old)?,
leftover(&d.0, ".scene.json.-3.craft_tmp", old)?,
leftover(&d.0, ".12-3.craft_tmp", old)?,
leftover(&d.0, &format!(".scene.json.{other}-7.craft_tmp.bak"), old)?,
leftover(&d.0, ".scene.json.99999999999-7.craft_tmp", old)?,
// temp_name writes the process id and the counter without leading zeros.
leftover(&d.0, ".scene.json.012-0.craft_tmp", old)?,
leftover(&d.0, ".scene.json.12-03.craft_tmp", old)?,
// temp_name keeps at most TEMP_STEM_BYTES bytes of the destination's name.
leftover(&d.0, &format!(".{}.{other}-7.craft_tmp", "s".repeat(TEMP_STEM_BYTES + 1)), old)?,
];
// The longest stem temp_name writes, in ASCII and in two-byte characters.
let longest = leftover(&d.0, &temp_name(&"s".repeat(200)), old)?;
let longest_wide = leftover(&d.0, &temp_name(&"é".repeat(100)), old)?;
let folder = d.0.join(format!(".scene.json.{other}-8.craft_tmp"));
std::fs::create_dir(&folder)?;
assert_eq!(sweep_temp_files(&d.0, std::time::Duration::ZERO)?, 3);
assert!(!orphan.exists() && !longest.exists() && !longest_wide.exists());
assert!(kept.iter().all(|p| p.exists()), "a file without the staging name was removed");
assert!(folder.is_dir());
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn sweep_of_a_missing_folder_is_an_error() {
let d = TempDir::new("sweep_missing");
let err = sweep_temp_files(&d.0.join("absent"), std::time::Duration::ZERO).err().map(|e| e.kind());
assert_eq!(err, Some(io::ErrorKind::NotFound));
}
+11 -1
View File
@@ -578,7 +578,17 @@ impl<P: Clone + Eq + Hash> Layout<P> {
moving.column.groups.iter_mut().for_each(|group| group.height = height);
}
let index = place.group_index().ok_or(DockError::InvalidPlacement)?;
let groups = &mut self.column_mut(&place).ok_or(DockError::MissingTarget)?.groups;
let column = self.column_mut(&place).ok_or(DockError::MissingTarget)?;
// Groups shown at a width of their own, in a floating window or an expanded column, keep it
// as the flyout width of the collapsed column they join.
if column.iconic
&& !moving.column.iconic
&& let Some(width) = moving.column.width
{
let flyout = (column.width != Some(width)).then_some(width);
moving.column.groups.iter_mut().for_each(|group| group.flyout_width = flyout);
}
let groups = &mut column.groups;
let index = (index + usize::from(below)).min(groups.len());
groups.splice(index..index, moving.column.groups);
Ok(())
+34 -7
View File
@@ -82,7 +82,8 @@ impl Reader {
self
}
/// The digit-group separator, which the reader skips between digits.
/// The digit-group separator, which the reader skips between digits. A comma or point after zero reads as a
/// decimal when it is the number's only separator and digits follow it.
#[must_use]
pub fn group(mut self, group: char) -> Self {
self.group = Some(group);
@@ -250,11 +251,6 @@ impl Parse<'_> {
}
}
/// Whether the group separator at `at` is followed by exactly three digits.
fn three_digits_after(&self, at: usize) -> bool {
self.chars[at + 1..].iter().take_while(|c| digit(**c).is_some()).count() == 3
}
fn number(&mut self) -> Result<f64, NotAValue> {
let mut text = String::new();
let mut seen_decimal = false;
@@ -264,7 +260,16 @@ impl Parse<'_> {
} else if c == self.reader.decimal && !seen_decimal {
seen_decimal = true;
text.push('.');
} else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() && self.three_digits_after(self.at) {
} else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() {
let after = &self.chars[self.at + 1..];
let digits = after.iter().take_while(|c| digit(**c).is_some()).count();
let only_mark = after.get(digits).is_none_or(|&next| next != c && next != self.reader.decimal);
if text == "0" && matches!(c, '.' | ',') && digits > 0 && only_mark {
seen_decimal = true;
text.push('.');
} else if digits != 3 {
break;
}
} else {
break;
}
@@ -281,6 +286,28 @@ impl Parse<'_> {
mod tests {
use super::*;
#[test]
fn a_single_group_mark_after_zero_reads_as_a_decimal() {
for (decimal, group) in [('.', ','), (',', '.')] {
let reader = Reader::new().decimal(decimal).group(group).unit("cm", 2.0);
for (text, want) in [
(format!("0{group}125+2"), 2.125),
(format!("2x0{group}125"), 0.25),
(format!("-0{group}25 cm"), -0.5),
(format!("٠{group}١٢٥"), 0.125),
(format!("1{group}125"), 1125.0),
(format!("1{group}234{decimal}5"), 1234.5),
(format!("0{group}123{group}456"), 123456.0),
(format!("0{group}125{decimal}5"), 125.5),
] {
assert_eq!(reader.read(&text, None), Ok(want), "{text}");
}
assert_eq!(reader.read(&format!("0{group}"), None), Err(NotAValue));
}
let swiss = Reader::new().group('\'');
assert_eq!(swiss.read("0'125", None), Ok(125.0));
}
#[test]
fn expressions_units_and_relative_input_read_through_one_grammar() {
let reader = Reader::new().decimal(',').group('.').unit("in", 72.0).unit("pt", 1.0);
+36 -2
View File
@@ -66,6 +66,15 @@ pub struct Wheel {
pub lines: Vec2,
/// Zoom factor; 1 for none.
pub zoom: f32,
/// The wheel motion that reached the share as `zoom` instead of `scroll`, in wheel lines: wheel events under the
/// zoom modifier, and the Ctrl+wheel steps the service reads as a touchpad's pinch on Windows and Linux. A line
/// event counts its lines (notches) as the device sent them, a point or page event its points over egui's line
/// scroll speed. It travels with the zoom share, so a taker can count the notches or lines of a Ctrl+wheel that
/// zooms without the zoom speed; zero for a native pinch and for a wheel without the modifier.
pub zoom_lines: Vec2,
/// The running gesture's `zoom_lines` gathered so far, this share included, for the taker that owns the gesture;
/// another taker's share gathers only itself, as with `gathered`.
pub zoom_gathered: Vec2,
/// The modifiers held.
pub mods: Mods,
/// The unit the device reported.
@@ -224,6 +233,8 @@ impl Wheel {
scroll,
lines: Vec2::ZERO,
zoom: 1.0,
zoom_lines: Vec2::ZERO,
zoom_gathered: Vec2::ZERO,
mods,
unit,
phase,
@@ -245,6 +256,13 @@ impl Wheel {
self
}
/// The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`).
#[must_use]
pub const fn zoom_lines(mut self, lines: Vec2) -> Self {
self.zoom_lines = lines;
self
}
/// The same gesture with the two-finger touch zoom factor `zoom`.
pub const fn touch_zoom(mut self, zoom: f32) -> Self {
self.touch_zoom = zoom;
@@ -563,13 +581,28 @@ fn for_field(wheel: &Wheel) -> bool {
/// Whether `wheel` carries a pinch, a touch zoom, a rotation or a two-finger pan: the zoom share's values.
fn pinches(wheel: &Wheel) -> bool {
wheel.zoom != 1.0 || wheel.touch_zoom != 1.0 || wheel.rotation != 0.0 || wheel.touch_rotation != 0.0 || wheel.touch_pan != Vec2::ZERO
wheel.zoom != 1.0
|| wheel.zoom_lines != Vec2::ZERO
|| wheel.touch_zoom != 1.0
|| wheel.rotation != 0.0
|| wheel.touch_rotation != 0.0
|| wheel.touch_pan != Vec2::ZERO
}
/// `wheel` without the zoom share's values: a scroll share carries no pinch or rotation, so a field or a scroll region
/// never reads one.
const fn scroll_only(wheel: Wheel) -> Wheel {
Wheel { zoom: 1.0, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, touch_pan: Vec2::ZERO, zooms: false, ..wheel }
Wheel {
zoom: 1.0,
zoom_lines: Vec2::ZERO,
zoom_gathered: Vec2::ZERO,
touch_zoom: 1.0,
rotation: 0.0,
touch_rotation: 0.0,
touch_pan: Vec2::ZERO,
zooms: false,
..wheel
}
}
/// The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes
@@ -715,6 +748,7 @@ fn split_at<O: Copy + PartialEq>(
Some((_, share)) => {
share.scroll += part.scroll;
share.zoom *= part.zoom;
share.zoom_lines += part.zoom_lines;
share.touch_zoom *= part.touch_zoom;
share.rotation += part.rotation;
share.touch_rotation += part.touch_rotation;
+39
View File
@@ -319,6 +319,45 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare
assert_eq!(floated.edge, None, "an expanded column keeps to the edge nearer its rect");
}
/// A group docked into a collapsed column keeps the width it was shown at as its flyout width: a floating window's
/// width, or an expanded column's. A width equal to the column's leaves the flyout following the column, and a group
/// moved between collapsed columns keeps its own flyout width.
#[test]
fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width() {
let flyout = |layout: &Layout<u32>, panel: u32| layout.group(&layout.place(&panel).unwrap()).unwrap().flyout_width;
let mut layout = columns();
layout.apply(Action::move_floating(6, rect(100.0, 100.0, 420.0, 400.0))).unwrap();
layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap();
assert!(!floats(&layout, 6) && column_of(&layout, 6).iconic);
assert_eq!(flyout(&layout, 6), Some(420.0), "the floating window's width");
layout.apply(Action::resize_flyout_width(6, Some(380.0))).unwrap();
layout.apply(Action::move_group(6, Target::float(rect(100.0, 100.0, 380.0, 400.0)))).unwrap();
layout.apply(Action::set_iconic(6, false)).unwrap();
layout.apply(Action::move_floating(6, rect(100.0, 100.0, 300.0, 400.0))).unwrap();
layout.apply(Action::move_group(6, Target::at(4, DockPlacement::group(false, None)))).unwrap();
assert_eq!(flyout(&layout, 6), Some(300.0), "the width the window was resized to, not the flyout width it left with");
let mut layout = columns();
layout.apply(Action::resize_column(2, 260.0)).unwrap();
layout.apply(Action::move_group(2, Target::at(3, DockPlacement::group(true, None)))).unwrap();
assert_eq!(flyout(&layout, 2), Some(260.0), "the expanded column's width");
let mut layout = columns();
layout.apply(Action::resize_column(3, 300.0)).unwrap();
layout.apply(Action::move_group(6, Target::at(3, DockPlacement::group(true, None)))).unwrap();
assert_eq!(flyout(&layout, 6), None, "a width equal to the column's follows the column");
let mut layout = columns();
let start = Node::dock(DockEdge::Start, vec![Column::new(vec![g(&[7], 0)]).with_iconic(true)]);
let Some(root) = layout.root.take() else { panic!("no root") };
layout.root = Some(Node::split(Axis::X, SplitSize::FixedFirst(48.0), start, root));
layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap();
layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap();
assert_eq!(flyout(&layout, 3), Some(350.0), "a group from another collapsed column keeps its own");
}
/// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a
/// column float in its state; groups joining a column, docked or floating, take that column's state.
#[test]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "craft-cdr"
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings"
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing; writer for version 15 .cdr drawings, and a .cmx writer in the layouts it reads"
version.workspace = true
edition.workspace = true
license.workspace = true
+45 -4
View File
@@ -1,8 +1,10 @@
# Where each layout comes from
The reader relies on the record layouts below, and the writer (`src/write.rs`) lays out version 15
files by the same rows, with R64 to R73 for what only the writer needs. Code cites a row by its id
(`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row here.
files by the same rows, with R64 to R73 for what only the writer needs. The `.cmx` writer
(`src/cmx_write.rs`) writes in them, with R74 for what only it needs ("Written fields" lists each
field it sets). Code cites a row by its id (`R1` ...), and `tests/it/provenance.rs` fails when a
cited id has no row here.
Sources:
@@ -57,7 +59,10 @@ Sources:
Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks
confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows;
listed so it can be checked against a file, with what the reader does when it is wrong).
listed so it can be checked against a file, with what the reader does when it is wrong). The
"Written fields" table also uses `own` (a value the reader does not read, set as the synthetic test
files of `src/synth_cmx.rs` set it) and `the writer's choice` (a value the reader does not read and
the synthetic test files do not set, chosen by the writer).
Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as
the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the
@@ -126,7 +131,7 @@ file is committed.
| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample |
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) |
| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample |
| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist; in `balloon.cmx`, `PC.CMX` and `squares.cmx`, solid outlines name `rdot` entry 1, whose field 1 is a count of 0 | sample |
| R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) |
| R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) |
| R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) |
@@ -142,3 +147,39 @@ file is committed.
| R71 | An `outl` chunk from version 13 holds records up to the one of id 1, whose length the specification's samples give as the bytes left in the chunk less 8. In the version 15 samples the id 1 record holds 130 bytes, 8 bytes follow it, and its body holds an f64 1 at bytes 16 and 48, 45 degrees at byte 84 and 60 at byte 88; the writer writes that layout and those values. A record of id 2 holds a color property list that ends at its empty property, without the fields R66 names after a fill's list | KF L1158-L1244 (the records, type 2 a color property list, and the id 1 length in its samples); S: the 18 `outl` chunks of the LT `testset/15` files without text (each 237 bytes, the id 1 record 130 bytes long with those values and 8 bytes of 0 after it, the id 2 record 43 bytes long) | public-spec (the record types and the length), sample (the values; the reader does not use them) |
| R72 | In the version 15 samples an `mcfg` chunk starts with the tag 1300 and the length of the rest of the chunk, then 4 bytes of 0 (the 12 bytes R10 names), and each `fild` chunk sits in a `LIST filc` of its own inside `LIST filt` | S: the 15 LT `testset/15` files without text (every `mcfg` starts with 1300 and its size less 8; each of their 31 `fild` chunks is the only chunk of a `LIST filc`) | sample (the reader skips the 12 bytes and finds `fild` chunks at any depth) |
| R73 | The specification reads the id in a container's argument 8005 (R46) as the stored u32 plus 1, halved, and the `spnd` id as stored. Sample files hold the same stored u32 in both places, even ids included, which the halved reading would not match. The writer numbers containers 1, 2, 3 and so on, and writes the same number in the clipped group's `spnd` | KF L799-L807 (`powerclip_id`), L2305-L2312 (`spnd`); S: the container and `spnd` of LT `powerclipsquare_blackfill_whiterectangleinside.cdr` of `testset/12` (156091928) and `powerclipsquare_blackfill_whiterectangleinside_cdr15.cdr` (1), the eight UC files `corel_powerclip_*` of versions 7 to 13 (47834832) and TDF 114901 (515235504) | sample (the halved reading: not followed) |
| R74 | `rscr`: a u16 count, then one field list per screen entry, which a `rotl` entry names (R58). The reader does not read it; the `.cmx` writer writes one entry whose field 1 holds the 13 bytes `00 00 3c 00 00 00 00 00 40 a5 ae 02 00` | S: each of the nine CX files with 32-bit coordinates has an `rscr` of one entry with a 13-byte field 1, these bytes in seven of them (`bars.cmx` and `thatch.cmx` differ in bytes 2 and 8 to 11) | sample |
## Written fields
`src/cmx_write.rs` writes `.cmx` files in the layouts of the rows above, nothing else. The table
lists every field it sets. `own` marks a value the reader does not read, which the writer sets as
the synthetic test files of `src/synth_cmx.rs` set it. The header's offsets at bytes 84 to 95, the
index chunks (`LIST indx`), the instruction counts and file offsets that the CX files also keep in
their page, layer and group records, and the bounds they keep in layer and group records are not
written: no public source describes
them, and the reader finds every chunk by its id and walks the instructions in order.
| Field written | Rows | Status |
|---|---|---|
| The RIFF form `CMX1`, chunk ids and sizes, a pad byte after an odd body | R53 | sample |
| Chunk order: `cont`, the `page` chunks, then `rclr`, `rpen`, `rott`, `rdot`, `rotl`, `rota` and `rscr` | R53 | own (the reader finds each chunk by its id) |
| `cont`: `4` at byte 52, the unit 1e-7 m as an f64 at bytes 64 to 72 | R54 | sample |
| `cont`: `2` at bytes 48 and 54, zeros elsewhere, 180 bytes | R54 | own |
| Table counts and field lists | R55 | sample |
| `rclr` field 10: a property list with part 1, the color record (model, palette 5, 4 zero bytes, 4 values), and for a spot color part 3, its name; models 2 (CMYK in percent), 5 (blue, green, red), 9 (gray), 20 (registration) and 21 (blue, green, red at the tint, and the tint in percent) | R11, R14, R56 | public-notes (field 10), public-spec (the models) |
| `rpen` field 1: the width | R57 | public-notes |
| `rpen` field 1 after the width: an aspect of 100, an angle of 0, a matrix type of 1 | R57 | own |
| `rott` field 1: the flags 2, 4, 8 and 16, the caps and the join | R57 | public-notes |
| `rdot` field 1: a count and the lengths in whole outline widths | R57 | public-notes |
| `rdot` field 1 of a solid outline's pattern: a count of 0 | R57, R58 | sample |
| `rotl` field 1: six entries, the screen and the arrowhead pair always 1, a solid outline's dash pattern the entry with a count of 0 | R58 | sample |
| `rota`: one pair of 0 | R59 | sample |
| `rscr`: one screen entry, its field 1 as the sample files write it | R74 | sample |
| Instructions in the short form, and the long form past 65,534 bytes | R60 | sample (short form), public-notes (long form) |
| Begin page, field 1: the page number (from 1), a u32 of 0, the left, top, right and bottom edges of the page's curves (of the page around its center when it has none; all 0 for a page without a size) | R61 | sample (page number 1, the edges), own (the later numbers, the edges of a page with no curves or no size) |
| Begin page, field 4: the page's width and height | R61 | public-notes |
| Begin layer, field 1: the page number and the layer number (u16 each, from 1), then 8 zero bytes, then the name as a u16 byte count and 8-bit characters | R62 | sample (the numbers: `balloon.cmx` and `PC.CMX` number their four layers `01 00 01 00` to `01 00 04 00`; the name), own (the 8 bytes) |
| Begin layer, field 4: the name as a u32 count of UTF-16 code units and the units | R62 | public-notes |
| Begin group with field 1 of 26 zero bytes; end layer, group and page with no fields | R60 | own (the bodies are not read) |
| Curve, field 1: rendering attributes with a uniform fill (type 1, the color entry, screen entry 1) and an outline entry | R63, R74 | sample (the uniform fills of `bars.cmx`, `balloon.cmx` and `PC.CMX` name screen 1) |
| Curve, field 2: the point count, the points as i32 and a type byte each, bit 2 set on every move, line and curve end node and clear on control points, bit 3 on the first and last nodes of a closed subpath that fits in one curve; a closed subpath cut into open pieces gets a line back to its start added when its last point is elsewhere; at most 7,281 points | R16, R62 | sample (the layout), own (bit 2 on the nodes the synthetic files set it on), the writer's choice (bit 2 on a closing node, which the synthetic files leave clear) |
+32 -2
View File
@@ -97,6 +97,36 @@ arrowheads and lenses are not read; the drawing's `warnings` name each kind it h
path is left out and the objects it clips are read without it. Files in big-endian byte order and
files with 16-bit coordinates are refused.
`write_cmx` writes a drawing as a `.cmx` file with 32-bit coordinates in the layouts `read_cmx`
reads, so that `read_cmx` leaves nothing out because of the `Limits` given: pages with their
sizes, layers with their names, groups, and curves with uniform fills and outlines. What the file
holds differently from the drawing is reported, as below. Rectangles and ellipses are
written as curves, and a clipping container as a group of its fill, the objects it clips
(unclipped) and its outline. A rounded rectangle scaled differently along its two sides gets round
corners, not stretched ones. Hidden layers, groups and shapes, guide and grid layers, guidelines
and master layers are left out; opacity, blend modes, fill rules and locked states are not
written, desktop layers are written as drawing layers, and a spot color with no name opens as a
process color; every use of a named spot color takes the look of its use at the strongest tint
among the uses whose look is known.
`write_cmx` returns an error, and writes nothing, for a coordinate, page side or outline width
past the 32-bit range, a negative or NaN outline width, a page side that rounds to 0, more than
65,535 pages, layers on a page or different colors, pens, line types, dash patterns or outlines, a
dash pattern of more than 32,765 lengths, groups nested deeper than the limits allow, more chunks,
objects, coordinates or dashes than a read within the limits takes, a file longer than their input
size, and a chunk past its 32-bit size. Otherwise the returned `Written` reports paths split or cut into several curves, dashes
rounded to whole outline widths, nonzero fills that may fill differently, names that open
shortened, spot colors at a tint too low to keep their look, with no name or with no known look
(written black), uses of one ink with different looks, and what was left out or written opaque,
unclipped or unlocked.
The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets
inside page, layer and group records, and the bounds inside layer and group records are not
written, so a reader must find the chunks by their ids and walk the instructions in order, as
`read_cmx` does. The record of a page with a size holds the edges of its curves, or of the page
when it has none. `PROVENANCE.md`'s "Written
fields" table lists every field the `.cmx` writer sets.
## Writing
`write` writes a drawing as a `.cdr` file of version 15: a ZIP package whose first member,
@@ -157,8 +187,8 @@ degree of its angle.
## Provenance
`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writer
needs, with their public sources and status.
`PROVENANCE.md` lists every record layout the reader relies on, and the rows only the writers
need, with their public sources and status.
Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row.
The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the
`synth` feature); no third-party file is committed.
File diff suppressed because it is too large. Load diff
+34 -2
View File
@@ -11,7 +11,7 @@
//! panic.
//!
//! [`write()`] writes a [`Drawing`] as a `.cdr` file of version 15, laying out each record as the
//! reader reads it. Nothing here writes `.cmx` files.
//! reader reads it. [`write_cmx`] writes `.cmx` files in the layouts the reader reads.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -20,6 +20,7 @@ use std::fmt;
mod build;
mod bytes;
mod cmx;
mod cmx_write;
mod geometry;
mod inline;
mod layout;
@@ -38,6 +39,7 @@ mod wl;
mod write;
mod zip;
pub use cmx_write::{MAX_CURVE_POINTS, Written};
pub use limits::Limits;
pub use model::{Drawing, Warning};
pub use preview::{Preview, PreviewFormat, preview};
@@ -66,7 +68,8 @@ pub enum Error {
Version(u16),
/// A container structure that doesn't parse.
Damaged(&'static str),
/// Past one of the [`Limits`].
/// Past one of the [`Limits`]; from [`write_cmx`], also past what a `.cmx` file holds, or an
/// outline width that is negative or NaN.
Limit(&'static str),
/// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that
/// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates; a
@@ -118,3 +121,32 @@ pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
let mut budget = limits::Budget::new(limits);
cmx::drawing(bytes, &mut budget)
}
/// Write `drawing` as a `.cmx` exchange file with 32-bit coordinates, in the layouts
/// [`read_cmx`] reads: its pages, layers, groups and shapes (as curves) with uniform fills and
/// outlines. [`read_cmx`] reading the file within `limits` leaves nothing out because of them;
/// what the file holds differently from the drawing, such as a name the reader shortens, is
/// reported in [`Written`].
///
/// It fails with [`Error::Limit`], and writes nothing, for:
/// - a coordinate, page side or outline width past the 32-bit range, a negative or NaN outline
/// width, or a page side that rounds to 0;
/// - more than 65,535 pages, layers on a page, or different colors, pens, line types, dash
/// patterns or outlines, or a dash pattern of more than 32,765 lengths;
/// - groups nested deeper than the depth of `limits`, or more chunks, objects, coordinates or
/// dashes than a read within `limits` takes;
/// - a file longer than the input size of `limits`, or a chunk past what its 32-bit size holds.
///
/// [`Written`] reports what the file holds differently from the drawing; its fields name each
/// case. A rounded rectangle under a scale that keeps right angles but differs along its sides is
/// written with round corners of its radii times the square root of the scales' product, not with
/// stretched corners, and is not reported.
///
/// The header's index offsets, the index chunks (`LIST indx`), the instruction counts and offsets
/// inside page, layer and group records, and the bounds inside layer and group records are not
/// written, so a reader must find the chunks by their ids and walk the instructions in order, as
/// [`read_cmx`] does. The record of a page with a size holds the edges of its curves, or of the
/// page when it has none.
pub fn write_cmx(drawing: &Drawing, limits: Limits) -> Result<Written, Error> {
cmx_write::write(drawing, limits)
}
+3 -3
View File
@@ -15,7 +15,7 @@ const MAX_SKIPPED: usize = 4;
const MAX_OUTLINE_RECORDS: usize = 16;
/// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of
/// a layer's.
const MAX_NAME: usize = 256;
pub(crate) const MAX_NAME: usize = 256;
/// A header field: u16 in short files, u32 otherwise.
fn word(r: &mut Rd, p: &Profile) -> Option<usize> {
@@ -260,7 +260,7 @@ fn b_tint(b: &[u8]) -> Option<f32> {
}
/// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white).
fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] {
pub(crate) fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] {
if tint <= 0.0 {
return rgb;
}
@@ -486,7 +486,7 @@ fn with_hash(name: String, hash: Option<u64>) -> String {
/// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes
/// are Latin-1.
const CP1252_HIGH: [char; 32] = [
pub(crate) const CP1252_HIGH: [char; 32] = [
'€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–',
'—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ',
];
File diff suppressed because it is too large. Load diff
+1
View File
@@ -4,6 +4,7 @@
mod bench;
mod cmx;
mod cmx_write;
mod provenance;
mod read;
mod write;
@@ -282,6 +282,58 @@ fn a_late_reply_from_before_sign_out_is_dropped() {
);
}
/// File › Open calls `start` on every frame. A sign-out has no answer, so nothing orders it
/// before a request the next frame sends. A provider that still holds the session answers that
/// request with the departed account, and the window must not show that account or its files.
#[test]
fn a_page_drawn_after_sign_out_does_not_bring_the_account_back() {
let (mut app, held, _log) = two_tabs();
start(&mut app);
let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap();
post.send(Event::Account(Ok(account("Previous Person"))));
held.take(|j| matches!(j, Job::List(_))).unwrap();
drain(&mut app, &egui::Context::default());
sign_out(&mut app);
start(&mut app);
// Whatever the frame asked is answered as a provider that has not yet ended the session would.
while let Some((job, post)) = held.take(|j| matches!(j, Job::Account | Job::List(_))) {
match job {
Job::Account => post.send(Event::Account(Ok(account("Previous Person")))),
Job::List(path) => post.send(Event::Listed { path, entries: Ok(vec![entry("/Payroll 2026.note", "p1")]) }),
_ => {}
}
}
drain(&mut app, &egui::Context::default());
let r = report(&app);
assert!(
r["account"].is_null() && r["entries"].as_array().is_some_and(Vec::is_empty),
"signed out, yet account={} entries={}",
r["account"],
r["entries"]
);
sign_in(&mut app);
let (_, post) = held.take(|j| matches!(j, Job::SignIn)).unwrap();
post.send(Event::Account(Ok(account("Ada"))));
drain(&mut app, &egui::Context::default());
start(&mut app);
assert!(held.take(|j| matches!(j, Job::List(_))).is_some(), "the next sign-in lists the root folder again");
}
/// Save As while signed out has no account to land in. A provider that has not ended the session
/// yet would create the file in the account that is leaving.
#[test]
fn save_as_after_sign_out_is_refused_until_the_next_sign_in() {
let (mut app, held, _log) = two_tabs();
start(&mut app);
let (_, post) = held.take(|j| matches!(j, Job::Account)).unwrap();
post.send(Event::Account(Ok(account("Previous Person"))));
drain(&mut app, &egui::Context::default());
sign_out(&mut app);
let refused = save_as(&mut app, "", "Plan");
assert!(refused.is_err(), "signed out, yet Save As went ahead: {refused:?}");
assert!(held.take(|j| matches!(j, Job::Create { .. })).is_none(), "nothing is created while signed out");
}
/// Save as a copy, then the first click on the Save As page is refused (no name typed yet). The
/// second click, with a name, must still copy the conflicted document A, not the active tab B.
#[test]
+22 -1
View File
@@ -191,6 +191,11 @@ pub struct CloudFiles {
pub account_fault: Option<Fault>,
/// The account is asked for once per run. A frame never asks again.
asked_account: bool,
/// Set by [`sign_out`] and cleared by [`sign_in`]. While it is set, the
/// pages ask the service nothing. [`Job::SignOut`] has no answer and no
/// order against a later job, so a provider that still holds the session
/// could answer an account or listing request with the departed account.
signed_out: bool,
/// The folder being browsed. Shared by the Open and Save As pages, which
/// are never on screen together.
pub mine: Folder,
@@ -249,6 +254,7 @@ impl CloudFiles {
account: None,
account_fault: None,
asked_account: false,
signed_out: false,
mine: Folder::default(),
shared: Folder::default(),
source: Source::default(),
@@ -344,8 +350,10 @@ pub fn submit<A: CloudApp>(app: &A, job: Job) {
}
/// Asks who is signed in, once per run, and lists the root folder.
///
/// After [`sign_out`] it asks nothing until the next [`sign_in`].
pub fn start<A: CloudApp>(app: &mut A) {
if !available(app) {
if !available(app) || app.cloud().signed_out {
return;
}
if !app.cloud().asked_account {
@@ -375,6 +383,7 @@ pub fn sign_in<A: CloudApp>(app: &mut A) {
// would then be swallowed by the guard that stops a frame asking twice. A
// button that does nothing the second time reads as a broken button.
cloud.asked_account = true;
cloud.signed_out = false;
cloud.link = None;
cloud.status = Some(working);
// A new session. A job the previous one left outstanding may never
@@ -402,6 +411,10 @@ pub fn sign_out<A: CloudApp>(app: &mut A) {
cloud.account = None;
cloud.account_fault = None;
cloud.asked_account = false;
// File › Open and Save As call `start` on every frame. Without this, the
// next frame would ask who is signed in and list the root folder while
// the sign-out may still be on its way.
cloud.signed_out = true;
cloud.link = None;
cloud.mine = Folder::default();
cloud.shared = Folder::default();
@@ -413,8 +426,13 @@ pub fn sign_out<A: CloudApp>(app: &mut A) {
// that never heard back does not refuse every one after it forever.
cloud.account_generation.fetch_add(1, Ordering::Relaxed);
cloud.busy = None;
cloud.sharing_save = false;
cloud.relist_after_sign_in = false;
cloud.save_as_target = None;
// Sharing went with the account: Share is not offered on the old
// account's answer, and a sheet open on one of its documents closes. The
// next sign-in asks the provider again.
app.sharing().signed_out();
submit(app, Job::SignOut);
}
@@ -630,6 +648,9 @@ pub fn save_as<A: CloudApp>(app: &mut A, folder: &str, name: &str) -> Result<Jso
if app.cloud().relist_after_sign_in {
return Err("wait for the sign-in to finish".to_owned());
}
if app.cloud().signed_out {
return Err(app.tr("Sign in to save to the cloud"));
}
// A document that does not exist yet has no content type to read. The
// name a person just typed is the whole of what was asked for.
let bytes = app.encode(uid, Destination::new(&name))?;
+5
View File
@@ -42,6 +42,11 @@ fn header<A: CloudApp>(app: &mut A, ui: &mut Ui) {
let line = if account.display.is_empty() { app.tr("Signed in") } else { account.display.clone() };
dim(ui, &style, &line);
}
// Nothing is asked after a sign-out, so there is nothing to wait for.
(None, None) if app.cloud().signed_out => {
let signed_out = app.tr("Signed out");
dim(ui, &style, &signed_out);
}
(None, None) => {
let waiting = app.tr("Connecting to your cloud account…");
dim(ui, &style, &waiting);
+43
View File
@@ -435,6 +435,49 @@ fn signing_out_forgets_everything_this_window_knew() {
assert!(jobs.lock().unwrap().iter().any(|j| matches!(j, Job::SignOut)), "the service is told, so the saved token goes too");
}
/// A sharing service that says it can share and answers nothing else.
struct Shares;
impl crate::share::ShareBackend for Shares {
fn submit(&self, request: crate::share::Request, reply: crate::share::Replier) {
if request == crate::share::Request::Capabilities {
reply.answer(crate::share::Answer::Capabilities { capabilities: vec![Capability::Sharing], linked: true });
}
}
}
#[test]
fn signing_out_takes_sharing_with_it() {
let (mut app, _jobs, ctx) = wired();
app.share.connect(Shares);
// Enough frames for an account answer to land, the provider to be asked,
// and its answer to be read.
let frames = |app: &mut Notebook| {
for _ in 0..3 {
ctx.begin_pass(Default::default());
app.share.show(&ctx);
pump(app, &ctx);
ctx.end_pass().textures_delta.clear();
}
};
frames(&mut app);
assert!(app.share.available());
app.share.open("/Minutes.note", "Minutes");
assert!(app.share.is_open());
sign_out(&mut app);
assert!(!app.share.is_open(), "a sheet open on the old account's document closes");
assert!(!app.share.available(), "Share is not offered on the old account's answer");
// The provider is not asked again while the sign-out may still be on its
// way, so a service that still has the old account cannot offer it back.
frames(&mut app);
assert!(!app.share.available(), "nobody is signed in");
sign_in(&mut app);
frames(&mut app);
assert!(app.share.available(), "the next sign-in asks again");
}
#[test]
fn an_answer_queued_before_the_session_changed_is_dropped() {
let (mut app, _jobs, ctx) = wired();
+34 -8
View File
@@ -338,6 +338,10 @@ pub struct ShareDialog {
provider: Option<Provider>,
/// When the capability question was last asked.
asked: Option<f64>,
/// The last request number issued before the latest [`ShareDialog::refresh`]
/// or [`ShareDialog::connect`]. A capabilities answer to that request or an
/// earlier one describes the account as it was, and is ignored.
capabilities_after: u64,
open: Option<Sheet>,
/// Keyed by the URL the contact carried, so reopening the dialog does not
/// fetch the same faces again.
@@ -370,6 +374,7 @@ impl ShareDialog {
seq: 0,
provider: None,
asked: None,
capabilities_after: 0,
open: None,
avatars: HashMap::new(),
wants_save: None,
@@ -387,6 +392,7 @@ impl ShareDialog {
self.backend = Some(Box::new(backend));
self.provider = None;
self.asked = None;
self.capabilities_after = self.seq;
}
pub fn connected(&self) -> bool {
@@ -413,10 +419,25 @@ impl ShareDialog {
/// The answer is kept once it arrives, so a host that signs somebody
/// in after the first answer has to say so. Without this the dialog
/// keeps the answer it got while nobody was signed in, and Share
/// stays unavailable for the rest of the run.
/// stays unavailable for the rest of the run. An answer to a question
/// asked before the refresh is ignored when it arrives.
pub fn refresh(&mut self) {
self.provider = None;
self.asked = None;
self.capabilities_after = self.seq;
}
/// Forget sharing for an account that signed out.
///
/// Closes the sheet and offers nothing until [`ShareDialog::refresh`],
/// which the next sign-in calls. The provider is not asked again here: a
/// question asked before the sign-out reaches the service would describe
/// the account that is leaving. Answers to earlier questions are ignored.
pub fn signed_out(&mut self) {
self.close();
self.provider = Some(Provider { sharing: false, contacts: false, mail: false, links: false, key: false, key_required: false });
self.asked = None;
self.capabilities_after = self.seq;
}
pub fn available(&self) -> bool {
@@ -639,6 +660,8 @@ impl ShareDialog {
// once the open sheet is no longer borrowed.
let mut reload = None;
match answer {
// Asked before the account changed: it describes the old one.
Answer::Capabilities { .. } if seq <= self.capabilities_after => {}
Answer::Capabilities { capabilities, linked } => {
self.provider = Some(Provider {
sharing: linked && capabilities.contains(&Capability::Sharing),
@@ -717,13 +740,16 @@ impl ShareDialog {
}
}
Answer::Linked => {
// An account arrived, so the list is stale.
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);
// 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);
}
}
}
Answer::Withdrawn { share_id } => {
+27
View File
@@ -113,6 +113,24 @@ fn nothing_is_offered_until_the_service_says_sharing_exists() {
assert!(dialog.is_open());
}
#[test]
fn a_capabilities_answer_asked_before_a_refresh_is_ignored() {
let ctx = Context::default();
let backend = Silent::default();
let mut dialog = ShareDialog::new();
dialog.connect(backend.clone());
dialog.collect(&ctx);
dialog.refresh();
dialog.collect(&ctx);
assert_eq!(backend.seen(), vec![Request::Capabilities, Request::Capabilities], "the refresh asks again");
// The first question was about the account before the refresh.
dialog.receive(&ctx, 1, Ok(everything()));
assert!(!dialog.available(), "the old account's answer must not offer Share");
dialog.receive(&ctx, 2, Ok(everything()));
assert!(dialog.available());
}
#[test]
fn an_unlinked_account_cannot_share_even_where_the_provider_can() {
let ctx = Context::default();
@@ -580,6 +598,15 @@ fn a_closed_dialog_still_collects_and_reports_nothing() {
assert!(shared.is_empty() && failed.is_empty());
}
#[test]
fn a_link_answer_arriving_with_no_sheet_open_asks_for_nothing() {
let (ctx, mut dialog, backend) = ready();
dialog.signed_out();
let before = backend.seen().len();
dialog.receive(&ctx, 99, Ok(Answer::Linked));
assert_eq!(backend.seen().len(), before);
}
#[test]
fn pressing_return_takes_the_first_match_or_an_address() {
let (_ctx, mut dialog, _) = ready();
+2 -2
View File
@@ -59,7 +59,7 @@ pub enum ChosenColor {
pub struct ColorChoiceOutput {
/// The choice's response.
pub response: Response,
/// The row chosen this pass; the host stores it.
/// The row committed this pass; the host stores it. Navigating an open popup reports no choice.
pub chosen: Option<ChosenColor>,
/// "Select Custom Color…" was chosen, for this pass only: the app opens its colour picker from the request (key
/// [`ColorChoice::CUSTOM_KEY`], the custom colour) and, on OK, stores the colour and chooses
@@ -151,7 +151,7 @@ impl<'a> ColorChoice<'a> {
entries.push(Entry::separator());
entries.push(Entry::new(Row::SelectCustom, words.select_custom.as_str().to_owned()));
let shown = Select::new(self.label.clone(), Bind::given(row), &entries).enabled(self.enabled).show(ui);
let picked = shown.value().cloned();
let picked = shown.events.committed().cloned();
let mut pick_color = None;
let chosen = match picked {
Some(Row::Named(id)) => Some(ChosenColor::Named(id)),
+10 -5
View File
@@ -440,8 +440,13 @@ impl<P: Clone + Send + Sync + 'static> Component for SwatchPair<'_, P> {
flags.set(Flags::MIXED, self.wells[i].paint.same().is_none());
flags.set(Flags::CHECKED, well == active);
let shape = if cx.style.round { HitShape::circle(at.center(), at.width() / 2.0) } else { HitShape::Rect(at) };
let part =
cx.part(WELL.at(i as u64), shape).sense(sense).priority(HitPriority::new(HitLevel::Body, u8::from(front))).flags(flags).focusable();
let part = cx
.part(WELL.at(i as u64), shape)
.sense(sense)
.priority(HitPriority::new(HitLevel::Body, u8::from(front)))
.flags(flags)
.focusable()
.tooltip(self.wells[i].label.clone());
// Focus arrives at the active well, so arriving makes no other well active.
let part = if well == active { part.selected() } else { part };
if self.popover {
@@ -449,10 +454,10 @@ impl<P: Clone + Send + Sync + 'static> Component for SwatchPair<'_, P> {
}
}
let buttons = self.button_rects(cx.style);
for (key, button, shown) in [(DEFAULT, buttons[0], self.default_button.is_some()), (SWAP, buttons[1], self.swap_button.is_some())] {
if shown {
for (key, button, name) in [(DEFAULT, buttons[0], &self.default_button), (SWAP, buttons[1], &self.swap_button)] {
if let Some(name) = name {
let at = flow.to_physical(button.translate(rect.min.to_vec2()));
cx.part(key, at).sense(Sense::CLICK).pointer_only("The host's Default Colours and Swap Colours commands");
cx.part(key, at).sense(Sense::CLICK).tooltip(name.clone()).pointer_only("The host's Default Colours and Swap Colours commands");
}
}
cx.roving(Roving::new(NavShape::Flat));
+43 -15
View File
@@ -3,15 +3,15 @@
use craft_behavior::{EditEvent, IconId, Mixed, Selection};
use craft_theme::Srgba;
use craft_ui::choice::{SwatchSpacing, SwatchTable};
use craft_ui::contract::{ActivateOn, Bind, Held, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _};
use craft_ui::choice::{SwatchSpacing, SwatchTable, SwatchTableOutput};
use craft_ui::contract::{ActivateOn, Bind, Held, LeadOnOpen, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _, SpaceAction};
use craft_ui::display::{Shade, Text};
use craft_ui::layout_components::Stack;
use craft_ui::runtime::env::Label;
use craft_ui::runtime::memory::StageAccess;
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::style::TypeRole;
use egui::{Response, Ui};
use egui::{PointerButton, Response, Ui};
use std::sync::Arc;
#[cfg(feature = "suite")]
@@ -35,6 +35,9 @@ pub struct SwatchPaletteOutput {
pub pick_color: Option<ColorRequest>,
/// Every swatch click of this pass, also a click on the colour already bound, which files no `edit`.
pub picked: Option<Srgba>,
/// The picked entry's index in the palette, including a swatch with the bound colour or a duplicate colour.
/// The recent row and the Other… cell do not report a swatch index.
pub picked_swatch: Option<usize>,
}
impl Outcome for SwatchPaletteOutput {
@@ -65,6 +68,7 @@ pub struct SwatchPalette<'a> {
label: Label,
color: PaletteColor<'a>,
swatches: &'a [(Label, Srgba)],
selected_swatch: Option<usize>,
spacing: SwatchSpacing,
drag: Option<TableMap>,
/// The Other… cell: the key of its colour request and its name.
@@ -109,7 +113,7 @@ impl PaletteColor<'_> {
#[derive(Clone, Copy)]
enum Pick {
/// A swatch or a recent colour.
Color(Srgba),
Color { color: Srgba, swatch: Option<usize> },
/// The Other… cell.
Other,
}
@@ -119,6 +123,15 @@ fn cell_of(swatches: &[(Label, Srgba)], color: Option<Srgba>) -> Selection<usize
color.and_then(|color| swatches.iter().position(|(_, c)| c.to_rgba() == color.to_rgba())).map_or_else(Selection::default, Selection::single)
}
/// A completed activation, or the table's existing secondary-button pick.
fn picked_cell(table: &SwatchTableOutput, ui: &Ui) -> Option<usize> {
table.open.or_else(|| {
table.selected.filter(|_| {
ui.input(|input| input.pointer.button_pressed(PointerButton::Secondary) || input.pointer.button_released(PointerButton::Secondary))
})
})
}
impl<'a> SwatchPalette<'a> {
/// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`.
pub fn new(label: impl Into<Label>, color: Bind<'a, Srgba>, swatches: &'a [(Label, Srgba)]) -> Self {
@@ -126,6 +139,7 @@ impl<'a> SwatchPalette<'a> {
label: label.into(),
color: PaletteColor::Color(Held::new(color)),
swatches,
selected_swatch: None,
spacing: SwatchSpacing::Touching,
drag: None,
other: None,
@@ -141,6 +155,7 @@ impl<'a> SwatchPalette<'a> {
label: label.into(),
color: PaletteColor::Optional(color),
swatches,
selected_swatch: None,
spacing: SwatchSpacing::Touching,
drag: None,
other: None,
@@ -148,6 +163,13 @@ impl<'a> SwatchPalette<'a> {
}
}
/// Selects the entry at `index` when the host knows the swatch's identity. The palette uses the
/// bound colour to find a selection when the index is absent or out of range.
pub fn selected_swatch(mut self, index: Option<usize>) -> Self {
self.selected_swatch = index;
self
}
/// The gap between the cells, passed on to its `SwatchTable`.
pub fn spacing(mut self, spacing: SwatchSpacing) -> Self {
self.spacing = spacing;
@@ -179,7 +201,7 @@ impl<'a> SwatchPalette<'a> {
/// Shows the palette.
pub fn show(self, ui: &mut Ui) -> SwatchPaletteOutput {
let SwatchPalette { label, mut color, swatches, spacing, drag, other, recent } = self;
let SwatchPalette { label, mut color, swatches, selected_swatch, spacing, drag, other, recent } = self;
let recent = recent.filter(|(_, colors)| !colors.is_empty());
let recent_cells: Vec<(Label, Srgba)> =
recent.iter().flat_map(|(_, colors)| colors.iter()).map(|color| (Label::from(color.to_hex()), *color)).collect();
@@ -187,7 +209,8 @@ impl<'a> SwatchPalette<'a> {
let mut shown = Stack::new().show(ui, |ui, cx| {
let before = color.read(cx)?;
let bound = before.same().copied().flatten();
let mut current = cell_of(swatches, bound);
let preferred = selected_swatch.filter(|&index| index < swatches.len());
let mut current = preferred.map_or_else(|| cell_of(swatches, bound), Selection::single);
// A palette of recent colours alone has no grid: an empty table would be an empty list box in the tree.
let mut pick = None;
if !swatches.is_empty() || other.is_some() {
@@ -197,7 +220,11 @@ impl<'a> SwatchPalette<'a> {
.wells(true)
.spacing(spacing)
.activate(ActivateOn::Click)
.space(SpaceAction::ActivateLead)
.selection(Bind::bound(&mut current));
if let Some(index) = preferred {
table = table.rows_stamp(index as u64).lead_on_open(LeadOnOpen::Selected);
}
if let Some(map) = &drag {
table = map(table);
}
@@ -207,8 +234,8 @@ impl<'a> SwatchPalette<'a> {
let table = table.show_all(ui);
// The Other… cell is keyed `swatches.len()`, past the swatches. A click selects on its press and activates
// on its release, so only the activation files the request: one request for one click.
pick = table.selected.or(table.open).and_then(|at| match swatches.get(at) {
Some((_, picked)) => Some(Pick::Color(*picked)),
pick = picked_cell(&table, ui).and_then(|at| match swatches.get(at) {
Some((_, picked)) => Some(Pick::Color { color: *picked, swatch: Some(at) }),
None => (other.is_some() && table.open == Some(at) && at == swatches.len()).then_some(Pick::Other),
});
}
@@ -219,10 +246,11 @@ impl<'a> SwatchPalette<'a> {
.tips(true)
.wells(true)
.activate(ActivateOn::Click)
.space(SpaceAction::ActivateLead)
.selection(Bind::bound(&mut current))
.show_all(ui);
if let Some((_, picked)) = row.selected.or(row.open).and_then(|at| recent_cells.get(at)) {
pick = Some(Pick::Color(*picked));
if let Some((_, picked)) = picked_cell(&row, ui).and_then(|at| recent_cells.get(at)) {
pick = Some(Pick::Color { color: *picked, swatch: None });
}
}
Some((before, pick))
@@ -235,21 +263,21 @@ impl<'a> SwatchPalette<'a> {
match pick? {
Pick::Other => {
let key = other.as_ref().map(|(key, _)| key.clone())?;
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone()))))
Some((None, None, Some(ColorRequest::new(key, bound).title(name.clone())), None))
}
Pick::Color(after) => {
Pick::Color { color: after, swatch } => {
let unchanged = bound.is_some_and(|bound| bound.to_rgba() == after.to_rgba());
let edit = (!unchanged).then(|| {
color.write(cx, before, after, name.as_str());
let reported = bound.map_or(Mixed::Mixed, Mixed::Same);
EditEvent::set(reported, after, Arc::from(name.as_str()), None)
});
Some((Some(after), edit, None))
Some((Some(after), edit, None, swatch))
}
}
})
.flatten();
let (picked, edit, pick_color) = settled.unwrap_or((None, None, None));
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked }
let (picked, edit, pick_color, picked_swatch) = settled.unwrap_or((None, None, None, None));
SwatchPaletteOutput { response: shown.output, edit, pick_color, picked, picked_swatch }
}
}
+20 -3
View File
@@ -446,6 +446,7 @@ pub struct ColorPanel<'a> {
dynamic: bool,
layout: ColorPanelLayout,
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
buttons: Option<[Label; 2]>,
edited: Option<Option<PickedColor>>,
shown: Option<ColorPanelShown>,
recent: Option<&'a [Srgba]>,
@@ -469,6 +470,7 @@ fn recent_setup<P: Send + Sync + 'static>(map: impl Fn(usize) -> Option<P> + Sen
#[derive(Clone, Copy)]
struct Inputs<'a> {
wells: Option<&'a [PairWell; 2]>,
buttons: Option<&'a [Label; 2]>,
edited: Option<&'a Option<PickedColor>>,
shown: &'a ColorPanelShown,
recent: Option<&'a [Srgba]>,
@@ -486,6 +488,7 @@ impl<'a> ColorPanel<'a> {
dynamic: true,
layout: ColorPanelLayout::default(),
wells: None,
buttons: None,
edited: None,
shown: None,
recent: None,
@@ -528,6 +531,14 @@ impl<'a> ColorPanel<'a> {
self
}
/// The names of the [`ColorPanelLayout::FillStroke`] layout's swap and default buttons, which are also their
/// tooltips: a host names the keys of its own commands there ("Swap Fill and Stroke (Shift+X)"). The panel's
/// words by default.
pub fn buttons(mut self, swap: impl Into<Label>, default: impl Into<Label>) -> Self {
self.buttons = Some([swap.into(), default.into()]);
self
}
/// The colour the rows edit, with its model values; `None` disables the rows (mixed, None, a pattern). The edited
/// well's colour by default.
pub fn edited(mut self, color: Option<PickedColor>) -> Self {
@@ -562,7 +573,7 @@ impl<'a> ColorPanel<'a> {
/// Shows the panel and returns this pass's edits and requests.
pub fn show(self, ui: &mut Ui) -> ColorPanelOutput {
let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, edited, shown: rows, recent, recent_setup, gamut } = self;
let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, buttons, edited, shown: rows, recent, recent_setup, gamut } = self;
let env = Env::of(ui);
let (words, dialog) = (env.words::<ColorPanelWords>(), env.words::<ColorPickerDialogWords>());
let mut held = Held::new(state);
@@ -598,6 +609,7 @@ impl<'a> ColorPanel<'a> {
dialog: &dialog,
inputs: Inputs {
wells: wells.as_ref(),
buttons: buttons.as_ref(),
edited: edited.as_ref(),
shown: rows.as_ref().unwrap_or(&default_rows),
recent,
@@ -982,7 +994,8 @@ impl Body<'_> {
}
/// The foreground over the background (the host's wells when it gave them): a click on the other well edits it, a
/// click on the edited one asks for the picker. `FillStroke` adds the pair's swap and default buttons.
/// click on the edited one asks for the picker. `FillStroke` adds the pair's swap and default buttons, named by the
/// host's [`ColorPanel::buttons`] when it gave them.
fn wells(&mut self, ui: &mut Ui) {
let was = self.active;
let mut active = was;
@@ -992,7 +1005,11 @@ impl Body<'_> {
let pair = SwatchPair::<()>::new(self.words.wells.clone(), wells, Bind::bound(&mut active)).popover(false).frame_active(true);
let pair = match self.layout {
ColorPanelLayout::ForegroundBackground => pair,
ColorPanelLayout::FillStroke => pair.swap_button(self.words.swap_colors.clone()).default_button(self.words.default_colors.clone()),
ColorPanelLayout::FillStroke => {
let [swap, default] =
self.inputs.buttons.cloned().unwrap_or_else(|| [self.words.swap_colors.clone(), self.words.default_colors.clone()]);
pair.swap_button(swap).default_button(default)
}
};
let pair = pair.show(ui);
self.active = active;
+5 -1
View File
@@ -642,7 +642,11 @@ pub(super) fn panel_source<'a>(
} else {
entries().filter_map(|e| e.color().map(|color| (e.name.as_str(), color.to_srgb(cmyk)))).collect()
};
PresetSource::new(SwatchInputs { groups, drawn, icons, host }, PresetFns::new(source_rows).thumb(paint_swatch))
let fns = PresetFns::new(source_rows).thumb(paint_swatch).accepts(|_, drag, _, _| {
let groups = matches!(drag.grabbed, SwatchKey::Group(_));
drag.keys.iter().all(|key| matches!(key, SwatchKey::Group(_)) == groups)
});
PresetSource::new(SwatchInputs { groups, drawn, icons, host }, fns)
}
fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>> {
+56 -3
View File
@@ -1,6 +1,6 @@
//! `SwatchesPanel`: the panel body, its state and what it reports.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::rc::Rc;
use std::sync::Arc;
@@ -20,7 +20,7 @@ use craft_ui::primitives::IconSpec;
use craft_ui::runtime::env::{Count, Env};
use egui::{AsIdSalt, IdSalt, Response, Ui};
use super::library::{HostThumb, find_swatch, has, panel_source};
use super::library::{HostThumb, find_swatch, group_of, has, panel_source};
use super::menu::event_edits;
use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords};
use crate::palette::{SwatchGroup, SwatchNote, SwatchReport};
@@ -40,6 +40,7 @@ pub struct SwatchesPanelOutput {
pub edits: Vec<SwatchEdit>,
/// The browser events the panel does not turn into `used` or `edits`, in the order they happened: `Activate`,
/// `Menu`, `DropAt`, `Dropped` and `Reorder`. `Reorder` is also in `edits`; a host runs one of the two.
/// When enabled by [`SwatchesPanel::report_invalid_renames`], rejected inline renames appear here as `Rename`.
pub events: Vec<PresetEvent<SwatchKey>>,
}
@@ -89,16 +90,19 @@ pub struct SwatchesPanel<'a> {
foreground: Srgba,
thumb: Option<HostThumb<'a>>,
tools: Option<ToolsFn<'a>>,
tools_at_start: bool,
drop_zone: Option<DropZone>,
footer: Option<Option<PresetFooterOptions<'a>>>,
reveal: Option<SwatchKey>,
search: bool,
row_icons: Option<RowIconsFn<'a>>,
select: SelectMode,
report_invalid_renames: bool,
takes_drop: Option<DropMaker<'a>>,
payloads: Vec<PayloadAdder<'a>>,
row_items: Option<RowItemsFn<'a>>,
document: Option<IdSalt>,
select_groups: bool,
}
/// What the body decided; `show` stores the state and reports the rest after the real run.
@@ -120,16 +124,19 @@ impl<'a> SwatchesPanel<'a> {
foreground,
thumb: None,
tools: None,
tools_at_start: false,
drop_zone: None,
footer: None,
reveal: None,
search: true,
row_icons: None,
select: SelectMode::Single,
report_invalid_renames: false,
takes_drop: None,
payloads: Vec::new(),
row_items: None,
document: None,
select_groups: false,
}
}
@@ -154,6 +161,12 @@ impl<'a> SwatchesPanel<'a> {
self
}
/// Places the host's tools before the browser controls in the toolbar. Off by default.
pub fn tools_at_start(mut self, at_start: bool) -> Self {
self.tools_at_start = at_start;
self
}
/// Where a drop onto the panel lands.
pub fn drop_zone(mut self, zone: DropZone) -> Self {
self.drop_zone = Some(zone);
@@ -191,6 +204,13 @@ impl<'a> SwatchesPanel<'a> {
self
}
/// Reports committed inline renames rejected by the panel in [`SwatchesPanelOutput::events`], so the host can
/// explain the rejection. Accepted renames produce their usual edit. Off by default.
pub fn report_invalid_renames(mut self, enabled: bool) -> Self {
self.report_invalid_renames = enabled;
self
}
/// A host payload of type `P` can be dropped onto a swatch or between swatches at `place` where `accepts` agrees;
/// the drop comes back as `PresetEvent::Dropped`.
pub fn takes_drop<P: Send + Sync + 'static>(mut self, place: DropPlace, accepts: impl Fn(&P, &DropAt<SwatchKey>) -> bool + 'a) -> Self {
@@ -228,6 +248,12 @@ impl<'a> SwatchesPanel<'a> {
self
}
/// Lets panel interactions select group rows alongside swatches in both views. Off by default.
pub fn select_groups(mut self, enabled: bool) -> Self {
self.select_groups = enabled;
self
}
/// Draws the panel and returns the user's actions this pass.
pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput {
let SwatchesPanel {
@@ -237,16 +263,19 @@ impl<'a> SwatchesPanel<'a> {
foreground,
thumb,
mut tools,
tools_at_start,
drop_zone,
footer,
reveal,
search,
row_icons,
select,
report_invalid_renames,
takes_drop,
payloads,
row_items,
document,
select_groups,
} = self;
let cmyk = cmyk.unwrap_or_else(|| CmykConverter::coated());
let words = Env::of(ui).words::<SwatchesWords>();
@@ -278,8 +307,10 @@ impl<'a> SwatchesPanel<'a> {
let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &source)
.thumb_range(SWATCH_ZOOM)
.toolbar(true)
.tools_at_start(tools_at_start)
.search(search)
.select(select)
.select_groups(select_groups)
.reorder(PresetReorder::items_and_groups())
.selection(Bind::bound(&mut st.selection));
if let Some(id) = document_id {
@@ -311,7 +342,21 @@ impl<'a> SwatchesPanel<'a> {
let mut used = None;
let mut edits = Vec::new();
let mut events = Vec::new();
let deleting_groups: BTreeSet<_> = out
.events
.iter()
.filter_map(|event| match event {
PresetEvent::Delete(key @ SwatchKey::Group(_)) => group_of(groups, key),
_ => None,
})
.collect();
for event in out.events {
if !deleting_groups.is_empty()
&& let PresetEvent::Delete(key @ SwatchKey::Swatch(_)) = &event
&& group_of(groups, key).is_some_and(|group| deleting_groups.contains(&group))
{
continue;
}
if let PresetEvent::Select { key: SwatchKey::Swatch(name), mods, .. } = &event
&& let Some(at) = find_swatch(groups, name)
&& let Some(entry) = groups.get(at.group).and_then(|g| g.entries.get(at.index))
@@ -327,7 +372,15 @@ impl<'a> SwatchesPanel<'a> {
| PresetEvent::Reorder { .. }
)
.then(|| event.clone());
edits.extend(event_edits(groups, &mut st, event, foreground, &words));
// The browser has discarded empty and unchanged names. Keep a live target's attempt for diagnostics
// if translating it into an edit fails. Validation and its selection updates still run in one place.
let attempted_rename =
(report_invalid_renames && matches!(&event, PresetEvent::Rename { key, .. } if live(key))).then(|| event.clone());
let resolved = event_edits(groups, &mut st, event, foreground, &words);
if resolved.is_empty() {
events.extend(attempted_rename);
}
edits.extend(resolved);
events.extend(forwarded);
}
Some(Settled { before_state, st, used, edits, events })
+101
View File
@@ -0,0 +1,101 @@
//! A named/custom color choice reports only a committed row or custom picker request.
use std::cell::RefCell;
use std::rc::Rc;
use craft_color_ui::ui::{ChosenColor, ColorChoice, NamedColor};
use craft_theme::Srgba;
use craft_ui::runtime::requests::ColorRequest;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, vec2};
const RED: Srgba = Srgba::rgb(0.8, 0.1, 0.2);
const BLUE: Srgba = Srgba::rgb(0.1, 0.2, 0.8);
const CUSTOM: Srgba = Srgba::rgb(0.2, 0.6, 0.4);
#[derive(Default)]
struct Reports {
chosen: Vec<ChosenColor>,
requests: Vec<ColorRequest>,
}
struct Rig {
fixture: Fixture,
value: Rc<RefCell<ChosenColor>>,
reports: Rc<RefCell<Reports>>,
}
impl Rig {
fn new(start: ChosenColor, custom: Option<Srgba>) -> Self {
let value = Rc::new(RefCell::new(start));
let reports = Rc::new(RefCell::new(Reports::default()));
let (held, reported) = (value.clone(), reports.clone());
let mut fixture = Fixture::new(move |ui| {
let value = held.borrow().clone();
let shown = ColorChoice::new("Color", &value)
.named([NamedColor::new("red", "Red", Some(RED)), NamedColor::new("blue", "Blue", Some(BLUE))])
.custom(custom)
.show(ui);
if let Some(chosen) = shown.chosen {
*held.borrow_mut() = chosen.clone();
reported.borrow_mut().chosen.push(chosen);
}
reported.borrow_mut().requests.extend(shown.pick_color);
});
fixture.room(vec2(400.0, 240.0)).settle();
Rig { fixture, value, reports }
}
fn open(&mut self) {
let field = self.fixture.by_label("Color").expect("the color choice");
self.fixture.click(&field);
}
}
/// A provisional named row never replaces the host's named or custom choice; Enter reports it once.
#[trial]
fn canceled_color_navigation_keeps_the_hosts_original_choice() {
for original in [ChosenColor::Named("red".into()), ChosenColor::Custom] {
let key = if original == ChosenColor::Custom { Key::ArrowUp } else { Key::ArrowDown };
let mut rig = Rig::new(original.clone(), Some(CUSTOM));
rig.open();
rig.fixture.key(key, Modifiers::NONE).idle(2);
assert_eq!(*rig.value.borrow(), original, "navigation alone does not replace the original color");
assert!(rig.reports.borrow().chosen.is_empty());
rig.fixture.key(Key::Escape, Modifiers::NONE).settle();
assert_eq!(*rig.value.borrow(), original);
assert!(rig.reports.borrow().chosen.is_empty());
assert!(rig.reports.borrow().requests.is_empty());
rig.open();
rig.fixture.key(key, Modifiers::NONE).key(Key::Enter, Modifiers::NONE).settle().idle(2);
assert_eq!(*rig.value.borrow(), ChosenColor::Named("blue".into()));
assert_eq!(rig.reports.borrow().chosen, [ChosenColor::Named("blue".into())]);
assert!(rig.reports.borrow().requests.is_empty());
}
}
/// Proposing Select Custom Color neither requests the picker nor changes the color; Enter requests it once.
#[trial]
fn custom_color_picker_waits_for_a_committed_row() {
for custom in [Some(CUSTOM), None] {
let original = ChosenColor::Named("blue".into());
let mut rig = Rig::new(original.clone(), custom);
rig.open();
rig.fixture.key(Key::End, Modifiers::NONE).idle(2);
assert!(rig.reports.borrow().requests.is_empty(), "a provisional custom row cannot open a picker");
rig.fixture.key(Key::Escape, Modifiers::NONE).settle();
assert_eq!(*rig.value.borrow(), original);
assert!(rig.reports.borrow().requests.is_empty());
assert!(rig.reports.borrow().chosen.is_empty());
rig.open();
rig.fixture.key(Key::End, Modifiers::NONE).key(Key::Enter, Modifiers::NONE).settle().idle(2);
assert_eq!(*rig.value.borrow(), original, "the host changes its color only after the requested picker answers");
let reports = rig.reports.borrow();
assert!(reports.chosen.is_empty());
assert_eq!(reports.requests.len(), 1);
assert_eq!(reports.requests[0].key, ColorChoice::CUSTOM_KEY);
assert_eq!(reports.requests[0].color, Some(custom.unwrap_or(BLUE)));
}
}
+1
View File
@@ -1,6 +1,7 @@
//! The screen tests of craft-color-ui, folded into the lib's test target.
pub(crate) mod area_gamut;
pub(crate) mod choice;
pub(crate) mod color_parts;
pub(crate) mod gradient_bar;
pub(crate) mod paint_chip;
+31
View File
@@ -8,7 +8,9 @@ use std::rc::Rc;
use craft_behavior::Mixed;
use craft_color_ui::ui::{PairWell, SwatchPair, SwatchPairOutput, Well};
use craft_theme::{Srgba, ThemeId};
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _};
use craft_ui::testing::pointer::moved;
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Rect, Ui, Vec2, vec2};
@@ -118,6 +120,35 @@ fn the_well_corner_follows_the_theme_well_shape() {
assert_eq!(clicks("craft.pro"), [Some(Well::Primary), Some(Well::Primary)], "square wells");
}
/// A rest of the pointer on a well shows the well's label, and one on the Swap or Default button shows that button's
/// label: a host that names a well "Fill (X)" shows its key there.
#[trial]
fn a_rest_on_a_well_or_a_button_shows_its_label() {
let mut fixture = Fixture::new(|ui| {
let wells = [PairWell::new("Fill (X)", Srgba::rgb(0.1, 0.3, 0.8)), PairWell::new("Stroke (X)", Srgba::rgb(1.0, 1.0, 1.0))];
SwatchPair::<()>::new("Fill and Stroke", wells, Bind::given(Well::Primary))
.swap_button("Swap (Shift+X)")
.default_button("Default (D)")
.popover(false)
.show(ui);
});
fixture.room(vec2(200.0, 200.0)).settle();
let wells = fixture.by_role(Role::RADIO_BUTTON);
let swap = fixture.by_label("Swap (Shift+X)").expect("the Swap button").rect.center();
let default = fixture.by_label("Default (D)").expect("the Default button").rect.center();
let spots =
[(in_primary(wells[0].rect), "Fill (X)"), (in_secondary(wells[1].rect), "Stroke (X)"), (swap, "Swap (Shift+X)"), (default, "Default (D)")];
for (at, tip) in spots {
fixture.frame(vec![moved(egui::pos2(199.0, 199.0))]);
fixture.settle();
assert!(!fixture.texts().iter().any(|run| run.text == tip), "no {tip:?} before the rest");
fixture.frame(vec![moved(at)]);
fixture.advance(DELAY);
fixture.settle();
assert!(fixture.texts().iter().any(|run| run.text == tip), "a rest there shows {tip:?}");
}
}
/// A popover that opens with the pair as its first stop puts the focus on the active well, as Tab into the pair does:
/// the arrival makes no other well active (a Color panel opened over the Stroke chip leaves Stroke active).
#[trial]
+190 -1
View File
@@ -13,6 +13,7 @@ use craft_color_ui::ui::{
};
use craft_host::target::Os;
use craft_theme::{ColorModel as _, HsbModel, Srgba};
use craft_ui::buttons::Button;
use craft_ui::choice::SwatchTable;
use craft_ui::contract::Role;
use craft_ui::contract::tooltip::DELAY;
@@ -217,6 +218,24 @@ fn a_fill_stroke_panels_warnings_keep_their_room_so_the_spectrum_holds_still() {
assert_eq!(clean, warned, "the spectrum with no warning and with both");
}
/// A host's names for the FillStroke layout's swap and default buttons replace the panel's words, so a host can name
/// its keys there; without them the buttons keep the words.
#[trial]
fn a_fill_stroke_panel_names_its_buttons_as_the_host_asks() {
let names = |given: bool| {
let mut fixture = Fixture::new(move |ui| {
let mut state = ColorPanelState::default();
let panel = ColorPanel::new(Bind::bound(&mut state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke);
let panel = if given { panel.buttons("Swap (Shift+X)", "Default (D)") } else { panel };
let _ = panel.show(ui);
});
fixture.room(COLOR_ROOM).settle();
["Swap (Shift+X)", "Default (D)", "Swap fill and stroke", "Default fill and stroke"].map(|name| fixture.by_label(name).is_some())
};
assert_eq!(names(true), [true, true, false, false], "the host's names");
assert_eq!(names(false), [false, false, true, true], "the panel's words");
}
/// The spectrum's tooltip is the shown mode's name, and a Shift click on it moves the state to the next mode without
/// editing a paint.
#[trial]
@@ -360,6 +379,7 @@ struct PaletteReports {
edits: Vec<EditEvent<Srgba>>,
requests: Vec<ColorRequest>,
picked: Vec<Srgba>,
swatches: Vec<usize>,
}
type Reports = Rc<RefCell<PaletteReports>>;
@@ -370,6 +390,7 @@ fn collect(reports: &Reports, shown: craft_color_ui::ui::SwatchPaletteOutput) {
reports.edits.extend(shown.edit);
reports.requests.extend(shown.pick_color);
reports.picked.extend(shown.picked);
reports.swatches.extend(shown.picked_swatch);
}
fn palette_swatches() -> Vec<(Label, Srgba)> {
@@ -417,7 +438,7 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
let recent = fixture.by_label(&RECENT[0].to_hex()).expect("a recent colour is named by its hex");
fixture.click(&recent).settle();
let taken = std::mem::take(&mut *reports.borrow_mut());
assert!(taken.requests.is_empty(), "a recent pick files no request");
assert!(taken.requests.is_empty() && taken.swatches.is_empty(), "a recent pick is not a palette entry");
assert_eq!(taken.edits.len(), 1, "one edit for one recent pick");
assert!(
matches!(&taken.edits[0], EditEvent::Set { before: Mixed::Same(before), after, .. }
@@ -440,6 +461,47 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::<Vec<_>>(), [swatch("Violet").to_rgba()], "and still reports the pick");
}
#[trial]
fn a_palette_reports_the_actual_swatch_when_its_color_matches_the_bound_color() {
let color = swatch("Green");
let swatches = [(Label::from("First green"), color), (Label::from("Second green"), color), (Label::from("Third green"), color)];
let selected = Rc::new(Cell::new(2));
let preferred = Rc::clone(&selected);
let reports = Reports::default();
let out = reports.clone();
let mut fixture = Fixture::new(move |ui| {
collect(&out, SwatchPalette::new("Swatches", Bind::given(color), &swatches).selected_swatch(Some(preferred.get())).show(ui));
let _ = Button::new("Next control").show(ui);
});
fixture.room(PALETTE_WIDE).settle();
let third = fixture.by_label("Third green").expect("the linked entry");
assert_eq!(fixture.tree().selected_of(third.node), Some(true), "the linked entry stays selected");
let second = fixture.by_label("Second green").expect("the second entry");
fixture.hold(Modifiers::SHIFT).click(&second).hold(Modifiers::NONE).settle();
let click = std::mem::take(&mut *reports.borrow_mut());
assert_eq!(click.swatches, [1]);
assert_eq!(click.picked.iter().map(|picked| picked.to_rgba()).collect::<Vec<_>>(), [color.to_rgba()]);
assert!(click.edits.is_empty(), "the color binding has not changed");
fixture.key(Key::ArrowRight, Modifiers::NONE).key(Key::Space, Modifiers::NONE).settle();
let keys = std::mem::take(&mut *reports.borrow_mut());
assert_eq!(keys.swatches, [2], "Space picks the already selected swatch");
assert!(keys.edits.is_empty());
let focused = |fixture: &Fixture| {
let tree = fixture.tree();
tree.name_of(craft_ui::testing::access::focused_key(tree)).map(str::to_owned)
};
fixture.key(Key::Tab, Modifiers::NONE).settle();
assert_eq!(focused(&fixture).as_deref(), Some("Next control"));
selected.set(0);
fixture.settle();
fixture.key(Key::Tab, Modifiers::SHIFT).settle();
assert_eq!(focused(&fixture).as_deref(), Some("First green"));
fixture.key(Key::Space, Modifiers::NONE).settle();
assert_eq!(reports.borrow().swatches, [0], "Tab returns to the host's current swatch");
}
/// The FillStroke layout shows its Recent Colors caption while the host's list is empty, as it does with colors in
/// it; a host that gives no recent colors gets no row.
#[trial]
@@ -595,6 +657,54 @@ fn swatches_panel_reports_each_edit_and_leaves_the_library() {
assert_eq!(state.rename, Some(SwatchKey::Swatch("Color Swatch 2".to_owned())), "the new swatch opens for renaming");
}
#[trial]
fn a_mixed_swatches_selection_rejects_reorder_and_deletes_each_entry_once() {
use craft_ui::contract::SelectMode;
let entry = |name: &str, color| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb(color));
let groups = vec![
SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red", [1.0, 0.0, 0.0])] },
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Blue", [0.0, 0.0, 1.0])] },
];
let state = Rc::new(RefCell::new(SwatchesState::default()));
let edits = Rc::new(RefCell::new(Vec::new()));
let reorders = Rc::new(Cell::new(0));
let (seen, moves, held) = (edits.clone(), reorders.clone(), state.clone());
let mut fixture = Fixture::new(move |ui| {
let out = SwatchesPanel::new(&groups, Bind::bound(&mut *held.borrow_mut()), RED).select(SelectMode::Multi).select_groups(true).show(ui);
seen.borrow_mut().extend(out.edits);
for event in out.events {
if matches!(event, craft_ui::patterns::presets::PresetEvent::Reorder(_)) {
moves.set(moves.get() + 1);
}
}
});
fixture.room(Vec2::new(320.0, 400.0)).settle();
let group = |name: &str| {
let tree = fixture.tree();
tree.with_role(Role::LIST_BOX_OPTION)
.into_iter()
.find(|&key| tree.name_of(key).is_some_and(|label| label == name || label.starts_with(&format!("{name},"))))
.and_then(|key| fixture.target(key))
.unwrap_or_else(|| panic!("the {name} group"))
};
let basics = group("Basics");
let red = fixture.by_label("Red, #ff0000").expect("the Red swatch");
let blue = fixture.by_label("Blue, #0000ff").expect("the Blue swatch");
let other = group("Other");
fixture.click(&basics).hold(Modifiers::COMMAND).click(&red).click(&blue).hold(Modifiers::NONE).settle();
let keys = [SwatchKey::Group("Basics".to_owned()), SwatchKey::Swatch("Red".to_owned()), SwatchKey::Swatch("Blue".to_owned())];
assert_eq!(state.borrow().selection.items, keys, "the group and swatch keys are selected together");
fixture.drag(&red, other.center() - red.center()).settle();
assert!(edits.borrow().is_empty());
assert_eq!(reorders.get(), 0, "the swatch source refuses a mixed reorder");
fixture.key(Key::Delete, Modifiers::NONE).settle();
let reported = edits.borrow();
assert_eq!(reported.len(), 2, "the group delete already includes Red: {reported:?}");
assert!(reported.contains(&SwatchEdit::DeleteGroup { group: "Basics".to_owned() }));
assert!(reported.contains(&SwatchEdit::delete("Blue".to_owned())));
}
/// A group with an empty name holds the swatches outside every group: they show at the top with no header, so no
/// heading or disclosure button of the panel is left without a name, and a named group keeps its header.
#[trial]
@@ -734,6 +844,85 @@ fn a_rename_left_open_stays_with_its_document() {
assert!(!edits.borrow().iter().any(|edit| matches!(edit, SwatchEdit::Rename { .. })), "nothing is renamed: {:?}", edits.borrow());
}
#[trial]
fn opt_in_reports_only_rejected_swatch_and_group_renames() {
use craft_ui::patterns::presets::{PresetEvent, PresetView};
let entry = |name: &str| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb([1.0, 0.0, 0.0]));
let groups = vec![
SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red"), entry("Rose")] },
SwatchGroup { name: "Other".to_owned(), entries: Vec::new() },
];
let red = SwatchKey::Swatch("Red".to_owned());
let basics = SwatchKey::Group("Basics".to_owned());
for (opt_in, key, name, accepted) in [
(false, &red, "Rose", false),
(false, &basics, "Other", false),
(true, &red, "Rose", false),
(true, &basics, "Other", false),
(true, &red, " Red ", false),
(true, &red, "Coral", true),
(true, &basics, "Favorites", true),
] {
let mut start = SwatchesState::default();
start.browser.view = PresetView::List;
let state = Rc::new(RefCell::new(start));
let edits = Rc::new(RefCell::new(Vec::new()));
let renames = Rc::new(RefCell::new(Vec::new()));
let (held, seen_edits, seen_renames) = (Rc::clone(&state), Rc::clone(&edits), Rc::clone(&renames));
let groups = groups.clone();
let mut fixture = Fixture::new(move |ui| {
let mut current = held.borrow_mut();
let mut panel = SwatchesPanel::new(&groups, Bind::bound(&mut *current), RED);
if opt_in {
panel = panel.report_invalid_renames(true);
}
let out = panel.show(ui);
seen_edits.borrow_mut().extend(out.edits);
seen_renames.borrow_mut().extend(out.events.into_iter().filter_map(|event| match event {
PresetEvent::Rename { key, text, .. } => Some((key, text)),
_ => None,
}));
});
fixture.room(Vec2::new(320.0, 400.0)).settle();
let label = if key == &red { "Red" } else { "Basics" };
let tree = fixture.tree();
let row = tree
.with_role(Role::TREE_ITEM)
.into_iter()
.find(|&node| tree.name_of(node).is_some_and(|actual| actual == label || actual.starts_with(&format!("{label},"))))
.and_then(|node| fixture.target(node))
.unwrap_or_else(|| {
panic!("the {label} row is shown, names: {:?}", tree.keys().into_iter().filter_map(|key| tree.name_of(key)).collect::<Vec<_>>())
});
fixture.click(&row).key(Key::F2, Modifiers::NONE).type_text(name).settle();
let tree = fixture.tree();
assert!(tree.keys().into_iter().any(|key| tree.value_of(key) == Some(name)), "the rename field shows {name}");
let selection = state.borrow().selection.clone();
fixture.key(Key::Enter, Modifiers::NONE).settle();
let rejected = opt_in && matches!(name, "Rose" | "Other");
if rejected {
assert_eq!(*renames.borrow(), [(key.clone(), name.to_owned())]);
} else {
assert!(renames.borrow().is_empty(), "{name}");
}
if accepted {
let reported = edits.borrow();
assert!(
match &reported[..] {
[SwatchEdit::Rename { swatch, name: new }] => key == &SwatchKey::Swatch(swatch.clone()) && new == name,
[SwatchEdit::RenameGroup { group, name: new }] => key == &SwatchKey::Group(group.clone()) && new == name,
_ => false,
},
"{name}: {reported:?}",
);
} else {
assert!(edits.borrow().is_empty(), "{name}");
assert_eq!(state.borrow().selection, selection, "{name}");
}
}
}
fn table_entries(count: usize) -> Vec<(Label, Srgba)> {
(0..count).map(|i| (Label::from(format!("Index {i}")), Srgba::rgb(i as f32 / count as f32, 0.5, 0.25))).collect()
}
+1 -1
View File
@@ -3,7 +3,7 @@
/// The egui fork the library is built and tested with. Apps patch egui to exactly this.
pub const GIT: &str = "https://github.com/storytold/egui.git";
/// The commit of [`GIT`].
pub const REV: &str = "b9770908e0f304896f9658d239a7b29cf8af1564";
pub const REV: &str = "932a73b28560acb1a695533307b2cd0d66a42081";
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
pub const PACKAGES: &[&str] = &[
+2 -2
View File
@@ -283,7 +283,7 @@ fn read_limited(bytes: &[u8], password: Option<&str>, max_paragraphs: usize) ->
let mut doc = Document::new();
// Word opens Word 97-2003 files in compatibility mode 11 (Word 2003); the model's default
// 15 would apply Word 2013+ justification and line-breaking rules to them.
doc.settings.compat_mode = 11;
doc.settings.compat_mode = Some(11);
if let Some(core) = metadata::read(&comp) {
doc.core = core;
}
@@ -455,7 +455,7 @@ fn read_word6(comp: &craft_cfb::CompoundFile<'_>, word: &[u8], max_paragraphs: u
let content = word6::content(word, &fib)?;
let mut doc = Document::new();
// Word opens these files in compatibility mode 11 too.
doc.settings.compat_mode = 11;
doc.settings.compat_mode = Some(11);
if let Some(core) = metadata::read(comp) {
doc.core = core;
}
+1 -1
View File
@@ -347,7 +347,7 @@ fn a_doc_opens_in_word_97_2003_compatibility_mode() {
let doc = read(&f).expect("opens");
// Word 97-2003 files are mode 11 in Word 2013+; mode 15 would change justification and
// line breaking.
assert_eq!(doc.settings.compat_mode, 11);
assert_eq!(doc.settings.compat_mode, Some(11));
}
#[test]
+2 -1
View File
@@ -254,7 +254,8 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize,
lenient("numbering", r.read_numbering(&p));
}
// Without a stated mode (or settings at all) Word lays a document out as Word 2007 did.
r.doc.settings.compat_mode = craft_wordmodel::LEGACY_COMPAT_MODE;
// Retain `compat_mode` as `None` when omitted from the source file to preserve XML fidelity on save (#3308).
r.doc.settings.compat_mode = None;
if let Some(p) = part(rt::SETTINGS) {
lenient("settings", r.read_settings(&p));
}
+1 -1
View File
@@ -47,7 +47,7 @@ impl Reader<'_> {
})
.and_then(|c| c.attr("w:val"));
if let Some(m) = mode.and_then(u32_of) {
s.compat_mode = m.clamp(11, 99);
s.compat_mode = Some(m.clamp(11, 99));
}
s.sum_paragraph_spacing = k.children("w:doNotUseHTMLParagraphAutoSpacing").any(on_off);
s.do_not_expand_shift_return = k.children("w:doNotExpandShiftReturn").any(on_off);
+2 -1
View File
@@ -49,6 +49,7 @@ const MAX_FORM: usize = 64 * 1024;
pub struct RunCtx {
link: Option<String>,
link_tooltip: Option<std::sync::Arc<str>>,
link_history: Option<craft_wordmodel::props::LinkHistory>,
ins: Option<u32>,
del: Option<u32>,
}
@@ -212,5 +213,5 @@ fn placeholder_of(s: &str) -> String {
}
fn on_off_attr(e: &El, name: &str) -> bool {
e.attr(name).is_some_and(|v| !matches!(v, "0" | "false" | "off"))
e.attr(name).is_some_and(|v| !crate::units::is_off_val(v))
}
+16 -2
View File
@@ -32,6 +32,12 @@ impl Reader<'_> {
if let Some(link) = link {
c.link = Some(link);
c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from);
// History on stays `None`: it is what the writer writes for a link with none.
c.link_history = match k.attr("w:history") {
Some(v) if crate::units::is_off_val(v) => Some(craft_wordmodel::props::LinkHistory::Off),
Some(_) => None,
None => Some(craft_wordmodel::props::LinkHistory::Omitted),
};
}
self.read_inline_children(sc, pb, k, rels, &c, depth + 1);
}
@@ -138,6 +144,7 @@ impl Reader<'_> {
let mut p = self.pc.rpr(rpr);
p.link = ctx.link.clone();
p.link_tooltip = ctx.link_tooltip.clone();
p.link_history = ctx.link_history;
p.ins = ctx.ins;
p.del = ctx.del;
p.fmt_change = self.rpr_change(rpr);
@@ -145,7 +152,14 @@ impl Reader<'_> {
}
fn run_props_none(&self, ctx: &RunCtx) -> CharProps {
CharProps { link: ctx.link.clone(), link_tooltip: ctx.link_tooltip.clone(), ins: ctx.ins, del: ctx.del, ..Default::default() }
CharProps {
link: ctx.link.clone(),
link_tooltip: ctx.link_tooltip.clone(),
link_history: ctx.link_history,
ins: ctx.ins,
del: ctx.del,
..Default::default()
}
}
fn read_run(&mut self, sc: &mut StoryCtx, pb: &mut PB, r: &El, rels: &Rels, ctx: &RunCtx, depth: usize) {
@@ -354,7 +368,7 @@ impl Reader<'_> {
let (base, base_props) = part("w:rubyBase");
let (ruby, ruby_props) = part("w:rt");
let mut bp = base_props.unwrap_or_default();
(bp.link, bp.ins, bp.del) = (props.link.clone(), props.ins, props.del);
(bp.link, bp.link_history, bp.ins, bp.del) = (props.link.clone(), props.link_history, props.ins, props.del);
if base.is_empty() {
return;
}
+6 -1
View File
@@ -141,11 +141,16 @@ pub fn tw_u16(e: &El, attr: &str) -> Option<f32> {
}
}
/// Return whether an XML attribute value for an `ST_OnOff` represents "off" / false.
pub fn is_off_val(v: &str) -> bool {
matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE")
}
/// ST_OnOff: absent `w:val` = on; `0`, `false`, `off` = off.
pub fn on_off(e: &El) -> bool {
match e.attr("w:val") {
None => true,
Some(v) => !matches!(v.trim(), "0" | "false" | "off" | "False" | "FALSE"),
Some(v) => !is_off_val(v),
}
}
+11 -2
View File
@@ -151,6 +151,13 @@ fn write_note_settings(
}
fn write_compatibility_settings(w: &mut W, doc: &Document) {
let has_compat = doc.settings.do_not_expand_shift_return
|| doc.settings.sum_paragraph_spacing
|| doc.settings.allow_space_of_same_style_in_table
|| doc.settings.compat_mode.is_some();
if !has_compat {
return;
}
w.open("w:compat", &[]);
// CT_Compat: the older switches come before the `w:compatSetting`s.
if doc.settings.do_not_expand_shift_return {
@@ -162,8 +169,10 @@ fn write_compatibility_settings(w: &mut W, doc: &Document) {
if doc.settings.allow_space_of_same_style_in_table {
w.empty("w:allowSpaceOfSameStyleInTable", &[]);
}
let mode = doc.settings.compat_mode.clamp(11, 15).to_string();
w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]);
if let Some(mode) = doc.settings.compat_mode {
let mode = mode.clamp(11, 15).to_string();
w.empty("w:compatSetting", &[("w:name", "compatibilityMode"), ("w:uri", "http://schemas.microsoft.com/office/word"), ("w:val", &mode)]);
}
w.close("w:compat");
}
+213 -25
View File
@@ -8,7 +8,8 @@
//! tag (namespace declarations, `mc:Ignorable`) and every child the model doesn't own are kept
//! byte for byte; owned children come from the generated part (or go, when the model turned
//! them off); owned children the original lacks are inserted at their CT_Settings position; in
//! `w:compat` only the `compatibilityMode` setting is replaced. Kept children that refer to a
//! `w:compat` only the switches the model writes and the `compatibilityMode` setting come from the
//! generated part, and a block left empty goes. Kept children that refer to a
//! relationship are dropped unless owned: mail merge is regenerated with remapped external
//! sources by `mail_merge`. Anything unexpected returns `None`, and the generated part is written as before.
@@ -232,29 +233,125 @@ fn children(xml: &str, root: &str) -> Option<(usize, usize, Vec<Child>)> {
Some((open_end, close, out))
}
/// The original `w:compat` with its `compatibilityMode` taken from the generated one.
/// The `w:compat` switches the model writes (`super::settings`).
const OWNED_COMPAT_SWITCHES: &[&str] = &["w:doNotExpandShiftReturn", "w:doNotUseHTMLParagraphAutoSpacing", "w:allowSpaceOfSameStyleInTable"];
/// CT_Compat's sequence (ECMA-376 §17.15.3.9), for placing inserted switches.
const CT_COMPAT_ORDER: &[&str] = &[
"useSingleBorderforContiguousCells",
"wpJustification",
"noTabHangInd",
"noLeading",
"spaceForUL",
"noColumnBalance",
"balanceSingleByteDoubleByteWidth",
"noExtraLineSpacing",
"doNotLeaveBackslashAlone",
"ulTrailSpace",
"doNotExpandShiftReturn",
"spacingInWholePoints",
"lineWrapLikeWord6",
"printBodyTextBeforeHeader",
"printColBlack",
"wpSpaceWidth",
"showBreaksInFrames",
"subFontBySize",
"suppressBottomSpacing",
"suppressTopSpacing",
"suppressSpacingAtTopOfPage",
"suppressTopSpacingWP",
"suppressSpBfAfterPgBrk",
"swapBordersFacingPages",
"convMailMergeEsc",
"truncateFontHeightsLikeWP6",
"mwSmallCaps",
"usePrinterMetrics",
"doNotSuppressParagraphBorders",
"wrapTrailSpaces",
"footnoteLayoutLikeWW8",
"shapeLayoutLikeWW8",
"alignTablesRowByRow",
"forgetLastTabAlignment",
"adjustLineHeightInTable",
"autoSpaceLikeWord95",
"noSpaceRaiseLower",
"doNotUseHTMLParagraphAutoSpacing",
"layoutRawTableWidth",
"layoutTableRowsApart",
"useWord97LineBreakRules",
"doNotBreakWrappedTables",
"doNotSnapToGridInCell",
"selectFldWithFirstOrLastChar",
"applyBreakingRules",
"doNotWrapTextWithPunct",
"doNotUseEastAsianBreakRules",
"useWord2002TableStyleRules",
"growAutofit",
"useFELayout",
"useNormalStyleForList",
"doNotUseIndentAsNumberingTabStop",
"useAltKinsokuLineBreakRules",
"allowSpaceOfSameStyleInTable",
"doNotSuppressIndentation",
"doNotAutofitConstrainedTables",
"autofitToFirstFixedWidthCell",
"underlineTabInNumList",
"displayHangulFixedWidth",
"splitPgBreakAndParaMark",
"doNotVertAlignCellWithSp",
"doNotBreakConstrainedForcedTable",
"doNotVertAlignInTxbx",
"useAnsiKerningPairs",
"cachedColBalance",
"compatSetting",
];
/// Position of a `w:`-prefixed `w:compat` child in [`CT_COMPAT_ORDER`]; `None` for anything else.
fn compat_rank(name: &str) -> Option<usize> {
let local = name.strip_prefix("w:")?;
CT_COMPAT_ORDER.iter().position(|n| *n == local)
}
/// Is this `w:compat` child Word's `compatibilityMode` setting?
fn is_compat_mode(child: &str) -> bool {
let mut reader = quick_xml::Reader::from_str(child);
let Ok(quick_xml::events::Event::Start(e) | quick_xml::events::Event::Empty(e)) = reader.read_event() else { return false };
e.name().as_ref() == b"w:compatSetting"
&& e.attributes().with_checks(false).flatten().any(|a| a.key.as_ref() == b"w:name" && a.value.as_ref() == b"compatibilityMode")
}
/// The original `w:compat` with what the model owns in it taken from the generated one (`""`
/// when the model writes none): its switches, and the `compatibilityMode` setting. A block left
/// without children goes (`""`).
fn merge_compat(orig: &str, generated: &str) -> Option<String> {
let mode = |s: &str| -> Option<(usize, usize)> {
let at = s.find("w:name=\"compatibilityMode\"")?;
let tag_start = s.get(..at)?.rfind('<')?;
let tag_end = tag_start + s.get(tag_start..)?.find('>')? + 1;
Some((tag_start, tag_end))
let g_kids = children(generated, "w:compat").map(|(_, _, kids)| kids).unwrap_or_default();
let g_child = |pred: &dyn Fn(&Child, &str) -> bool| g_kids.iter().find_map(|k| generated.get(k.start..k.end).filter(|text| pred(k, text)));
let mut out = match orig.strip_suffix("/>") {
Some(open) => format!("{}></w:compat>", open.trim_end()),
None => orig.to_string(),
};
match (mode(orig), mode(generated)) {
(Some((a, b)), Some((c, d))) => Some(format!("{}{}{}", orig.get(..a)?, generated.get(c..d)?, orig.get(b..)?)),
(None, Some((c, d))) => {
// No mode in the original: add the generated one before `</w:compat>`, or expand a self-closing `<w:compat/>`.
if let Some(close) = orig.rfind("</w:compat>") {
Some(format!("{}{}{}", orig.get(..close)?, generated.get(c..d)?, orig.get(close..)?))
} else if let Some(slash) = orig.rfind("/>") {
let open = orig.get(..slash)?.trim_end();
Some(format!("{open}>{}</w:compat>", generated.get(c..d)?))
} else {
None
}
for sw in OWNED_COMPAT_SWITCHES {
let (_, _, kids) = children(&out, "w:compat")?;
for k in kids.iter().rev().filter(|k| k.name == *sw) {
out.replace_range(k.start..k.end, "");
}
if let Some(g) = g_child(&|k, _| k.name == *sw) {
let (_, close, kids) = children(&out, "w:compat")?;
let rank = compat_rank(sw);
let at = kids.iter().find(|k| compat_rank(&k.name) > rank).map_or(close, |k| k.start);
out.insert_str(at, g);
}
_ => Some(orig.to_string()),
}
let (_, close, kids) = children(&out, "w:compat")?;
let o_mode = kids.iter().find(|k| out.get(k.start..k.end).is_some_and(is_compat_mode)).map(|k| k.start..k.end);
match (o_mode, g_child(&|_, text| is_compat_mode(text))) {
(Some(span), Some(g)) => out.replace_range(span, g),
(Some(span), None) => out.replace_range(span, ""),
(None, Some(g)) => out.insert_str(close, g),
(None, None) => {}
}
let (_, _, kids) = children(&out, "w:compat")?;
Some(if kids.is_empty() { String::new() } else { out })
}
/// Does `original` (a settings part) hold anything the model doesn't write? Then the reader keeps
@@ -358,11 +455,11 @@ pub fn merge(original: &[u8], generated: &[u8]) -> Option<Vec<u8>> {
out.push((k.name.clone(), g_text(g_kids.get(gi)?)?));
}
} else if k.name == "w:compat" {
let merged = match mark("w:compat", &mut used) {
Some(gi) => merge_compat(text, &g_text(g_kids.get(gi)?)?)?,
None => text.to_string(),
};
out.push((k.name.clone(), merged));
let g_compat = mark("w:compat", &mut used).and_then(|gi| g_text(g_kids.get(gi)?));
let merged = merge_compat(text, g_compat.as_deref().unwrap_or(""))?;
if !merged.is_empty() {
out.push((k.name.clone(), merged));
}
} else if !text.contains("r:id=") {
out.push((k.name.clone(), text.to_string()));
}
@@ -475,4 +572,95 @@ mod tests {
// A file whose only extra setting is this one has nothing foreign to keep.
assert!(!has_unowned(br#"<w:settings xmlns:w="w"><w:zoom w:percent="100"/><w:gutterAtTop/></w:settings>"#));
}
#[test]
fn compatibility_mode_removal_handles_paired_tags_quotes_and_whitespace() {
let gen_no_mode = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:zoom w:percent="100"/></w:settings>"#;
// Paired tag with closing </w:compatSetting>
let orig_paired = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"></w:compatSetting><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat></w:settings>"#;
assert!(has_unowned(orig_paired.as_bytes()));
let out_paired = String::from_utf8(merge(orig_paired.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap();
assert!(!out_paired.contains("compatibilityMode"), "{out_paired}");
assert!(!out_paired.contains("</w:compatSetting>"), "{out_paired}");
assert!(out_paired.contains("overrideTableStyleFontSizeAndJustification"), "{out_paired}");
// Single quotes
let orig_single_quotes = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:compat><w:compatSetting w:name='compatibilityMode' w:uri='http://schemas.microsoft.com/office/word' w:val='15'/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:val="1"/></w:compat></w:settings>"#;
let out_sq = String::from_utf8(merge(orig_single_quotes.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap();
assert!(!out_sq.contains("compatibilityMode"), "{out_sq}");
assert!(out_sq.contains("overrideTableStyleFontSizeAndJustification"), "{out_sq}");
// Whitespace around equals
let orig_spaces = r#"<w:settings xmlns:w="w" xmlns:m="m" xmlns:r="r"><w:compat><w:compatSetting w:name = "compatibilityMode" w:uri = "http://schemas.microsoft.com/office/word" w:val = "15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:val="1"/></w:compat></w:settings>"#;
let out_sp = String::from_utf8(merge(orig_spaces.as_bytes(), gen_no_mode.as_bytes()).unwrap()).unwrap();
assert!(!out_sp.contains("compatibilityMode"), "{out_sp}");
assert!(out_sp.contains("overrideTableStyleFontSizeAndJustification"), "{out_sp}");
// Foreign vendor compatSetting element is preserved
let orig_foreign = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="m" xmlns:r="r" xmlns:x="urn:vendor"><w:compat><x:compatSetting x:name="compatibilityMode" x:uri="urn:vendor" x:val="1"/><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/></w:compat></w:settings>"#;
let gen_foreign =
r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:zoom w:percent="100"/></w:settings>"#;
let out_foreign = String::from_utf8(merge(orig_foreign.as_bytes(), gen_foreign.as_bytes()).unwrap()).unwrap();
assert!(out_foreign.contains("x:compatSetting"), "{out_foreign}");
assert!(!out_foreign.contains(r#"w:name="compatibilityMode""#), "{out_foreign}");
}
#[test]
fn repeated_compat_switches_are_all_removed_when_disabled_and_deduplicated_when_enabled() {
let orig_two = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:compat><w:doNotExpandShiftReturn/><w:useFELayout/><w:doNotExpandShiftReturn/></w:compat></w:settings>"#;
// Disabled in generated: both must be removed
let gen_disabled =
r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:zoom w:percent="100"/></w:settings>"#;
let out_disabled = String::from_utf8(merge(orig_two.as_bytes(), gen_disabled.as_bytes()).unwrap()).unwrap();
assert!(!out_disabled.contains("doNotExpandShiftReturn"), "{out_disabled}");
assert!(out_disabled.contains("<w:useFELayout/>"), "{out_disabled}");
// Enabled in generated: exactly one occurrence emitted
let gen_enabled = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:compat><w:doNotExpandShiftReturn/></w:compat></w:settings>"#;
let out_enabled = String::from_utf8(merge(orig_two.as_bytes(), gen_enabled.as_bytes()).unwrap()).unwrap();
assert_eq!(out_enabled.matches("doNotExpandShiftReturn").count(), 1, "{out_enabled}");
assert!(out_enabled.contains("<w:useFELayout/>"), "{out_enabled}");
}
#[test]
fn new_compat_switches_are_inserted_in_schema_order() {
// spacingInWholePoints is ranked after doNotExpandShiftReturn in CT_Compat
let orig = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:compat><w:spacingInWholePoints/></w:compat></w:settings>"#;
let gen_xml = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:compat><w:doNotExpandShiftReturn/></w:compat></w:settings>"#;
let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap();
let idx_shift = merged.find("<w:doNotExpandShiftReturn/>").unwrap();
let idx_spacing = merged.find("<w:spacingInWholePoints/>").unwrap();
assert!(idx_shift < idx_spacing, "doNotExpandShiftReturn must precede spacingInWholePoints: {merged}");
}
#[test]
fn foreign_child_is_ignored_when_finding_switch_insertion_point() {
// x:spacingInWholePoints precedes w:ulTrailSpace
let orig = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:x="urn:vendor"><w:compat><x:spacingInWholePoints/><w:ulTrailSpace/><w:spacingInWholePoints/></w:compat></w:settings>"#;
let gen_xml = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:compat><w:doNotExpandShiftReturn/></w:compat></w:settings>"#;
let merged = String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap();
let idx_custom = merged.find("<x:spacingInWholePoints/>").unwrap();
let idx_trail = merged.find("<w:ulTrailSpace/>").unwrap();
let idx_shift = merged.find("<w:doNotExpandShiftReturn/>").unwrap();
let idx_spacing = merged.find("<w:spacingInWholePoints/>").unwrap();
assert!(idx_custom < idx_trail, "custom before trail: {merged}");
assert!(idx_trail < idx_shift, "trail before shift: {merged}");
assert!(idx_shift < idx_spacing, "shift before spacing: {merged}");
}
#[test]
fn a_bare_self_closing_compat_block_goes_like_an_empty_paired_one() {
let gen_xml = r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:zoom w:percent="100"/></w:settings>"#;
let merged_with = |compat: &str| {
let orig = format!(
r#"<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{compat}<w:rsids><w:rsidRoot w:val="00112233"/></w:rsids></w:settings>"#
);
String::from_utf8(merge(orig.as_bytes(), gen_xml.as_bytes()).unwrap()).unwrap()
};
let self_closing = merged_with("<w:compat/>");
assert!(!self_closing.contains("compat"), "{self_closing}");
assert!(self_closing.contains(r#"<w:rsidRoot w:val="00112233"/>"#), "{self_closing}");
assert_eq!(self_closing, merged_with("<w:compat></w:compat>"));
}
}
+42 -11
View File
@@ -210,17 +210,24 @@ impl Writer<'_> {
i += 1;
continue;
}
// Hyperlinks with different ScreenTips stay separate even if their target is shared.
let link = props
.link
.as_deref()
.filter(|target| !target.is_empty())
.map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip)));
// Hyperlinks with different ScreenTips or history settings stay separate even if their target is shared.
let base = link_target_and_tip;
// Text with no history of its own (typed into a link) takes the history of the link it
// is in: the open one, or else the first of the following text in the same link that has one.
let link = base(props).map(|(target, tip)| {
let history = match open_link {
Some((open_target, open_tip, open_history)) if (open_target, open_tip) == (target, tip) => props.link_history.or(open_history),
_ => props.link_history.or_else(|| {
pieces.iter().skip(i + 1).map(|(_, p)| *p).take_while(|p| base(p) == Some((target, tip))).find_map(|p| p.link_history)
}),
};
(target, tip, history)
});
if link != open_link {
if open_link.is_some() {
w.close("w:hyperlink");
}
if let Some((link, tip)) = link {
if let Some((link, tip, hist)) = link {
let id;
let target = if let Some(anchor) = link.strip_prefix('#') {
("w:anchor", anchor)
@@ -228,11 +235,19 @@ impl Writer<'_> {
id = rels.add(rt::HYPERLINK, link, true);
("r:id", id.as_str())
};
if let Some(tip) = tip {
w.open("w:hyperlink", &[target, ("w:history", "1"), ("w:tooltip", tip)]);
} else {
w.open("w:hyperlink", &[target, ("w:history", "1")]);
let mut attrs = [("", ""); 3];
let mut n = 0;
attrs[n] = target;
n += 1;
if let Some(h) = link_history_val(hist) {
attrs[n] = ("w:history", h);
n += 1;
}
if let Some(tip) = tip {
attrs[n] = ("w:tooltip", tip);
n += 1;
}
w.open("w:hyperlink", &attrs[..n]);
}
open_link = link;
}
@@ -355,3 +370,19 @@ impl Writer<'_> {
}
}
}
/// A run's hyperlink target and the ScreenTip it is written with, or `None` outside a link.
fn link_target_and_tip(p: &CharProps) -> Option<(&str, Option<&str>)> {
p.link.as_deref().filter(|target| !target.is_empty()).map(|target| (target, p.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip)))
}
/// The `w:history` value a hyperlink is written with: off or none when a .docx file gave that,
/// otherwise on, as Word writes it for a new link.
fn link_history_val(history: Option<craft_wordmodel::props::LinkHistory>) -> Option<&'static str> {
use craft_wordmodel::props::LinkHistory;
match history {
None => Some("1"),
Some(LinkHistory::Off) => Some("0"),
Some(LinkHistory::Omitted) => None,
}
}
+11 -9
View File
@@ -1280,17 +1280,17 @@ fn compatibility_mode_is_read_and_defaults_to_word_2007() {
let compat = |v: &str| {
format!(r#"<w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="{v}"/></w:compat>"#)
};
assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, 15);
assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, 14);
assert_eq!(with_settings(Some(&compat("15"))).settings.compat_mode, Some(15));
assert_eq!(with_settings(Some(&compat("14"))).settings.compat_mode, Some(14));
// Unnamed, out of range or junk values.
assert_eq!(with_settings(Some("<w:compat/>")).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE);
assert_eq!(with_settings(None).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE);
assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, 11);
assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, 99);
assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE);
assert_eq!(with_settings(Some("<w:compat/>")).settings.compat_mode, None);
assert_eq!(with_settings(None).settings.compat_mode, None);
assert_eq!(with_settings(Some(&compat("-3"))).settings.compat_mode, Some(11));
assert_eq!(with_settings(Some(&compat("99999"))).settings.compat_mode, Some(99));
assert_eq!(with_settings(Some(&compat("abc"))).settings.compat_mode, None);
// Another vendor's setting of the same name is ignored.
let other = r#"<w:compat><w:compatSetting w:name="compatibilityMode" w:uri="urn:example" w:val="15"/></w:compat>"#;
assert_eq!(with_settings(Some(other)).settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE);
assert_eq!(with_settings(Some(other)).settings.compat_mode, None);
}
#[test]
@@ -1458,7 +1458,9 @@ fn anchor_stacking_order_is_read_and_kept() {
#[test]
fn documents_without_a_compatibility_mode_are_laid_out_as_word_2007() {
assert_eq!(read_body("<w:p/>").settings.compat_mode, craft_wordmodel::LEGACY_COMPAT_MODE);
let d = read_body("<w:p/>");
assert_eq!(d.settings.compat_mode, None);
assert_eq!(d.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE);
}
#[test]
+157 -5
View File
@@ -143,6 +143,7 @@ fn every_char_prop_round_trips() {
}),
link: None,
link_tooltip: None,
link_history: None,
ins: None,
del: None,
fmt_change: None,
@@ -1564,11 +1565,11 @@ fn table_contextual_spacing_compatibility_flag_round_trips() {
for mode in [11, 12, 14, 15] {
for allow in [false, true] {
let mut d = Document::new();
d.settings.compat_mode = mode;
d.settings.compat_mode = Some(mode);
d.settings.allow_space_of_same_style_in_table = allow;
let r = rt(&d);
assert_eq!(r.settings.allow_space_of_same_style_in_table, allow);
assert_eq!(r.settings.compat_mode, mode);
assert_eq!(r.settings.compat_mode, Some(mode));
if allow {
let bytes = craft_docx::write(&d).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
@@ -1585,14 +1586,165 @@ fn table_contextual_spacing_compatibility_flag_round_trips() {
fn compatibility_mode_round_trips() {
// New documents are Word 2013+ documents; an older file keeps its mode, so saving it doesn't
// change how Word lays it out.
assert_eq!(rt(&Document::new()).settings.compat_mode, craft_wordmodel::COMPAT_MODE_CURRENT);
assert_eq!(rt(&Document::new()).settings.compat_mode, Some(craft_wordmodel::COMPAT_MODE_CURRENT));
for mode in [11, 12, 14, 15] {
let mut d = Document::new();
d.settings.compat_mode = mode;
assert_eq!(rt(&d).settings.compat_mode, mode);
d.settings.compat_mode = Some(mode);
assert_eq!(rt(&d).settings.compat_mode, Some(mode));
}
}
/// #3308: A document without `<w:compat>` or without `<w:compatSetting w:name="compatibilityMode">`
/// round-trips without synthesizing the tag on save.
#[test]
fn compatibility_mode_omitted_round_trips_without_synthesizing() {
let settings_xml_of = |bytes: &[u8]| {
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
match zip.by_name("word/settings.xml") {
Ok(mut file) => {
std::io::Read::read_to_string(&mut file, &mut xml).unwrap();
Some(xml)
}
Err(zip::result::ZipError::FileNotFound) => None,
Err(e) => panic!("zip error: {e:?}"),
}
};
// Case 1: settings.xml without `<w:compat>` at all.
let base_docx = craft_docx::write(&Document::new()).unwrap();
let original_settings = settings_xml_of(&base_docx).unwrap();
let without_compat = original_settings.replace(
"<w:compat><w:compatSetting w:name=\"compatibilityMode\" w:uri=\"http://schemas.microsoft.com/office/word\" w:val=\"15\"/></w:compat>",
"",
);
assert_ne!(original_settings, without_compat);
let docx_without_compat = replace_part(&base_docx, "word/settings.xml", without_compat.as_bytes());
let doc = craft_docx::read(&docx_without_compat).unwrap();
assert_eq!(doc.settings.compat_mode, None);
assert_eq!(doc.settings.effective_compat_mode(), craft_wordmodel::LEGACY_COMPAT_MODE);
let saved_bytes = craft_docx::write(&doc).unwrap();
let saved_settings = settings_xml_of(&saved_bytes).unwrap();
assert!(!saved_settings.contains("<w:compat"), "expected no <w:compat>, got: {saved_settings}");
assert!(!saved_settings.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings}");
let read_back = craft_docx::read(&saved_bytes).unwrap();
assert_eq!(read_back.settings.compat_mode, None);
// Case 2: settings.xml with `<w:compat>` but without `<w:compatSetting w:name="compatibilityMode">`
// (e.g. only legacy compatibility flags like `<w:doNotExpandShiftReturn/>`).
let with_other_compat = original_settings.replace(
"<w:compatSetting w:name=\"compatibilityMode\" w:uri=\"http://schemas.microsoft.com/office/word\" w:val=\"15\"/>",
"<w:doNotExpandShiftReturn/>",
);
assert_ne!(original_settings, with_other_compat);
let docx_with_other = replace_part(&base_docx, "word/settings.xml", with_other_compat.as_bytes());
let doc2 = craft_docx::read(&docx_with_other).unwrap();
assert_eq!(doc2.settings.compat_mode, None);
assert!(doc2.settings.do_not_expand_shift_return);
let saved_bytes2 = craft_docx::write(&doc2).unwrap();
let saved_settings2 = settings_xml_of(&saved_bytes2).unwrap();
assert!(saved_settings2.contains("<w:compat>"), "expected <w:compat>, got: {saved_settings2}");
assert!(saved_settings2.contains("<w:doNotExpandShiftReturn/>"), "expected doNotExpandShiftReturn, got: {saved_settings2}");
assert!(!saved_settings2.contains("compatibilityMode"), "expected no compatibilityMode, got: {saved_settings2}");
let read_back2 = craft_docx::read(&saved_bytes2).unwrap();
assert_eq!(read_back2.settings.compat_mode, None);
assert!(read_back2.settings.do_not_expand_shift_return);
}
/// #3305: a hyperlink keeps the `w:history` a .docx file gave it (on, off or none), and a link
/// with no value, as one made in the app has, is written with history on and reads back the same.
#[test]
fn hyperlink_history_attribute_preservation_round_trips() {
use craft_wordmodel::props::LinkHistory;
let doc_xml_of = |bytes: &[u8]| {
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
xml
};
// 1. Each model value is written as the matching attribute and read back as it.
for (history, written) in [(None, Some("1")), (Some(LinkHistory::Off), Some("0")), (Some(LinkHistory::Omitted), None)] {
let mut p = Paragraph::new();
p.insert_text(0, "link", &CharProps { link: Some("https://example.com/".into()), link_history: history, ..Default::default() }).unwrap();
let bytes = craft_docx::write(&doc_with(vec![p])).unwrap();
let xml = doc_xml_of(&bytes);
assert!(xml.contains("<w:hyperlink "), "{xml}");
match written {
Some(v) => assert!(xml.contains(&format!(r#"w:history="{v}""#)), "{history:?}: {xml}"),
None => assert!(!xml.contains("w:history"), "{history:?}: {xml}"),
}
let read = craft_docx::read(&bytes).unwrap();
assert_eq!(paras(&read)[0].props_of_char(0).link_history, history);
}
let mut p_one = Paragraph::new();
p_one
.insert_text(
0,
"link with history 1",
&CharProps { link: Some("https://example.com/hist-one".into()), link_history: None, ..Default::default() },
)
.unwrap();
let d_one = doc_with(vec![p_one]);
// 2. Original XML fixture round-trip:
// Verify that reading raw XML with omitted w:history and w:history="0" saves back identically.
let base = craft_docx::write(&d_one).unwrap();
// Replace the hyperlink in document.xml to have NO w:history attribute
let orig_doc_xml = doc_xml_of(&base);
let xml_omitted_hist = orig_doc_xml.replace(r#" w:history="1""#, "");
assert_ne!(orig_doc_xml, xml_omitted_hist);
let file_omitted = replace_part(&base, "word/document.xml", xml_omitted_hist.as_bytes());
let read_omitted = craft_docx::read(&file_omitted).unwrap();
assert_eq!(paras(&read_omitted)[0].props_of_char(0).link_history, Some(LinkHistory::Omitted));
let saved_omitted = craft_docx::write(&read_omitted).unwrap();
let resaved_xml = doc_xml_of(&saved_omitted);
assert!(!resaved_xml.contains("w:history"), "expected no w:history on save, got: {resaved_xml}");
// Replace the hyperlink in document.xml to have w:history="0"
let xml_zero_hist = orig_doc_xml.replace(r#"w:history="1""#, r#"w:history="0""#);
assert_ne!(orig_doc_xml, xml_zero_hist);
let file_zero = replace_part(&base, "word/document.xml", xml_zero_hist.as_bytes());
let read_zero = craft_docx::read(&file_zero).unwrap();
assert_eq!(paras(&read_zero)[0].props_of_char(0).link_history, Some(LinkHistory::Off));
let saved_zero = craft_docx::write(&read_zero).unwrap();
let resaved_zero_xml = doc_xml_of(&saved_zero);
assert!(resaved_zero_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_zero_xml}");
// Replace the hyperlink in document.xml to have w:history=" 0 " (whitespace-padded false)
let xml_padded_zero = orig_doc_xml.replace(r#"w:history="1""#, r#"w:history=" 0 ""#);
assert_ne!(orig_doc_xml, xml_padded_zero);
let file_padded = replace_part(&base, "word/document.xml", xml_padded_zero.as_bytes());
let read_padded = craft_docx::read(&file_padded).unwrap();
assert_eq!(paras(&read_padded)[0].props_of_char(0).link_history, Some(LinkHistory::Off));
let saved_padded = craft_docx::write(&read_padded).unwrap();
let resaved_padded_xml = doc_xml_of(&saved_padded);
assert!(resaved_padded_xml.contains(r#"w:history="0""#), "expected w:history=\"0\" on save, got: {resaved_padded_xml}");
}
/// #3305: a link the app makes, by laying a `CharProps` patch with a target over text, saves with
/// history on, as it did before `w:history` was kept from .docx files.
#[test]
fn a_link_made_with_a_char_props_patch_saves_with_history_on() {
let mut p = Paragraph::with_text("see the site", CharProps::default());
let patch = CharProps { link: Some("https://example.com/".into()), ..Default::default() };
p.format(4, 12, &|c| c.overlay(&patch)).unwrap();
let bytes = craft_docx::write(&doc_with(vec![p])).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
assert!(xml.contains("<w:hyperlink ") && xml.contains(r#"w:history="1""#), "{xml}");
}
/// Tools › Templates and Add-ins: the attached template (an external relationship of the settings
/// part) and "Automatically update document styles" (`w:linkStyles`) round-trip, written in the
/// schema's order (after `w:mirrorMargins`, before `w:trackRevisions`).
+33
View File
@@ -205,6 +205,39 @@ fn do_not_track_moves_round_trips() {
assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves);
}
#[test]
fn cleared_compatibility_mode_removes_it_from_merged_settings() {
let mut doc = craft_docx::read(&with_settings(SETTINGS)).unwrap();
assert_eq!(doc.settings.compat_mode, Some(15));
assert!(doc.passthrough.contains_key("wordcraft:settings.orig"));
// Case 1: compat_mode is set to None, and no other compat switch is enabled.
doc.settings.compat_mode = None;
let files = save(&doc);
let s = text(&files, "word/settings.xml");
assert!(!s.contains("compatibilityMode"), "expected mode removed: {s}");
assert!(s.contains("<w:compat>"), "expected w:compat preserved for unowned settings: {s}");
assert!(s.contains("overrideTableStyleFontSizeAndJustification"), "{s}");
assert!(s.contains("enableOpenTypeFeatures"), "{s}");
let reopened = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap();
assert_eq!(reopened.settings.compat_mode, None);
// Case 2: compat_mode is set to None, but another switch is enabled.
doc.settings.do_not_expand_shift_return = true;
let files2 = save(&doc);
let s2 = text(&files2, "word/settings.xml");
assert!(!s2.contains("compatibilityMode"), "expected mode removed: {s2}");
assert!(s2.contains("<w:compat>"), "{s2}");
assert!(s2.contains("<w:doNotExpandShiftReturn/>"), "expected switch preserved: {s2}");
assert!(s2.contains("overrideTableStyleFontSizeAndJustification"), "{s2}");
assert!(s2.contains("enableOpenTypeFeatures"), "{s2}");
let reopened2 = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap();
assert_eq!(reopened2.settings.compat_mode, None);
assert!(reopened2.settings.do_not_expand_shift_return);
}
/// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`,
/// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged
/// part), written in a generated part, and left out when they are turned off.
+78 -5
View File
@@ -7,7 +7,7 @@ use craft_color_ui::ui::{ChosenColor, ColorChoice, NamedColor};
use craft_theme::Srgba;
use craft_ui::choice::{Checkbox, Radio, RadioGroup};
use craft_ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id};
use craft_ui::display::{Shade, Text};
use craft_ui::form::{Field, FieldGroup};
use craft_ui::layout_components::Row;
@@ -194,6 +194,7 @@ pub struct SliceOptionsDialog {
options: SliceOptions,
kinds: Vec<SliceKind>,
requests: HostRequests,
held: Option<HeldAnswer<SliceOptions>>,
}
impl SliceOptionsDialog {
@@ -204,6 +205,7 @@ impl SliceOptionsDialog {
options,
kinds: vec![SliceKind::Image, SliceKind::NoImage],
requests: HostRequests::new(),
held: None,
}
}
@@ -220,6 +222,25 @@ impl SliceOptionsDialog {
}
}
impl HoldsOk for SliceOptionsDialog {
type Answer = SliceOptions;
fn held_ok(mut self) -> Self {
self.held = Some(HeldAnswer::new());
self
}
fn take_ok(&mut self) -> Option<SliceOptions> {
self.held.as_mut()?.take()
}
fn answer_ok(&mut self, answer: Result<(), Label>) {
if let Some(held) = &mut self.held {
held.answer(answer);
}
}
}
impl StackDialog for SliceOptionsDialog {
type Result = SliceOptions;
@@ -333,7 +354,11 @@ impl StackDialog for SliceOptionsDialog {
let background_labels = [&words.background_none, &words.background_matte, &words.background_white, &words.background_black];
let measuring = craft_ui::runtime::measure::active(ui.ctx());
let answers = if measuring { Vec::new() } else { self.requests.take_answers() };
let shown = FormDialog::new(words.options_title.clone(), Bind::bound(&mut self.options)).answers(answers).show(ui, |ui, form, options| {
let mut dialog = FormDialog::new(words.options_title.clone(), Bind::bound(&mut self.options)).answers(answers);
if let Some(held) = &mut self.held {
dialog = dialog.held(held);
}
let shown = dialog.show(ui, |ui, form, options| {
for answer in form.take_answers() {
if let HostAnswer::Color { key, color, .. } = answer
&& key == ColorChoice::CUSTOM_KEY
@@ -406,7 +431,18 @@ impl StackDialog for SliceOptionsDialog {
}
fn confirm(&mut self, _: &egui::Context) -> Option<SliceOptions> {
Some(self.options.clone())
let Some(held) = &mut self.held else { return Some(self.options.clone()) };
if let Some(answer) = held.finish() {
return Some(answer);
}
if !held.is_waiting() {
held.file(self.options.clone());
}
None
}
fn held_state(&self) -> Option<HeldOk> {
self.held.as_ref().and_then(HeldAnswer::state)
}
fn cancelled(&mut self, _: &egui::Context) {
@@ -518,6 +554,7 @@ pub struct DivideSlicesDialog {
id: DialogId,
axes: Axes,
lengths: LengthUnits,
held: Option<HeldAnswer<Axes>>,
}
impl DivideSlicesDialog {
@@ -527,6 +564,7 @@ impl DivideSlicesDialog {
id: dialog_id("slice.divide"),
axes: Axes::of(divide),
lengths: LengthUnits::new(UnitKind::Pixels, UnitKind::Pixels, 72.0),
held: None,
}
}
@@ -584,6 +622,25 @@ fn axis_rows(ui: &mut Ui, axis: &mut AxisState, caption: &Label, words: &SliceWo
});
}
impl HoldsOk for DivideSlicesDialog {
type Answer = DivideSlices;
fn held_ok(mut self) -> Self {
self.held = Some(HeldAnswer::new());
self
}
fn take_ok(&mut self) -> Option<DivideSlices> {
self.held.as_mut()?.take()?.answer()
}
fn answer_ok(&mut self, answer: Result<(), Label>) {
if let Some(held) = &mut self.held {
held.answer(answer);
}
}
}
impl StackDialog for DivideSlicesDialog {
type Result = DivideSlices;
@@ -633,7 +690,11 @@ impl StackDialog for DivideSlicesDialog {
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<DivideSlices>> {
let words = Env::of(ui).words::<SliceWords>();
let lengths = self.lengths;
let shown = FormDialog::new(words.divide_title.clone(), Bind::bound(&mut self.axes)).show(ui, |ui, _, axes| {
let mut dialog = FormDialog::new(words.divide_title.clone(), Bind::bound(&mut self.axes));
if let Some(held) = &mut self.held {
dialog = dialog.held(held);
}
let shown = dialog.show(ui, |ui, _, axes| {
FieldGroup::new(words.divide_title.clone()).show(ui, |ui, _| {
axis_rows(ui, &mut axes.rows, &words.horizontally, &words, lengths);
axis_rows(ui, &mut axes.columns, &words.vertically, &words, lengths);
@@ -648,6 +709,18 @@ impl StackDialog for DivideSlicesDialog {
}
fn confirm(&mut self, _: &egui::Context) -> Option<DivideSlices> {
self.axes.answer()
let answer = self.axes.answer();
let Some(held) = &mut self.held else { return answer };
if let Some(axes) = held.finish() {
return axes.answer();
}
if !held.is_waiting() && answer.is_some() {
held.file(self.axes);
}
None
}
fn held_state(&self) -> Option<HeldOk> {
self.held.as_ref().and_then(HeldAnswer::state)
}
}
+2 -2
View File
@@ -345,12 +345,12 @@ impl Body<'_> {
];
let cap = [
(LineCap::Butt, "stroke_cap_butt", &words.butt),
(LineCap::Round, "stroke_cap_round", &words.round_cap),
(LineCap::Round, "stroke_cap_round", if icons { &words.round_cap_icon } else { &words.round_cap }),
(LineCap::Square, "stroke_cap_square", &words.square),
];
let join = [
(LineJoin::Miter, "stroke_join_miter", &words.miter),
(LineJoin::Round, "stroke_join_round", &words.round_join),
(LineJoin::Round, "stroke_join_round", if icons { &words.round_join_icon } else { &words.round_join }),
(LineJoin::Bevel, "stroke_join_bevel", &words.bevel),
];
let event = choice(ui, &words.alignment, "align", held(mixed.align, style.align), &align, self.closed, icons);
+4
View File
@@ -30,6 +30,8 @@ craft_ui::words! {
butt: "strokeEditor.butt" = "Butt / Flat";
/// The round cap.
round_cap: "strokeEditor.roundCap" = "Round";
/// The tooltip and accessible name of the round cap icon.
round_cap_icon: "strokeEditor.roundCapIcon" = "Round Cap";
/// The square cap.
square: "strokeEditor.square" = "Square";
/// The Corners row.
@@ -38,6 +40,8 @@ craft_ui::words! {
miter: "strokeEditor.miter" = "Miter";
/// The round corner.
round_join: "strokeEditor.roundJoin" = "Round";
/// The tooltip and accessible name of the round join icon.
round_join_icon: "strokeEditor.roundJoinIcon" = "Round Join";
/// The bevelled corner.
bevel: "strokeEditor.bevel" = "Bevel";
/// The Miter limit row.
+21 -5
View File
@@ -492,6 +492,10 @@ pub struct TransformBox<'a> {
/// Whether the corner and side handles are circles (a rounded document editor's look) instead of squares.
#[prop]
round_handles: bool,
/// The side of the corner and side handles in points, for a host with a handle size preference; `None` uses the
/// theme's (`size.handle.md`). A handle's reach grows with a larger side and stays at least the theme's.
#[prop(quantity = "points, from the host's handle size preference")]
handle_side: Option<f32>,
/// Draws the box as a live line's controls (the Line tool's live line as the whole selection). Only the two ends
/// take a press and the keys, each as the box handle it points to ([`LineLook`]), so an end drag scales the box as
/// that handle does; while it is dragged, the box shows as it scales. No other part is declared.
@@ -538,6 +542,7 @@ impl<'a> TransformBox<'a> {
session_arrows: true,
centre_mark: false,
round_handles: false,
handle_side: None,
line: None,
reach: TransformReach::Box,
color: None,
@@ -580,6 +585,16 @@ impl<'a> TransformBox<'a> {
self.color.map_or(StrokeColor::from(theme), StrokeColor::from)
}
/// The side of a corner or side handle: the host's, else the theme's.
fn side_of_handles(&self, style: &TransformBoxStyle) -> f32 {
self.handle_side.unwrap_or(style.handle.side)
}
/// The hit radius of a corner or side handle: the theme's, or more for a host's larger handle.
fn reach_of_handles(&self, style: &TransformBoxStyle) -> f32 {
self.handle_side.map_or(style.handle_reach, |side| style.handle_reach.max(side * HANDLE_REACH_IN_HANDLES))
}
/// Whether the middle of the box is a move part: the reference point is hidden, so it does not take that place.
fn declares_centre(&self) -> bool {
self.takes_input() && self.move_only().is_none() && !self.reference_point && self.inside_moves && self.rules.allows(BoxPart::Inside)
@@ -1032,7 +1047,8 @@ impl TransformBox<'_> {
/// press; `enlarged` with the overflow plus.
fn paint_handle(&self, draw: &Draw<'_>, cx: &Cx<'_, Self>, part: BoxPart, at: Pos2, enlarged: bool) {
let look = &cx.style.handle;
let side = if enlarged { look.side * OVERFLOW_IN_HANDLES } else { look.side };
let side = self.side_of_handles(cx.style);
let side = if enlarged { side * OVERFLOW_IN_HANDLES } else { side };
self.paint_handle_shape(draw, cx, self.handle_shape(at, side), self.rules.allows(part).then(|| BOX.at(part.index())));
if enlarged {
Handle::plus(draw, look, at, side);
@@ -1048,14 +1064,14 @@ impl TransformBox<'_> {
paint_frame(draw, style, self.ink(style.line), corners);
for k in 0..4 {
let middle = corners[k].lerp(corners[(k + 1) % 4], 0.5);
self.paint_handle_shape(draw, cx, self.handle_shape(middle, style.handle.side), None);
self.paint_handle_shape(draw, cx, self.handle_shape(middle, self.side_of_handles(style)), None);
}
}
for (part, end) in line.end_parts() {
self.paint_handle(draw, cx, part, view.to_screen(end), false);
}
for (end, at) in line.free_ends() {
self.paint_handle_shape(draw, cx, self.handle_shape(view.to_screen(at), style.handle.side), Some(LINE_END.at(end.index())));
self.paint_handle_shape(draw, cx, self.handle_shape(view.to_screen(at), self.side_of_handles(style)), Some(LINE_END.at(end.index())));
}
paint_widget(draw, view.to_screen(line.from.midpoint(line.to)), &style.widget, None);
}
@@ -1278,7 +1294,7 @@ impl Component for TransformBox<'_> {
handle => {
let at = self.part_point(&state, handle).map_or(Pos2::ZERO, |at| space.view.to_screen(at));
(
HitShape::circle(at, style.handle_reach),
HitShape::circle(at, self.reach_of_handles(style)),
Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS,
HitPriority::new(HitLevel::Handle, HANDLE_SUB),
FocusShape::Circle,
@@ -1290,7 +1306,7 @@ impl Component for TransformBox<'_> {
}
if let Some(line) = self.line {
for (end, at) in line.free_ends() {
cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), style.handle_reach))
cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), self.reach_of_handles(style)))
.sense(Sense::DRAG | Sense::CLICK | context)
.priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB))
.pointer_only(LINE_END_BY_KEY);
+81 -3
View File
@@ -5,11 +5,11 @@ use craft_behavior::geometry::Constraint;
use craft_behavior::kurbo::{Point, Rect};
use craft_behavior::{CanvasView, EditEvent};
use craft_draw::ui::slice::{
DivideBy, DivideSlices, DivideSlicesDialog, SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOrigin, SliceOverlay, SliceRefusal, SliceTool,
SliceToolSettings,
DivideBy, DivideSlices, DivideSlicesDialog, SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOptions, SliceOptionsDialog, SliceOrigin,
SliceOverlay, SliceRefusal, SliceTool, SliceToolSettings,
};
use craft_ui::contract::{CommandSet, Role, Show as _};
use craft_ui::dialog::DialogHost;
use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, HoldsOk};
use craft_ui::runtime::commands::CommandRef;
use craft_ui::runtime::frame::take_output;
use craft_ui::testing::{Fixture, ToolFixture, access, trial};
@@ -241,3 +241,81 @@ fn divide_slice_names_each_axis_control_by_its_axis() {
}
}
}
const STALE_SELECTION: &str = "Select the opening slices and try again.";
#[trial]
fn slice_options_keeps_its_draft_after_the_app_refuses_ok() {
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(Vec2::new(900.0, 700.0));
let id = host.borrow_mut().open(SliceOptionsDialog::new(SliceOptions::default()).held_ok());
fixture.idle(10);
host.borrow_mut().set_json_field(fixture.ctx(), id, "name", serde_json::json!("Draft name")).unwrap();
fixture.idle(4);
fixture.click(&fixture.by_label("OK").unwrap()).idle(4);
assert_eq!(host.borrow().held_state(id), Some(HeldOk::Waiting));
let draft = host.borrow_mut().get_mut::<SliceOptionsDialog>().unwrap().take_ok().unwrap();
assert_eq!(draft.name, "Draft name");
assert!(host.borrow_mut().get_mut::<SliceOptionsDialog>().unwrap().take_ok().is_none());
assert!(host.borrow_mut().take::<SliceOptionsDialog>().is_none());
host.borrow_mut().get_mut::<SliceOptionsDialog>().unwrap().answer_ok(Err(STALE_SELECTION.into()));
fixture.idle(4);
assert_eq!(host.borrow().get::<SliceOptionsDialog>().unwrap().options(), &draft);
assert!(fixture.by_label(STALE_SELECTION).is_some(), "the refusal shows in the dialog");
fixture.click(&fixture.by_label("OK").unwrap()).idle(4);
let mut open = host.borrow_mut();
let dialog = open.get_mut::<SliceOptionsDialog>().unwrap();
assert_eq!(dialog.take_ok(), Some(draft.clone()));
dialog.answer_ok(Ok(()));
drop(open);
fixture.idle(4);
assert_eq!(host.borrow_mut().take::<SliceOptionsDialog>().and_then(DialogResult::ok), Some(draft));
}
#[trial]
fn divide_slices_can_retry_a_held_answer_and_cancel_it_while_waiting() {
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(Vec2::new(900.0, 700.0));
let id = host.borrow_mut().open(DivideSlicesDialog::new(DivideSlices::new(None, None)).held_ok());
fixture.idle(10);
assert!(!host.borrow_mut().confirm::<DivideSlicesDialog>(fixture.ctx()));
assert!(host.borrow().held_state(id).is_none(), "two disabled axes produce no answer");
host.borrow_mut().set_json_field(fixture.ctx(), id, "rows", serde_json::json!(3)).unwrap();
fixture.idle(4);
let ok = fixture.by_label("OK").unwrap();
assert!(!fixture.tree().is_disabled_key(ok.node), "setting one axis enables OK");
fixture.click(&ok).idle(4);
let draft = DivideSlices::new(Some(DivideBy::Count(3)), None);
let mut open = host.borrow_mut();
let dialog = open.get_mut::<DivideSlicesDialog>().unwrap();
assert_eq!(dialog.take_ok(), Some(draft));
dialog.answer_ok(Err(STALE_SELECTION.into()));
drop(open);
fixture.idle(4);
assert!(fixture.by_label(STALE_SELECTION).is_some());
assert!(!host.borrow_mut().confirm::<DivideSlicesDialog>(fixture.ctx()), "programmatic OK files before closing");
let mut open = host.borrow_mut();
let dialog = open.get_mut::<DivideSlicesDialog>().unwrap();
assert_eq!(dialog.take_ok(), Some(draft));
dialog.answer_ok(Ok(()));
assert!(open.confirm::<DivideSlicesDialog>(fixture.ctx()));
assert_eq!(open.take::<DivideSlicesDialog>().and_then(DialogResult::ok), Some(draft));
open.open(DivideSlicesDialog::new(draft).held_ok());
assert!(!open.confirm::<DivideSlicesDialog>(fixture.ctx()));
drop(open);
fixture.idle(4);
fixture.key(Key::Escape, Modifiers::NONE);
fixture.idle(4);
assert!(matches!(host.borrow_mut().take::<DivideSlicesDialog>(), Some(DialogResult::Cancel)));
host.borrow_mut().open(DivideSlicesDialog::new(draft));
assert!(host.borrow_mut().confirm::<DivideSlicesDialog>(fixture.ctx()), "ordinary callers close immediately");
assert_eq!(host.borrow_mut().take::<DivideSlicesDialog>().and_then(DialogResult::ok), Some(draft));
}
+19
View File
@@ -78,3 +78,22 @@ fn dash_fields_add_after_the_pattern_and_a_cleared_field_ends_it() {
type_into(&mut fixture, "Dash 1", "");
assert_eq!(style.borrow().dashes, [4.0], "the first field never clears");
}
#[trial]
fn round_cap_and_round_join_names_lead_to_their_own_actions() {
use craft_draw::ui::stroke::{LineCap, LineJoin};
use craft_ui::testing::{access::focused_key, focus::AccessActionKind};
let (mut fixture, style) = editor(vec![4.0, 2.0]);
let cap = fixture.by_label("Round Cap").expect("the cap has its own accessible name");
let join = fixture.by_label("Round Join").expect("the join has its own accessible name");
assert_ne!(cap.node, join.node, "the names find independent choices");
fixture.click(&cap).settle();
assert_eq!(style.borrow().cap, LineCap::Round);
assert_eq!(style.borrow().join, LineJoin::Miter);
fixture.access(AccessActionKind::Focus, &join).settle();
assert_eq!(focused_key(fixture.tree()), join.node);
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(style.borrow().join, LineJoin::Round);
assert_eq!(style.borrow().cap, LineCap::Round);
}
+49
View File
@@ -60,6 +60,8 @@ struct Config {
f32_host: bool,
centre_mark: bool,
round_handles: bool,
/// The host's handle side, `None` for the theme's.
handle_side: Option<f32>,
line: Option<LineLook>,
/// Snap targets beside the guides at [`SNAP_XS`].
targets: Vec<SnapTarget>,
@@ -119,6 +121,7 @@ fn defaults() -> Config {
f32_host: false,
centre_mark: false,
round_handles: false,
handle_side: None,
line: None,
targets: Vec::new(),
suspend: SnapSuspend::Control,
@@ -218,6 +221,9 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness {
if let Some(line) = config.line {
control = control.line(line);
}
if let Some(side) = config.handle_side {
control = control.handle_side(side);
}
control = control.reach(config.reach).session_commit(config.session_commit);
if config.hover_frame {
control = control.id(frame_id);
@@ -1649,3 +1655,46 @@ fn round_handles_are_circles() {
// Each handle is a filled circle and its stroke.
assert_eq!(circles(true), circles(false) + 16, "the four corners and four sides are circles");
}
/// A host's handle side draws the corner and side handles at that side: a larger side draws a larger square.
#[trial]
fn a_host_handle_side_sets_the_drawn_handle_square() {
let corner_side = |side: Option<f32>| {
let mut h = harness(BoxState::from_rect(RECT), |config| config.handle_side = side);
let corner = h.screen(Point::new(RECT.x1, RECT.y1));
let sides: Vec<f32> = h
.fixture
.frame_shapes()
.iter()
.filter_map(|shape| match shape {
Shape::Rect(square) if (square.rect.center() - corner).length() < 0.5 => Some(square.rect.width()),
_ => None,
})
.collect();
sides.into_iter().fold(0.0, f32::max)
};
let (small, large) = (corner_side(Some(4.0)), corner_side(Some(12.0)));
assert!(small > 0.0, "the corner handle is drawn as a square");
assert!(large > small, "a larger side draws a larger square: {large} against {small}");
}
/// A large host handle takes a press anywhere on its square, also past the theme's reach, and the press drags it.
#[trial]
fn a_press_just_inside_a_large_handles_edge_grabs_it() {
// 7 points in from the bottom right corner on both axes: inside a 16 point square, about 9.9 from its centre.
let near_edge = Point::new(RECT.x1 - 7.0, RECT.y1 - 7.0);
let mut theme = harness(BoxState::from_rect(RECT), |config| config.rules = free_rules());
hover(&mut theme, near_edge);
assert_ne!(theme.host.borrow().hovered, Some(BoxPart::Corner(2)), "past the theme's handle reach");
let mut h = harness(BoxState::from_rect(RECT), |config| {
config.rules = free_rules();
config.handle_side = Some(16.0);
});
hover(&mut h, near_edge);
assert_eq!(h.host.borrow().hovered, Some(BoxPart::Corner(2)), "on the large handle's square");
drag(&mut h, near_edge, Point::new(RECT.x1 + 13.0, RECT.y1 + 13.0));
let quad = h.state().quad;
assert!(quad[2].x > RECT.x1 + 1.0 && quad[2].y > RECT.y1 + 1.0, "the corner moved with the drag: {quad:?}");
assert_eq!(quad[0], Point::new(RECT.x0, RECT.y0), "the opposite corner stayed: {quad:?}");
}
+32 -5
View File
@@ -15,7 +15,7 @@ pub type Migration = fn(Value) -> Result<Value, String>;
/// edit a shipped one.
pub const MIGRATIONS: &[Migration] = &[
v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9, v9_to_v10, v10_to_v11, v11_to_v12, v12_to_v13, v13_to_v14,
v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18,
v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, v18_to_v19,
];
/// The schema version this build writes (and the newest it reads).
@@ -262,6 +262,13 @@ fn v17_to_v18(doc: Value) -> Result<Value, String> {
Ok(doc)
}
/// v18 → v19: Script Project items (`ItemKind::Script`: script lines, slates with linked takes,
/// marks and independently positioned thumbnails). Existing data needs no change; older builds
/// must refuse such projects instead of failing on or dropping the Script items when saving.
fn v18_to_v19(doc: Value) -> Result<Value, String> {
Ok(doc)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -272,10 +279,10 @@ mod tests {
let bare = json!({"version": 2, "items": {}, "root": {}, "extra": [1, 2]});
assert_eq!(detect_version(&bare).unwrap(), 1);
let migrated = migrate_with(MIGRATIONS, bare, 1).unwrap();
assert_eq!(migrated["schema_version"], 18);
assert_eq!(migrated["schema_version"], SCHEMA_VERSION);
assert_eq!(migrated["project"]["extra"], json!([1, 2]));
assert_eq!(migrated["generator"], "FilmCraft (schema v1)");
assert_eq!(detect_bytes(serde_json::to_string(&migrated).unwrap().as_bytes()).unwrap(), 18);
assert_eq!(detect_bytes(serde_json::to_string(&migrated).unwrap().as_bytes()).unwrap(), SCHEMA_VERSION);
let parsed: EnvelopeIn<Value> = serde_json::from_value(migrated).unwrap();
assert!(parsed.view.is_none());
assert_eq!(parsed.project["extra"], json!([1, 2]));
@@ -303,20 +310,40 @@ mod tests {
let item = json!({"Media": {"interpret": {"par": [1, 1]}}});
let v17 = json!({"format": FORMAT_ID, "schema_version": 17, "project": {"items": {"1": {"kind": item}}, "root": {}}});
let up = migrate_with(MIGRATIONS, v17.clone(), 17).unwrap();
assert_eq!(up["schema_version"], 18);
assert_eq!(up["schema_version"], SCHEMA_VERSION);
assert_eq!(up["project"], v17["project"]);
let raw = json!({"white_balance": {"Custom": {"temperature": 3200.0, "tint": 12.5}}, "exposure": -0.75});
let mut v18 = up;
v18["schema_version"] = json!(18);
v18["project"]["items"]["1"]["kind"]["Media"]["interpret"]["raw"] = raw.clone();
let bytes = serde_json::to_vec(&v18).unwrap();
let (file, version): (EnvelopeIn<Value>, _) = decode(&bytes).unwrap();
assert_eq!(version, 18);
assert_eq!(file.project["items"]["1"]["kind"]["Media"]["interpret"]["raw"], raw);
}
/// Schema 19 (Script items): a v18 project upgrades with its data untouched, and a v19 project
/// with a Script item is read rather than refused as too new.
#[test]
fn v18_upgrades_and_v19_script_items_are_read() {
let media = json!({"Media": {"interpret": {"par": [1, 1]}}});
let v18 = json!({"format": FORMAT_ID, "schema_version": 18, "project": {"items": {"1": {"kind": media}}, "root": {}}});
let up = migrate_with(MIGRATIONS, v18.clone(), 18).unwrap();
assert!(up["schema_version"].as_u64().unwrap() > 18);
assert_eq!(up["project"], v18["project"]);
let script = json!({"Script": {"lines": [{"id": 1, "text": "one"}], "slates": [{"id": 2, "takes": [{"id": 3, "source": 1}]}], "next_id": 4}});
let mut v19 = up;
v19["schema_version"] = json!(19);
v19["project"]["items"]["2"] = json!({"kind": script.clone()});
let bytes = serde_json::to_vec(&v19).unwrap();
let (file, version): (EnvelopeIn<Value>, _) = decode(&bytes).unwrap();
assert_eq!(version, 19);
assert_eq!(file.project["items"]["2"]["kind"], script);
assert_eq!(file.project["items"]["1"]["kind"], media);
}
#[test]
fn rejects_wrong_future_and_damaged_envelopes() {
assert!(matches!(detect_bytes(br#"{"format":"other","schema_version":1}"#), Err(FormatError::NotAProject(_))));
assert!(matches!(detect_bytes(br#"{"schema_version":19}"#), Err(FormatError::TooNew { found: 19, supported: 18 })));
assert!(matches!(detect_bytes(br#"{"schema_version":20}"#), Err(FormatError::TooNew { found: 20, supported: 19 })));
assert!(matches!(detect_bytes(br#"{"schema_version":0}"#), Err(FormatError::TooOld { found: 0, oldest: 1 })));
assert!(matches!(detect_bytes(b"{"), Err(FormatError::Corrupt(_))));
assert!(matches!(migrate_with(MIGRATIONS, json!([]), 1), Err(FormatError::Migration { from: 1, .. })));
+109 -22
View File
@@ -1,6 +1,8 @@
//! [`GlyphsPanel`]: Photoshop's Glyphs panel. A family and style picker, a category list (Entire Font, Punctuation,
//! Currency, ...), a grid of glyph cells drawn by the app's text engine, a zoom slider, and the recently used
//! glyphs in a row at the top. Double-click or Enter inserts the glyph where the app can insert.
//! A secondary click on a grid cell reports that cell ([`GlyphsPanelOutput::menu`]); the app opens
//! the menu from the grid response.
#[cfg(feature = "suite")]
pub(crate) mod stories;
@@ -11,7 +13,7 @@ use craft_behavior::{IconId, Selection};
use craft_host::Section;
use craft_ui::contract::{
ActivateOn, Bind, CollectionEvent, CommandSet, Entry, NoValue, Outcome, Pad, Pattern, Props, Remember as _, SelectMode, Show as _,
ShowCollection as _, ShowContainer as _,
ShowCollection as _, ShowContainer as _, Sizing,
};
use craft_ui::display::{Shade, Spinner, Text};
use craft_ui::layout_components::{Row, Stack};
@@ -209,6 +211,19 @@ pub struct GlyphsPanelOutput {
pub alternate: Option<AlternatePick>,
/// The family or style changed in the panel's own pickers.
pub font_changed: bool,
/// The grid cell a context menu was asked for, with the grid response the menu hangs from.
/// Reported on the secondary click and on every later pass while that menu stays open.
pub menu: Option<GlyphCellMenu>,
}
/// A grid cell's context menu: the cell, and the grid response the app hangs the menu from.
#[derive(Debug)]
#[non_exhaustive]
pub struct GlyphCellMenu {
/// The cell.
pub cell: GlyphCell,
/// The grid the menu hangs from.
pub opener: Response,
}
/// The cell whose popup was used and the picked glyph.
@@ -306,9 +321,36 @@ struct CellsCache {
cells: Arc<Vec<GlyphCell>>,
}
/// The tile selection of the main grid.
/// The tile selection of the main grid and the host's last mark in the shown cells.
#[derive(Clone, Default)]
struct Marked(Selection<usize>);
struct Marked {
selection: Selection<usize>,
host: Option<(GlyphCell, usize)>,
}
/// The glyph a context menu was opened on, and the face it was opened in. Later passes keep this glyph: the grid
/// remembers the row, and another glyph of a same-length list must not take the menu over. A glyph id names a glyph
/// only in its own face, so the menu holds the cell only while that face is shown: the same family and style, and
/// for a glyph id the same source revision, since the source can replace a face under the same names.
#[derive(Clone, Default)]
struct HeldMenu(Option<MenuCell>);
/// A held menu's cell, the family and style it was clicked in, and the source revision then.
#[derive(Clone)]
struct MenuCell {
cell: GlyphCell,
family: String,
style: String,
revision: u64,
}
impl MenuCell {
/// Whether the cell still names the glyph it was clicked on in `face` at `revision`. A character names the same
/// glyph after the source reads its faces again; a glyph id may not.
fn holds_in(&self, face: (&str, &str), revision: u64) -> bool {
(self.family.as_str(), self.style.as_str()) == face && (matches!(self.cell, GlyphCell::Char(_)) || self.revision == revision)
}
}
/// The alternates popup: whether it is open, the cell it was opened for and that cell's alternates, read once when
/// it opened.
@@ -334,10 +376,12 @@ fn recent_cells(recent: &[String]) -> Vec<GlyphCell> {
seen.into_iter().map(GlyphCell::Char).collect()
}
/// The cells of the shown set: the recents, or the source's cells of the category.
/// The cells of the shown set: the recents, or the source's cells of the category, read again when the source's
/// `revision` (read once for the pass) is not the one they were read at.
fn category_cells(
cache: &mut CellsCache,
source: &dyn GlyphSource,
revision: u64,
family: &str,
style: &str,
category: &str,
@@ -347,7 +391,6 @@ fn category_cells(
return Arc::new(recent_cells(recent));
}
let key = (family.to_owned(), style.to_owned(), category.to_owned());
let revision = source.revision();
if cache.key != key || cache.revision != revision {
*cache = CellsCache { key, revision, cells: Arc::new(source.cells(family, style, category)) };
}
@@ -422,7 +465,7 @@ pub struct GlyphsPanel<'a> {
/// Whether the app has a place to insert a glyph: a double click or Enter inserts.
#[prop]
can_insert: bool,
/// The host's cell (the selected character); the grid selects it.
/// The host's cell (the selected character); a change selects it without overriding grid navigation.
#[prop]
marked: Option<GlyphCell>,
/// In this pass only, the grid moves its lead to that cell and scrolls it into view. The host passes it in the
@@ -483,12 +526,13 @@ impl<'a> GlyphsPanel<'a> {
});
});
craft_ui::runtime::frame::request_repaint_after(ui.ctx(), SCAN_POLL_SECONDS);
return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false };
return GlyphsPanelOutput { response: shown.output, activated: None, alternate: None, font_changed: false, menu: None };
}
let ctx = ui.ctx().clone();
let mut activated_out: Option<GlyphCell> = None;
let mut picked: Option<AlternatePick> = None;
let mut font_changed = false;
let mut menu: Option<GlyphCellMenu> = None;
let shown = Stack::new().label(label).command_scope(GlyphsCommand::SCOPE).show(ui, |ui, cx| {
cx.publish(GlyphsCommand::Alternates, CommandState::new());
let mut state = read_bind(&mut settings, cx).unwrap_or_default();
@@ -505,20 +549,31 @@ impl<'a> GlyphsPanel<'a> {
let (held_family, held_style) = (read_bind(&mut family, cx).unwrap_or_default(), read_bind(&mut style, cx).unwrap_or_default());
let (mut face_family, mut face_style) = (held_family.clone(), held_style.clone());
Row::new().show(ui, |ui, _| {
let compact = ui.available_width() < env.tokens.size.length.field.md;
let picker_ids = ui.scope_id().with("glyph-pickers");
let mut font_controls = |ui: &mut Ui| {
if families.is_empty() {
Text::new(face_family.clone()).show(ui);
} else {
let entries: Vec<Entry<String>> = families.iter().map(|name| Entry::new(name.clone(), name.clone())).collect();
Select::new(words.font.clone(), Bind::bound(&mut face_family), &entries).searchable().show(ui);
let picker = Select::new(words.font.clone(), Bind::bound(&mut face_family), &entries).id(picker_ids.with("font")).searchable();
let picker = if compact { picker.sizing(Sizing::FillWidth) } else { picker };
picker.show(ui);
}
if styles.is_empty() {
Text::new(face_style.clone()).show(ui);
} else {
let entries: Vec<Entry<String>> = styles.iter().map(|name| Entry::new(name.clone(), name.clone())).collect();
Select::new(words.style.clone(), Bind::bound(&mut face_style), &entries).show(ui);
let picker = Select::new(words.style.clone(), Bind::bound(&mut face_style), &entries).id(picker_ids.with("style"));
let picker = if compact { picker.sizing(Sizing::FillWidth) } else { picker };
picker.show(ui);
}
});
};
if compact {
Stack::new().id(picker_ids.with("font-controls")).fill_width().show(ui, |ui, _| font_controls(ui));
} else {
Row::new().id(picker_ids.with("font-controls")).fill_width().wrap(true).show(ui, |ui, _| font_controls(ui));
}
if face_family != held_family {
write_bind(&mut family, cx, face_family.clone(), "Glyphs font");
}
@@ -534,15 +589,23 @@ impl<'a> GlyphsPanel<'a> {
state.category = CATEGORIES[0].to_owned();
}
let mut category = state.category.clone();
Row::new().show(ui, |ui, _| {
let mut category_controls = |ui: &mut Ui| {
Text::new(words.show.clone()).show(ui);
let entries: Vec<Entry<String>> = CATEGORIES
.iter()
.map(|name| Entry::new((*name).to_owned(), words.category_name(name).to_owned()))
.chain(extra.iter().map(|(id, name)| Entry::new(id.clone(), name.clone())))
.collect();
Select::new(words.category.clone(), Bind::bound(&mut category), &entries).show(ui);
});
Select::new(words.category.clone(), Bind::bound(&mut category), &entries)
.id(picker_ids.with("category"))
.sizing(Sizing::FillWidth)
.show(ui);
};
if compact {
Stack::new().id(picker_ids.with("category-controls")).fill_width().show(ui, |ui, _| category_controls(ui));
} else {
Row::new().id(picker_ids.with("category-controls")).fill_width().show(ui, |ui, _| category_controls(ui));
}
state.category = category;
// Recently used.
@@ -570,15 +633,20 @@ impl<'a> GlyphsPanel<'a> {
}
}
// The grid.
let cells = category_cells(cx.memory::<CellsCache>(), source, face.0, face.1, &state.category, &state.recent);
// The grid. One revision read serves the pass: a menu cell is stamped with the revision its list was read
// at, so a source that moves on mid-pass cannot give an old glyph id the new revision.
let revision = source.revision();
let cells = category_cells(cx.memory::<CellsCache>(), source, revision, face.0, face.1, &state.category, &state.recent);
let index_of = |cell: GlyphCell| cells.iter().position(|c| *c == cell);
let mut marked = cx.memory::<Marked>().clone();
if let Some(at) = marked_cell.and_then(index_of)
&& marked.0.lead != Some(at)
let host = marked_cell.and_then(|cell| index_of(cell).map(|at| (cell, at)));
if let Some((_, at)) = host
&& (marked.host != host || reveal_cell == marked_cell)
&& marked.selection.lead != Some(at)
{
marked.0 = Selection::single(at);
marked.selection = Selection::single(at);
}
marked.host = host;
match &empty {
Some(text) if cells.is_empty() => {
Text::new(text.clone()).shade(Shade::Muted).show(ui);
@@ -589,7 +657,7 @@ impl<'a> GlyphsPanel<'a> {
.zoom(GridZoom::Fixed(size))
.caption(CaptionPlace::None)
.select(SelectMode::Single)
.selection(Bind::bound(&mut marked.0));
.selection(Bind::bound(&mut marked.selection));
if let Some(at) = reveal_cell.and_then(index_of) {
grid = grid.reveal(at);
}
@@ -608,6 +676,25 @@ impl<'a> GlyphsPanel<'a> {
None => tile,
}
});
// The click names the glyph. Later passes keep that glyph: the grid remembers the row, so a
// same-length list must not move the open menu onto whatever glyph is there now.
let clicked = shown_grid.response.events.iter().find_map(|event| match event {
CollectionEvent::ContextMenu(request) => cells.get(request.key).copied(),
_ => None,
});
let mut held = std::mem::take(cx.memory::<HeldMenu>());
if let Some(cell) = clicked {
held = HeldMenu(Some(MenuCell { cell, family: face.0.to_owned(), style: face.1.to_owned(), revision }));
}
// A closed menu lets go of its cell, and so does another face, or a glyph id after the source
// replaced its faces: the same id there is another glyph.
let other_face = held.0.as_ref().is_some_and(|held| !held.holds_in(face, revision));
if shown_grid.response.menu.is_none() || other_face {
held = HeldMenu(None);
}
let opener = shown_grid.response.response.clone();
menu = held.0.as_ref().map(|held| GlyphCellMenu { cell: held.cell, opener });
*cx.memory::<HeldMenu>() = held;
for event in shown_grid.response.events {
match event {
CollectionEvent::Activate(key) => activated = cells.get(key).copied().or(activated),
@@ -660,7 +747,7 @@ impl<'a> GlyphsPanel<'a> {
// Footer: the selection, the count and the zoom.
let n = cells.len() as u64;
let count = words.count.text(n, &env.format().integer(n));
let info = match marked.0.lead.and_then(|lead| cells.get(lead)).copied() {
let info = match marked.selection.lead.and_then(|lead| cells.get(lead)).copied() {
Some(GlyphCell::Char(c)) => match source.describe(face.0, face.1, GlyphCell::Char(c)).gid {
Some(gid) => words.selected_glyph.fill(&[("code", &code(c)), ("gid", &gid.to_string()), ("count", &count)]),
None => words.selected.fill(&[("code", &code(c)), ("count", &count)]),
@@ -693,6 +780,6 @@ impl<'a> GlyphsPanel<'a> {
write_bind(&mut settings, cx, state, "Glyphs panel");
}
});
GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed }
GlyphsPanelOutput { response: shown.output, activated: activated_out, alternate: picked, font_changed, menu }
}
}
+33
View File
@@ -91,6 +91,8 @@ craft_ui::words! {
preview_small: "fontPicker.previewSmall" = "Small";
preview_medium: "fontPicker.previewMedium" = "Medium";
preview_large: "fontPicker.previewLarge" = "Large";
/// The dropdown of the host's sample texts, beside the preview size.
sample_text: "fontPicker.sampleText" = "Sample Text";
/// The similar-fonts chip, with `{family}` for the reference family.
similar_to: template "fontPicker.similarTo" = "≈ {family}";
clear_similar: "fontPicker.clearSimilar" = "Clear Similar Fonts";
@@ -178,6 +180,28 @@ impl FontPreviewSize {
}
}
/// A sample text the host offers in the Sample Text dropdown: the key the settings keep, its name in the dropdown and
/// the text every sample shows while it is chosen.
#[derive(Clone, Debug)]
pub struct SampleText<'a> {
key: &'a str,
label: Label,
text: &'a str,
}
impl<'a> SampleText<'a> {
/// The sample text `key` named `label`, showing `text`.
pub fn new(key: &'a str, label: impl Into<Label>, text: &'a str) -> Self {
SampleText { key, label: label.into(), text }
}
}
/// The sample text the settings keep the key of, else the first of `texts`; `None` when the host offers none.
fn chosen_sample<'s, 'a>(texts: &'s [SampleText<'a>], settings: Option<&FontPickerSettings>) -> Option<&'s SampleText<'a>> {
let key = settings.and_then(|s| s.sample_text.as_deref());
texts.iter().find(|text| Some(text.key) == key).or_else(|| texts.first())
}
/// Coverage from the face: Latin, the basic Latin letters in the cmap; 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.
@@ -302,6 +326,9 @@ pub struct FontPickerSettings {
pub names_in_english: bool,
/// Row samples and the banner paint black type on a white paper fill, in every theme.
pub samples_on_white: bool,
/// The key of the sample text chosen in the Sample Text dropdown; without one, or with a key the host no longer
/// offers, the first of the host's sample texts.
pub sample_text: Option<String>,
}
impl Default for FontPickerSettings {
@@ -313,6 +340,7 @@ impl Default for FontPickerSettings {
preview: FontPreviewSize::default(),
names_in_english: false,
samples_on_white: false,
sample_text: None,
}
}
}
@@ -700,6 +728,10 @@ pub struct FontPicker<'a> {
/// The preview banner's text and every row's sample (the sample word when not given).
#[prop]
preview_text: Option<&'a str>,
/// The sample texts the Sample Text dropdown offers, beside the preview size in the `Chips` layout; the chosen one
/// takes the place of `preview_text`. Empty: no dropdown.
#[prop]
sample_texts: &'a [SampleText<'a>],
/// Families the host can fetch but that are not installed, listed with the served mark.
#[prop]
served: &'a [String],
@@ -770,6 +802,7 @@ impl<'a> FontPicker<'a> {
rested: None,
preview: Preview::Unchanged,
preview_text: None,
sample_texts: &[],
served: &[],
sets: &[],
scripts: &[],
+53 -9
View File
@@ -14,12 +14,13 @@ use craft_ui::buttons::{Button, IconButton, ToggleButton};
use craft_ui::choice::{Radio, RadioGroup};
use craft_ui::contract::overlay::Dismiss;
use craft_ui::contract::{
Bind, CollectionEvent, ColumnSpec, Cx, Edit as _, LeadSource, Overlay, OverlayUi, Overlays as _, Props as _, Remember as _, Show as _,
Bind, CollectionEvent, ColumnSpec, Cx, Edit as _, Entry, LeadSource, Overlay, OverlayUi, Overlays as _, Props as _, Remember as _, Show as _,
ShowCollection as _, ShowContainer as _, ToggleColumn, WordSetCx as _, clicked,
};
use craft_ui::display::{Divider, Text};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::list::{List, ListRow, RowEvent, ThumbSize, ToggleCell, ToggleFace, ToggleState, TrailingFace, TreeLeaves};
use craft_ui::pickers::Select;
use craft_ui::primitives::{FacesCx, IconSpec};
use craft_ui::runtime::env::Label;
use craft_ui::runtime::memory::StageAccess;
@@ -28,8 +29,8 @@ use super::banner::FontPreviewBanner;
use super::rank::{FamilyInfos, Language, Listing, host_rows, list, shown_name};
use super::{
FamilyRow, FamilySet, FilterLayout, FontClass, FontFilters, FontFormat, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords,
FontPreviewSize, FontScript, HostFontGroup, HostFontKind, HostFontRow, POPUP, SAMPLE_EM, SIMILAR, Sample, Typing, infos_of, read, ui_language,
write,
FontPreviewSize, FontScript, HostFontGroup, HostFontKind, HostFontRow, POPUP, SAMPLE_EM, SIMILAR, Sample, SampleText, Typing, chosen_sample,
infos_of, read, ui_language, write,
};
use crate::panel::faces::{self, Owner, Shown};
use crate::panel::specimen::{FontSample, SampleFace};
@@ -374,16 +375,44 @@ fn set_chip(ui: &mut egui::Ui, set: &FamilySet<'_>, keys: &mut Vec<String>) {
}
}
/// The Sample Text dropdown over the host's `texts`, showing `chosen`; a pick writes its key to `key`.
fn sample_text_select(
ui: &mut egui::Ui,
texts: &[SampleText<'_>],
chosen: Option<&SampleText<'_>>,
key: &mut Option<String>,
words: &FontPickerWords,
) {
let Some(chosen) = chosen else { return };
let entries: Vec<Entry<String>> = texts.iter().map(|text| Entry::new(text.key.to_owned(), text.label.clone())).collect();
let mut picked = chosen.key.to_owned();
Select::new(words.sample_text.clone(), Bind::bound(&mut picked), &entries).show(ui);
if picked != chosen.key {
*key = Some(picked);
}
}
/// What the preview area of the `Chips` filters offers and writes: the preview size, and the host's sample texts with
/// the chosen one and the key a pick writes.
struct PreviewChoices<'s, 'a> {
size: &'s mut Option<FontPreviewSize>,
texts: &'s [SampleText<'a>],
chosen: Option<&'s SampleText<'a>>,
key: &'s mut Option<String>,
}
/// The `Chips` filter area: the script row; Favorites, the host sets, Any Kind and the classes; Font Technology and
/// Variable; the similar chip while Show Similar Fonts is on; and the Font Preview Size row while samples show.
/// Variable; the similar chip while Show Similar Fonts is on; and, while samples show, the Font Preview Size row and the
/// Sample Text dropdown when the host offers sample texts.
fn filter_chips(
ui: &mut egui::Ui,
filters: &mut FontFilters,
preview: &mut Option<FontPreviewSize>,
choices: PreviewChoices<'_, '_>,
sets: &[FamilySet<'_>],
scripts: &[FontScript],
words: &FontPickerWords,
) {
let PreviewChoices { size: preview, texts, chosen: sample, key } = choices;
Stack::new().show(ui, |ui, _| {
if !scripts.is_empty() {
Row::new().wrap(true).show(ui, |ui, _| {
@@ -436,6 +465,7 @@ fn filter_chips(
{
*size = *next;
}
sample_text_select(ui, texts, sample, key, words);
}
});
}
@@ -589,10 +619,15 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
(&query, narrowing.class, narrowing.favorites, narrowing.variable, &narrowing.similar, narrowing.script, &narrowing.sets, on_white, chips)
.hash(&mut stamp);
let banner_family = lead.unwrap_or_else(|| family.clone());
let texts = picker.sample_texts;
let chosen = chosen_sample(texts, settings.as_ref());
let mut sample_key = settings.as_ref().and_then(|s| s.sample_text.clone());
// The chosen sample text, else the host's preview text.
let host_text = chosen.map(|text| text.text).or(picker.preview_text);
// The library picker always shows the banner, with the sample word when the host gives no text.
let banner_text = picker.preview_text.or((!plain).then_some(words.sample.as_str()));
let banner_text = host_text.or((!plain).then_some(words.sample.as_str()));
// Every row's sample is the banner's text: the host's text, else the sample word.
let sample_text = picker.preview_text.unwrap_or(words.sample.as_str());
let sample_text = host_text.unwrap_or(words.sample.as_str());
let name = words.list.clone();
let mut stars: Vec<(String, bool)> = Vec::new();
let mut over_rows = false;
@@ -618,7 +653,8 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
}
if let Some(filters) = filters.as_mut() {
if chips {
filter_chips(ui, filters, &mut preview_size, sets, scripts, &words);
let choices = PreviewChoices { size: &mut preview_size, texts, chosen, key: &mut sample_key };
filter_chips(ui, filters, choices, sets, scripts, &words);
} else {
filter_bar(ui, filters, &mut hide_classes, &family, &words);
}
@@ -774,8 +810,16 @@ pub(super) fn popup<'a>(picker: &mut FontPicker<'a>, ui: &mut OverlayUi<'_>, cx:
if let Some(size) = preview_size {
changed.preview = size;
}
let sample_changed = sample_key != changed.sample_text;
changed.sample_text = sample_key;
if Some(&changed) != settings.as_ref() {
let label = if stars.is_empty() { "Font preview size" } else { "Favorite font" };
let label = if !stars.is_empty() {
"Favorite font"
} else if sample_changed {
"Font sample text"
} else {
"Font preview size"
};
write(&mut picker.settings, cx, changed, label);
}
}
+237 -2
View File
@@ -3,9 +3,13 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use craft_font_manager::glyphs::{CellInfo, GlyphCell, GlyphSource, GlyphsPanel, GlyphsPanelSettings};
use craft_ui::contract::Bind;
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::menu::{Menu, MenuItem};
use craft_ui::testing::pointer;
use craft_ui::testing::{Fixture, Room, trial};
use egui::{ColorImage, Event};
@@ -43,6 +47,8 @@ struct Seen {
marked: Option<GlyphCell>,
reveal: Option<GlyphCell>,
picks: Vec<(GlyphCell, GlyphCell)>,
/// Cells a secondary click asked for a menu on, in order.
menu: Vec<GlyphCell>,
}
fn rig() -> (Fixture, Rc<RefCell<Seen>>) {
@@ -62,9 +68,13 @@ fn rig() -> (Fixture, Rc<RefCell<Seen>>) {
if let Some(cell) = reveal {
panel = panel.reveal(cell);
}
if let Some(pick) = panel.show(ui).alternate {
let out = panel.show(ui);
if let Some(pick) = out.alternate {
shown.borrow_mut().picks.push((pick.cell, pick.glyph));
}
if let Some(menu) = out.menu {
shown.borrow_mut().menu.push(menu.cell);
}
});
fx.in_room(Room::Window);
fx.settle();
@@ -105,6 +115,39 @@ fn the_marked_cell_is_selected_and_revealed_only_in_the_pass_that_carries_reveal
assert!(!visible(&fx, FIRST), "the grid does not jump back to its start");
}
#[trial]
fn a_held_host_mark_leaves_the_keyboard_selection_on_the_active_glyph() {
use egui::{Key, Modifiers};
use std::cell::Cell;
let mark = Rc::new(Cell::new(GlyphCell::Char('ā')));
let held_mark = Rc::clone(&mark);
let activated = Rc::new(Cell::new(None));
let reported = Rc::clone(&activated);
let (mut family, mut style) = ("Plain".to_owned(), "Regular".to_owned());
let mut settings = GlyphsPanelSettings::default();
let mut fx = Fixture::new(move |ui| {
let out = GlyphsPanel::new("Glyphs", &Plain, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut settings))
.can_insert(true)
.marked(held_mark.get())
.show(ui);
if out.activated.is_some() {
reported.set(out.activated);
}
});
fx.in_room(Room::Window).settle();
assert!(selected(&fx, 'ā'), "the host mark selects the starting glyph");
let start = fx.by_label(&name('ā')).expect("the marked glyph");
fx.click(&start).key(Key::ArrowRight, Modifiers::NONE).settle();
assert!(selected(&fx, 'Ă'), "the selection follows the keyboard lead with the same host mark");
fx.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(activated.get(), Some(GlyphCell::Char('Ă')));
mark.set(GlyphCell::Char('Ą'));
fx.frame(Vec::new()).settle();
assert!(selected(&fx, 'Ą'), "a new host mark selects its glyph");
}
#[trial]
fn a_corner_pick_reports_the_cell_and_the_glyph() {
let (mut fx, seen) = rig();
@@ -125,6 +168,159 @@ fn a_corner_pick_reports_the_cell_and_the_glyph() {
assert!(!visible(&fx, 'Ⓑ'), "a pick closes the popup");
}
#[trial]
fn a_secondary_click_reports_the_cell_the_menu_is_for() {
let (mut fx, seen) = rig();
let cell = fx.by_label(&name(FIRST)).expect("the first cell");
let at = cell.center();
fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]);
fx.frame(vec![pointer::secondary(at, false)]);
fx.settle();
let menu = seen.borrow().menu.clone();
assert!(!menu.is_empty(), "the secondary click names the cell");
assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the menu is for the clicked cell: {menu:?}");
}
/// A list whose first cell changes, at the same length, when `swapped` is set. The revision changes with it, so the
/// panel reads the list again.
struct Swap(Arc<AtomicBool>);
impl GlyphSource for Swap {
fn cells(&self, _: &str, _: &str, _: &str) -> Vec<GlyphCell> {
let first = if self.0.load(Ordering::Relaxed) { '\u{0102}' } else { FIRST };
std::iter::once(GlyphCell::Char(first)).chain((1..300).filter_map(|i| char::from_u32(0x100 + i).map(GlyphCell::Char))).collect()
}
fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option<egui::ColorImage> {
None
}
fn revision(&self) -> u64 {
u64::from(self.0.load(Ordering::Relaxed))
}
}
#[trial]
fn an_open_menu_keeps_the_clicked_cell_when_that_row_changes() {
let swapped = Arc::new(AtomicBool::new(false));
let source = Swap(Arc::clone(&swapped));
let seen = Rc::new(RefCell::new(Vec::<GlyphCell>::new()));
let shown = Rc::clone(&seen);
let (mut family, mut style, mut settings) = ("Plain".to_owned(), "Regular".to_owned(), GlyphsPanelSettings::default());
let mut fx = Fixture::new(move |ui| {
let out = GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut settings))
.can_insert(true)
.show(ui);
if let Some(menu) = out.menu {
shown.borrow_mut().push(menu.cell);
Menu::context("Glyph", &menu.opener).show(ui, |ui, _| {
MenuItem::new("Insert Glyph").show(ui);
});
}
});
fx.in_room(Room::Window);
fx.settle();
let cell = fx.by_label(&name(FIRST)).expect("the first cell");
let at = cell.center();
fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]);
fx.frame(vec![pointer::secondary(at, false)]);
fx.settle();
assert!(seen.borrow().contains(&GlyphCell::Char(FIRST)), "the click names the cell");
seen.borrow_mut().clear();
swapped.store(true, Ordering::Relaxed);
fx.frame(Vec::new());
fx.settle();
let menu = seen.borrow().clone();
assert!(!menu.is_empty(), "the menu stays open");
assert!(menu.iter().all(|cell| *cell == GlyphCell::Char(FIRST)), "the row's new glyph does not take the menu: {menu:?}");
}
/// Unencoded glyphs 1 to 300 in every face and at every revision: the same id names another glyph in another face,
/// or in a face the source replaced under the same names.
struct Unencoded(Arc<AtomicU64>);
impl GlyphSource for Unencoded {
fn cells(&self, _: &str, _: &str, _: &str) -> Vec<GlyphCell> {
(1..=300).map(GlyphCell::Glyph).collect()
}
fn glyph(&self, _: &str, _: &str, _: GlyphCell, _: u32) -> Option<ColorImage> {
None
}
fn revision(&self) -> u64 {
self.0.load(Ordering::Relaxed)
}
}
/// A host menu open on glyph 1 of an [`Unencoded`] source, with the family and the revision the test can change.
struct GlyphMenu {
fx: Fixture,
family: Rc<RefCell<String>>,
revision: Arc<AtomicU64>,
seen: Rc<RefCell<Vec<GlyphCell>>>,
}
impl GlyphMenu {
fn open() -> Self {
let revision = Arc::new(AtomicU64::new(0));
let source = Unencoded(Arc::clone(&revision));
let family = Rc::new(RefCell::new("Plain".to_owned()));
let host_family = Rc::clone(&family);
let seen = Rc::new(RefCell::new(Vec::<GlyphCell>::new()));
let shown = Rc::clone(&seen);
let (mut style, mut settings) = ("Regular".to_owned(), GlyphsPanelSettings::default());
let mut fx = Fixture::new(move |ui| {
let out = {
let mut family = host_family.borrow_mut();
GlyphsPanel::new("Glyphs", &source, Bind::bound(&mut *family), Bind::bound(&mut style), Bind::bound(&mut settings))
.can_insert(true)
.show(ui)
};
if let Some(menu) = out.menu {
shown.borrow_mut().push(menu.cell);
Menu::context("Glyph", &menu.opener).show(ui, |ui, _| {
MenuItem::new("Insert Glyph").show(ui);
});
}
});
fx.in_room(Room::Window);
fx.settle();
let cell = fx.by_label("1, glyph 1").expect("the first glyph");
let at = cell.center();
fx.frame(vec![pointer::moved(at), pointer::secondary(at, true)]);
fx.frame(vec![pointer::secondary(at, false)]);
fx.settle();
assert!(seen.borrow().contains(&GlyphCell::Glyph(1)), "the click names the glyph");
seen.borrow_mut().clear();
GlyphMenu { fx, family, revision, seen }
}
/// The cells the menu reported over the next passes.
fn reported(&mut self) -> Vec<GlyphCell> {
self.fx.frame(Vec::new());
self.fx.settle();
self.seen.borrow().clone()
}
}
#[trial]
fn an_open_menu_does_not_report_a_glyph_id_from_another_face() {
let mut open = GlyphMenu::open();
*open.family.borrow_mut() = "Other".to_owned();
let menu = open.reported();
assert!(menu.is_empty(), "the clicked id names another glyph in the new face, so the menu reports none: {menu:?}");
}
#[trial]
fn an_open_menu_does_not_report_a_glyph_id_after_the_source_replaces_the_face() {
let mut open = GlyphMenu::open();
open.revision.store(1, Ordering::Relaxed);
let menu = open.reported();
assert!(menu.is_empty(), "the face behind the same names changed, so the clicked id names another glyph: {menu:?}");
}
#[trial]
fn glyphs_panel_alternates() {
let (mut fx, _seen) = rig();
@@ -139,3 +335,42 @@ fn glyphs_panel_alternates() {
assert!(visible(&fx, alternate), "the popup lists every alternate of the cell");
}
}
#[trial]
fn the_font_style_and_category_pickers_fit_in_a_narrow_glyphs_panel() {
let expected_family = "A particularly long font family name";
let families = ["Plain".to_owned(), expected_family.to_owned()];
let styles = ["Regular".to_owned(), "Extra Bold Extended Italic".to_owned()];
let selected = Rc::new(RefCell::new(String::new()));
let seen = Rc::clone(&selected);
let (mut family, mut style, mut settings) = ("Plain".to_owned(), "Regular".to_owned(), GlyphsPanelSettings::default());
let mut fx = Fixture::new(move |ui| {
let out = GlyphsPanel::new("Glyphs", &Plain, Bind::bound(&mut family), Bind::bound(&mut style), Bind::bound(&mut settings))
.families(&families)
.styles(&styles)
.show(ui);
if out.font_changed {
*seen.borrow_mut() = family.clone();
}
});
let width = 100.0;
fx.room(egui::vec2(width, 520.0)).settle();
for label in ["Font", "Style", "Category"] {
let target = fx.by_label(label).unwrap_or_else(|| panic!("missing {label}"));
assert!(target.rect.left() >= 0.0 && target.rect.right() <= width, "{label} overflows at {:?}", target.rect);
}
let category = fx.by_label("Category").expect("the Category picker");
fx.access(craft_ui::testing::focus::AccessActionKind::Focus, &category).settle();
fx.room(egui::vec2(480.0, 520.0)).settle();
let wide_category = fx.by_label("Category").expect("the Category picker stays available");
let caption = fx.by_label("Show:").expect("the Category caption");
assert_eq!(wide_category.node, category.node);
assert_eq!(fx.tree().focused_key(), category.node);
assert!(wide_category.rect.center().y >= caption.rect.top() && wide_category.rect.center().y <= caption.rect.bottom());
fx.room(egui::vec2(width, 520.0)).settle();
let font = fx.by_label("Font").expect("the Font picker");
fx.click(&font).settle();
let choice = fx.by_label(expected_family).expect("the long font name is accessible in the picker");
fx.click(&choice).settle();
assert_eq!(&*selected.borrow(), expected_family);
}
+62 -2
View File
@@ -9,8 +9,8 @@ use craft_behavior::{GESTURE_GAP, PartKey, Preview};
use craft_font_manager::craft_font_catalog::{Limits, Os, Source};
use craft_font_manager::missing::MissingFontsWords;
use craft_font_manager::picker::{
FamilyInfos, FamilySet, FontClass, FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, FontPreviewSize, FontScript,
HostFontGroup, HostFontRow, MissingAdvice, SIMILAR_COUNT, family_rows,
FamilyInfos, FamilySet, FilterLayout, FontClass, FontFilters, FontPicker, FontPickerKind, FontPickerSettings, FontPickerWords, FontPreviewSize,
FontScript, HostFontGroup, HostFontRow, MissingAdvice, SIMILAR_COUNT, SampleText, family_rows,
};
use craft_font_manager::{Catalog, FontEnv};
use craft_theme::{Contrast, Mode};
@@ -1054,6 +1054,66 @@ fn each_row_samples_the_preview_text_and_a_face_without_it_shows_its_name() {
);
}
/// The sample texts the host offers in the chips rigs: the selection's text first, then a fixed word.
const SAMPLE_TEXTS: [(&str, &str, &str); 2] = [("selection", "Selected Text", "Hello"), ("word", "Word", "Abc")];
/// An open library list in the `Chips` layout over Inter, keeping `settings`, with the host's sample texts when
/// `offered` and "Hello" as the preview text.
fn sample_texts_rig(settings: Rc<RefCell<FontPickerSettings>>, offered: bool) -> Fixture {
let catalog = catalog_of(&[INTER_REGULAR]);
let mut family = "Inter".to_owned();
let mut filters = FontFilters::default();
let mut fx = Fixture::new(move |ui| {
let texts: Vec<SampleText<'_>> =
if offered { SAMPLE_TEXTS.iter().map(|(key, label, text)| SampleText::new(key, *label, text)).collect() } else { Vec::new() };
let mut settings = settings.borrow_mut();
FontPicker::new("Font family", Bind::bound(&mut family), &catalog)
.settings(Bind::bound(&mut settings))
.filters(Bind::bound(&mut filters))
.filter_layout(FilterLayout::Chips)
.preview_text("Hello")
.sample_texts(&texts)
.show(ui);
});
fx.in_room(Room::Window);
fx.settle();
open(&mut fx);
fx
}
/// The host's sample texts make a Sample Text dropdown beside the preview size: the rows and the banner show the
/// chosen text (the first while none is chosen), a choice from the dropdown is kept in the settings and every row
/// follows it, and a stored choice the host no longer offers falls back to the first. Without sample texts there is
/// no dropdown and the preview text shows.
#[trial]
fn the_sample_text_dropdown_picks_what_every_sample_shows() {
let settings = Rc::new(RefCell::new(FontPickerSettings::default()));
let mut fx = sample_texts_rig(Rc::clone(&settings), true);
assert!(fx.by_label("Inter: Hello").is_some(), "with no choice stored the rows show the first sample text");
let dropdown = fx.by_label("Sample Text").expect("the sample text dropdown");
fx.click(&dropdown);
fx.settle();
let word = fx.by_label("Word").expect("the dropdown lists the host's sample texts");
fx.click(&word);
fx.settle();
assert_eq!(settings.borrow().sample_text.as_deref(), Some("word"), "the choice is kept in the settings");
assert!(fx.by_label("Inter: Abc").is_some(), "the row follows the chosen sample text");
assert!(fx.by_label("Inter: Hello").is_none(), "no row keeps the earlier text");
assert!(fx.texts().iter().any(|painted| painted.text == "Abc"), "the banner shows the chosen text");
let stored = |key: &str| {
let mut settings = FontPickerSettings::default();
settings.sample_text = Some(key.to_owned());
Rc::new(RefCell::new(settings))
};
let fx = sample_texts_rig(stored("gone"), true);
assert!(fx.by_label("Inter: Hello").is_some(), "a choice the host no longer offers falls back to the first sample text");
let fx = sample_texts_rig(stored("word"), false);
assert!(fx.by_label("Sample Text").is_none(), "without the host's sample texts there is no dropdown");
assert!(fx.by_label("Inter: Hello").is_some(), "without sample texts the rows show the preview text");
}
/// The repository's Noto Sans CJK SC subset (CFF): its line (hhea 1160/-288) is taller than Inter's.
const CJK_SUBSET: &[u8] = include_bytes!("../../../ui-contract/tests/fonts/NotoSansCJKsc-test.otf");
+12 -1
View File
@@ -12,7 +12,7 @@ build. The build reads a local checkout named by `CRAFT_FONTS_DIR` instead.
|---|---|
| `CRAFT_FONTS_DIR` unset or empty | Empty table. |
| `CRAFT_FONTS_DIR` = a craft-fonts checkout | Every selected face of `fonts/manifest.txt`, embedded with `include_bytes!`. |
| `CRAFT_FONTS_DIR` set, but no manifest or a missing font file | `cargo::warning`, empty table. |
| `CRAFT_FONTS_DIR` is set, but the main manifest or a main font file is missing, or a main font's SHA-256 differs from its manifest. | `Embed` prints `cargo::warning` and writes an empty table. |
| `CRAFT_FONTS_REQUIRED=1` (exactly `1`; other values are ignored) | Error instead when the directory is unset, unreadable, has no selected face, or has no face for a script passed to `scripts`. |
Give `CRAFT_FONTS_DIR` as an absolute path: Cargo runs build scripts in the package's directory.
@@ -209,3 +209,14 @@ a font collection (`fonts/noto-sans-cjk/NotoSansCJK.ttc#2`); without it the inde
field, `role`, is `ui` on interface faces, `mono` on the monospace face, `signature` on the signature
face and absent elsewhere. Fields
after the ninth are ignored.
Each selected font file is hashed and compared with the line's `sha256` field, in either letter
case; a field that is not 64 hex digits is not checked. A mismatch in a main font is `Error::HashMismatch`, treated
like a missing font file: a build error with `CRAFT_FONTS_REQUIRED=1`, and a `cargo::warning` with an
empty table otherwise. A hash mismatch in the optional `tab_face()` font returns the same error
with `CRAFT_FONTS_REQUIRED=1`. Otherwise, `Embed` warns and omits only that font, retaining the other
faces. The error names the manifest that supplied the expected hash.
Without `CRAFT_FONTS_REQUIRED=1`, `Embed` caches hashes at the generated
table's path with `.sha256.txt` appended. Each entry records the font file's size and modification
time, and a file is hashed again only when one of those changes. A required build hashes every file.
+113 -2
View File
@@ -81,7 +81,7 @@ fn checked_face(manifest: &Path, dir: &Path, root: &Path, entry: ManifestEntry,
}
rerun_if_changed(cargo, &path)?;
let (index, sha256) = (entry.index, entry.sha256.clone());
Ok(Face { entry, path, index, cut, sha256 })
Ok(Face { manifest, entry, path, index, cut, sha256 })
}
/// Whether the build script is building for wasm32 (web builds usually embed fewer faces).
@@ -115,6 +115,7 @@ struct Serve {
/// A selected face and the file the table embeds it from.
struct Face {
manifest: PathBuf,
entry: ManifestEntry,
path: PathBuf,
index: u32,
@@ -281,7 +282,12 @@ impl Embed {
let selected = match &dir {
None => Err(Error::NotSet),
Some(dir) => self.select(dir, required, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
Some(dir) => self
.select(dir, required, cargo)
// A required (release) build reads every file: a copy that keeps the size and the
// modification time would get past the cache.
.and_then(|faces| check_hashes(dir, faces, (!required).then_some(out.as_path()), required, cargo))
.and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
};
let mut selected = selected;
if let Ok(faces) = &mut selected {
@@ -578,6 +584,96 @@ impl Embed {
}
}
/// Each generated table has a cache file with this additional extension.
const HASH_CACHE: &str = "sha256.txt";
/// This check compares each face's file with the SHA-256 its manifest line gives. A mismatch in
/// a main font or a required build returns [`Error::HashMismatch`]. This check warns and omits
/// an optional tab font if validation fails. A line whose hash field is not 64 hex digits is not checked. Faces of
/// one collection share a file, which is hashed once. With `out_file`, a file whose size and
/// modification time match its line in that table's [`HASH_CACHE`] cache is not read again.
fn check_hashes(dir: &Path, faces: Vec<Face>, out_file: Option<&Path>, required: bool, cargo: &mut Vec<String>) -> Result<Vec<Face>, Error> {
let cache_file = out_file.map(|out_file| out_file.with_added_extension(HASH_CACHE));
let old_text = cache_file.as_ref().and_then(|cache_file| read_text_bounded(cache_file, MAX_MANIFEST_BYTES).ok());
let old = old_text.as_deref().map(parse_hash_cache).unwrap_or_default();
let mut new: Vec<(String, u64, u128, String)> = Vec::new();
let mut checked = Vec::with_capacity(faces.len());
for face in faces {
let optional = !required && face.manifest == dir.join("fonts/latin-manifest.txt");
let expected = &face.entry.sha256;
if !crate::sha256::is_hex_digest(expected) {
checked.push(face);
continue;
}
let key = face.path.to_str().map(str::to_owned);
let stamp = file_stamp(&face.path);
let known = key.as_ref().and_then(|key| {
new.iter()
.chain(&old)
.find(|(path, size, modified, _)| path == key && stamp == Some((*size, *modified)))
.map(|(.., sha256)| sha256.clone())
});
let actual = match known {
Some(sha256) => sha256,
None => match crate::sha256::file_hex(&face.path, MAX_FILE_BYTES) {
Ok(actual) => actual,
Err(source) => {
let error = Error::Read { path: face.path.clone(), source };
if optional {
cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {error}"));
continue;
}
return Err(error);
}
},
};
if let (Some(key), Some((size, modified))) = (key, stamp)
&& !new.iter().any(|(path, ..)| *path == key)
{
new.push((key, size, modified, actual.clone()));
}
if !actual.eq_ignore_ascii_case(expected) {
let error = Error::HashMismatch { manifest: face.manifest.clone(), file: face.entry.file.clone(), expected: expected.clone(), actual };
if optional {
cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {error}"));
continue;
}
return Err(error);
}
checked.push(face);
}
let text: String = new.iter().map(|(path, size, modified, sha256)| format!("{sha256}\t{size}\t{modified}\t{path}\n")).collect();
// The cache only saves time: a directory that can't hold it costs a rehash on the next run.
if let Some(cache_file) = cache_file
&& !new.is_empty()
&& old_text.as_deref() != Some(text.as_str())
{
let _ = std::fs::write(&cache_file, text);
}
Ok(checked)
}
/// The lines of a [`HASH_CACHE`] file: SHA-256, size, modification time in nanoseconds since the
/// epoch and path, separated by tabs. Lines that don't read are skipped.
fn parse_hash_cache(text: &str) -> Vec<(String, u64, u128, String)> {
text.lines()
.filter_map(|line| {
let mut fields = line.splitn(4, '\t');
let sha256 = fields.next().filter(|s| crate::sha256::is_hex_digest(s))?;
let size = fields.next()?.parse().ok()?;
let modified = fields.next()?.parse().ok()?;
Some((fields.next()?.to_owned(), size, modified, sha256.to_owned()))
})
.collect()
}
/// A file's size and modification time in nanoseconds since the epoch, when the system gives both.
fn file_stamp(path: &Path) -> Option<(u64, u128)> {
let metadata = std::fs::metadata(path).ok()?;
let modified = metadata.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?;
Some((metadata.len(), modified.as_nanos()))
}
/// Whether the interface faces need `c`: CJK and later blocks, except emoji and other pictographs
/// (the emoji faces draw them), variation selectors, tags and a byte order mark.
fn needs_glyph(c: char) -> bool {
@@ -861,6 +957,18 @@ pub enum Error {
/// The path.
path: PathBuf,
},
/// A font file's SHA-256 is not the one its manifest line gives: the file is damaged, or the
/// checkout's files and manifest are out of step.
HashMismatch {
/// The manifest.
manifest: PathBuf,
/// The font file, as the manifest line names it.
file: String,
/// The SHA-256 the manifest line gives.
expected: String,
/// The SHA-256 of the file on disk.
actual: String,
},
}
impl fmt::Display for Error {
@@ -892,6 +1000,9 @@ impl fmt::Display for Error {
write!(f, "{}: {file:?} is not a file inside the checkout", manifest.display())
}
Self::LineBreakInPath { path } => write!(f, "{path:?} has a line break: cargo could not be told to watch it"),
Self::HashMismatch { manifest, file, expected, actual } => {
write!(f, "{}: {file:?} has SHA-256 {actual}, but the manifest gives {expected}", manifest.display())
}
}
}
}
+2 -2
View File
@@ -8,7 +8,8 @@
//!
//! - **Unset or empty:** the table is empty and the app uses its own and system fonts.
//! - **Set:** every selected face in `fonts/manifest.txt` is embedded with `include_bytes!`.
//! - **Set, but not readable as a checkout:** a `cargo::warning` and an empty table.
//! - **Set, but not readable as a checkout:** a `cargo::warning` and an empty table. A selected
//! font file whose SHA-256 is not the one its manifest line gives counts as unreadable.
//! - **`CRAFT_FONTS_REQUIRED=1`** (release builds; any other value is ignored): a missing or
//! unreadable checkout, no selected face, or a requested script without a face is an [`Error`].
//!
@@ -56,7 +57,6 @@ mod cmap;
pub mod coverage;
mod embed;
mod manifest;
#[cfg(feature = "subset")]
mod sha256;
#[cfg(test)]
mod tests;
+1 -1
View File
@@ -33,7 +33,7 @@ pub struct ManifestEntry {
pub licence: String,
/// Licence text, relative to the checkout.
pub licence_file: String,
/// Hex SHA-256 of the font file.
/// Hex SHA-256 of the font file. [`Embed`](crate::Embed) checks each selected file against it.
pub sha256: String,
/// Where the file came from.
pub source: String,
+123 -30
View File
@@ -1,4 +1,8 @@
//! SHA-256 (FIPS 180-4) of a cut face, for its served file name and Subresource Integrity value.
//! SHA-256 (FIPS 180-4) of a font file, checked against its manifest line, and of a cut face, for
//! its served file name and Subresource Integrity value.
use std::io::{self, Read as _};
use std::path::Path;
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
@@ -9,38 +13,127 @@ const K: [u32; 64] = [
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
/// The lowercase hex SHA-256 of `data`, as craft-fonts' manifest writes it.
pub(crate) fn hex(data: &[u8]) -> String {
let mut h: [u32; 8] = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
let mut message = data.to_vec();
message.push(0x80);
while message.len() % 64 != 56 {
message.push(0);
}
message.extend_from_slice(&(u64::try_from(data.len()).unwrap_or(u64::MAX).wrapping_mul(8)).to_be_bytes());
for block in message.as_chunks::<64>().0 {
let mut w = [0u32; 64];
for (i, word) in block.as_chunks::<4>().0.iter().enumerate() {
w[i] = u32::from_be_bytes(*word);
/// A SHA-256 fed in pieces, so a font file is hashed as it is read rather than copied whole.
pub(crate) struct Sha256 {
h: [u32; 8],
/// Bytes of the next block not yet compressed: `block[..filled]`.
block: [u8; 64],
filled: usize,
len: u64,
}
impl Sha256 {
pub(crate) fn new() -> Self {
Self {
h: [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19],
block: [0; 64],
filled: 0,
len: 0,
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
}
pub(crate) fn update(&mut self, mut data: &[u8]) {
self.len = self.len.wrapping_add(u64::try_from(data.len()).unwrap_or(u64::MAX));
if self.filled > 0 {
let take = (64 - self.filled).min(data.len());
let (head, rest) = data.split_at(take);
if let Some(free) = self.block.get_mut(self.filled..self.filled + take) {
free.copy_from_slice(head);
}
self.filled += take;
data = rest;
if self.filled < 64 {
return;
}
compress(&mut self.h, &self.block);
self.filled = 0;
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
for (k, w) in K.iter().zip(w) {
let t1 = hh
.wrapping_add(e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25))
.wrapping_add((e & f) ^ (!e & g))
.wrapping_add(*k)
.wrapping_add(w);
let t2 = (a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22)).wrapping_add((a & b) ^ (a & c) ^ (b & c));
(hh, g, f, e, d, c, b, a) = (g, f, e, d.wrapping_add(t1), c, b, a, t1.wrapping_add(t2));
let (blocks, rest) = data.as_chunks::<64>();
for block in blocks {
compress(&mut self.h, block);
}
for (h, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
*h = h.wrapping_add(v);
if let Some(start) = self.block.get_mut(..rest.len()) {
start.copy_from_slice(rest);
}
self.filled = rest.len();
}
/// The lowercase hex digest.
pub(crate) fn finish(mut self) -> String {
let bits = self.len.wrapping_mul(8);
// A 0x80 byte and zeros up to 56 bytes into a block, then the length in bits.
let padding = if self.filled < 56 { 56 - self.filled } else { 120 - self.filled };
let mut tail = [0u8; 64];
tail[0] = 0x80;
self.update(tail.get(..padding).unwrap_or(&tail));
self.update(&bits.to_be_bytes());
self.h.iter().map(|v| format!("{v:08x}")).collect()
}
}
fn compress(h: &mut [u32; 8], block: &[u8; 64]) {
let mut w = [0u32; 64];
for (i, word) in block.as_chunks::<4>().0.iter().enumerate() {
w[i] = u32::from_be_bytes(*word);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = *h;
for (k, w) in K.iter().zip(w) {
let t1 = hh
.wrapping_add(e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25))
.wrapping_add((e & f) ^ (!e & g))
.wrapping_add(*k)
.wrapping_add(w);
let t2 = (a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22)).wrapping_add((a & b) ^ (a & c) ^ (b & c));
(hh, g, f, e, d, c, b, a) = (g, f, e, d.wrapping_add(t1), c, b, a, t1.wrapping_add(t2));
}
for (h, v) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
*h = h.wrapping_add(v);
}
}
/// The lowercase hex SHA-256 of `data`, as craft-fonts' manifest writes it.
#[cfg(any(feature = "subset", test))]
pub(crate) fn hex(data: &[u8]) -> String {
let mut sha = Sha256::new();
sha.update(data);
sha.finish()
}
/// The lowercase hex SHA-256 of the regular file `path`, read in pieces; an error when it holds
/// more than `limit` bytes.
pub(crate) fn file_hex(path: &Path, limit: u64) -> io::Result<String> {
// Opening a FIFO with no writer blocks, so refuse anything that isn't a file before opening.
if !std::fs::metadata(path)?.is_file() {
return Err(io::Error::other("not a regular file"));
}
let file = std::fs::File::open(path)?;
if !file.metadata()?.is_file() {
return Err(io::Error::other("not a regular file"));
}
let mut file = file.take(limit.saturating_add(1));
let mut sha = Sha256::new();
let mut buffer = vec![0; 1 << 16];
loop {
let read = match file.read(&mut buffer) {
Ok(0) => break,
Ok(read) => read,
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
sha.update(buffer.get(..read).unwrap_or(&buffer));
}
if sha.len > limit {
return Err(io::Error::other(format!("larger than {limit} bytes")));
}
h.iter().map(|v| format!("{v:08x}")).collect()
Ok(sha.finish())
}
/// Whether `value` is a SHA-256 written as 64 hex digits.
pub(crate) fn is_hex_digest(value: &str) -> bool {
value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit())
}
+182
View File
@@ -369,6 +369,152 @@ fn an_oversized_manifest_and_a_directory_face_are_errors() {
assert!(r.result.is_ok() && warnings(&r).iter().any(|w| w.contains("larger than")), "{:?}", r.cargo);
}
#[test]
fn sha256_matches_the_standard_vectors_in_any_pieces() {
use crate::sha256::{Sha256, file_hex, hex};
assert_eq!(hex(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
assert_eq!(hex(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
let two_blocks = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
assert_eq!(hex(two_blocks), "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
let million = vec![b'a'; 1_000_000];
assert_eq!(hex(&million), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0");
// Pieces that start and end inside a block give the digest of the whole.
for piece in [1, 7, 55, 56, 63, 64, 65, 1000] {
let mut sha = Sha256::new();
for chunk in million.chunks(piece) {
sha.update(chunk);
}
assert_eq!(sha.finish(), hex(&million), "{piece}-byte pieces");
}
let scratch = Scratch::new("sha256-file");
let file = scratch.0.join("f");
for len in [0, 55, 56, 64, 65_537] {
let data: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
std::fs::write(&file, &data).unwrap();
assert_eq!(file_hex(&file, 65_537).unwrap(), hex(&data), "{len} bytes");
}
assert!(file_hex(&file, 65_536).unwrap_err().to_string().contains("larger than 65536 bytes"));
assert!(file_hex(&scratch.0, 10).is_err(), "a directory");
}
/// A checkout in `scratch` whose one face, `fonts/a.ttf`, holds `font` and whose manifest line
/// gives `sha256`.
fn hashed_checkout(scratch: &Scratch, font: &[u8], sha256: &str) -> PathBuf {
let dir = scratch.0.join("craft-fonts");
std::fs::create_dir_all(dir.join("fonts")).unwrap();
std::fs::write(dir.join("fonts/a.ttf"), font).unwrap();
std::fs::write(dir.join("fonts/OFL.txt"), b"licence").unwrap();
std::fs::write(dir.join("fonts/manifest.txt"), format!("Sans | Regular | fonts/a.ttf | Latn | OFL-1.1 | fonts/OFL.txt | {sha256} | src\n"))
.unwrap();
dir
}
#[test]
fn a_font_file_that_differs_from_its_manifest_hash_is_not_embedded() {
use crate::sha256::hex;
let scratch = Scratch::new("hash-mismatch");
let font = b"font bytes";
let dir = hashed_checkout(&scratch, font, &hex(font).to_ascii_uppercase());
assert_eq!(run(Embed::new(), Some(&dir), Some("1")).result.unwrap(), ["Sans Regular"]);
let dir = hashed_checkout(&scratch, font, &hex(b"other bytes"));
let r = run(Embed::new(), Some(&dir), Some("1"));
match &r.result {
Err(Error::HashMismatch { file, expected, actual, .. }) => {
assert_eq!((file.as_str(), expected.as_str(), actual.as_str()), ("fonts/a.ttf", hex(b"other bytes").as_str(), hex(font).as_str()));
}
other => panic!("{other:?}"),
}
assert_eq!(r.table.trim(), "&[]");
let err = r.result.unwrap_err().to_string();
assert!(err.contains("fonts/a.ttf") && err.contains(&hex(font)), "{err}");
// Not required: a warning and an empty table, as for a missing font file.
let r = run(Embed::new(), Some(&dir), None);
assert!(r.result.as_ref().unwrap().is_empty());
assert_eq!(r.table.trim(), "&[]");
assert!(warnings(&r).iter().any(|w| w.contains("building without craft-fonts") && w.contains("SHA-256")), "{:?}", r.cargo);
// Served faces are checked too: the manifest's hash becomes their integrity value.
let served = scratch.0.join("served");
assert!(matches!(run(Embed::new().serve(&served, "fonts/"), Some(&dir), Some("1")).result, Err(Error::HashMismatch { .. })));
assert!(!served.join("a.ttf").exists());
}
/// A rerun of a build that is not required takes a file's hash from the cache beside the table
/// while its size and modification time are unchanged, and hashes it again once they change. A
/// required build hashes every file.
#[test]
fn the_hash_cache_is_used_only_while_the_file_is_unchanged_and_not_when_required() {
use crate::sha256::hex;
let scratch = Scratch::new("hash-cache");
let font = b"font bytes";
let dir = hashed_checkout(&scratch, font, &hex(font));
let out = scratch.0.join("out");
std::fs::create_dir_all(&out).unwrap();
// The embedded faces, and the hash a mismatch warning gives as the file's.
let run_in = |required: Option<&str>| {
let env = Env { dir: Some(dir.clone().into()), required: required.map(OsString::from), out_dir: Some(out.clone().into()) };
let mut cargo = Vec::new();
let faces = Embed::new().run(&env, Path::new("craft_fonts.rs"), &mut cargo).map(|faces| faces.len()).ok();
let warned = cargo.iter().find_map(|line| Some(line.split_once("has SHA-256 ")?.1.get(..64)?.to_owned()));
(faces, warned)
};
assert_eq!(run_in(None), (Some(1), None));
let cache = out.join("craft_fonts.rs.sha256.txt");
let text = std::fs::read_to_string(&cache).unwrap();
assert!(text.starts_with(&format!("{}\t10\t", hex(font))), "{text}");
// A cached hash is trusted while the stamp matches: a wrong one shows in the warning.
let wrong = hex(b"cached");
std::fs::write(&cache, text.replacen(&hex(font), &wrong, 1)).unwrap();
assert_eq!(run_in(None), (Some(0), Some(wrong)));
// A required build reads the file instead.
assert_eq!(run_in(Some("1")), (Some(1), None));
// A changed file is hashed again, whatever the cache holds.
std::fs::write(dir.join("fonts/a.ttf"), b"other font bytes").unwrap();
assert_eq!(run_in(None), (Some(0), Some(hex(b"other font bytes"))));
// An unreadable cache costs a rehash, not a failure.
std::fs::write(dir.join("fonts/a.ttf"), font).unwrap();
std::fs::write(&cache, "not a cache line\n").unwrap();
assert_eq!(run_in(None), (Some(1), None));
}
#[test]
fn separate_generated_tables_keep_their_hash_cache() {
use crate::sha256::hex;
let scratch = Scratch::new("hash-cache-tables");
let font = b"first font bytes";
let dir = hashed_checkout(&scratch, font, &hex(font));
std::fs::write(dir.join("fonts/b.ttf"), b"second font bytes").unwrap();
let manifest = format!(
"Sans | Regular | fonts/a.ttf | Latn | OFL-1.1 | fonts/OFL.txt | {} | src\nMono | Regular | fonts/b.ttf | Latn | OFL-1.1 | fonts/OFL.txt | {} | src\n",
hex(font),
hex(b"second font bytes")
);
std::fs::write(dir.join("fonts/manifest.txt"), manifest).unwrap();
let out = scratch.0.join("out");
std::fs::create_dir_all(&out).unwrap();
let run_in = |family: &str, table: &str| {
let env = Env { dir: Some(dir.clone().into()), required: None, out_dir: Some(out.clone().into()) };
let mut cargo = Vec::new();
let faces = Embed::documents(&[family]).run(&env, Path::new(table), &mut cargo).unwrap();
(faces.len(), cargo)
};
assert_eq!(run_in("Sans", "faces.rs").0, 1);
let cache = std::fs::read_dir(&out)
.unwrap()
.map(|entry| entry.unwrap().path())
.find(|path| std::fs::read_to_string(path).is_ok_and(|text| text.starts_with(&format!("{}\t", hex(font)))))
.unwrap();
let cached = std::fs::read_to_string(&cache).unwrap();
let wrong = hex(b"cached first font");
std::fs::write(&cache, cached.replacen(&hex(font), &wrong, 1)).unwrap();
assert_eq!(run_in("Mono", "faces.inc").0, 1);
let (faces, cargo) = run_in("Sans", "faces.rs");
assert_eq!(faces, 0, "the first table's cached hash was discarded");
assert!(cargo.iter().any(|line| line.contains(&wrong)), "{cargo:?}");
}
/// `Embed::tab_face` adds only the Noto Sans Condensed SemiBold row of `fonts/latin-manifest.txt`, with the `tab` role.
/// A checkout without that manifest or row keeps its other faces, required or not; a broken manifest or row is an
/// error only when required. The face counts for none of the scripts a required build asks for and covers none of the
@@ -440,3 +586,39 @@ fn the_tab_face_comes_from_the_latin_manifest_with_the_tab_role() {
let r = run(Embed::new().tab_face(), Some(&dir), None);
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo);
}
fn tab_hash_checkout(scratch: &Scratch) -> PathBuf {
let dir = checkout(scratch, &[("Noto Sans Arabic", "Arab", "", tiny_font(&[(0x627, 0x627, None)], &[]))]);
std::fs::write(dir.join("fonts/OFL.txt"), b"licence").unwrap();
std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap();
std::fs::write(
dir.join("fonts/latin-manifest.txt"),
format!(
"Noto Sans | Condensed SemiBold | fonts/condensed.ttf | Latn | OFL-1.1 | fonts/OFL.txt | {} | src\n",
crate::sha256::hex(b"other font bytes")
),
)
.unwrap();
dir
}
#[test]
fn an_optional_tab_hash_mismatch_keeps_main_faces() {
let scratch = Scratch::new("optional-tab-hash");
let dir = tab_hash_checkout(&scratch);
let r = run(Embed::new().tab_face(), Some(&dir), None);
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"], "valid main faces remain available");
assert!(!r.table.contains("Condensed SemiBold"));
assert!(warnings(&r).iter().any(|warning| warning.contains("not embedding the tab-title face") && warning.contains("SHA-256")), "{:?}", r.cargo);
}
#[test]
fn a_required_tab_hash_mismatch_names_the_latin_manifest() {
let scratch = Scratch::new("required-tab-hash");
let dir = tab_hash_checkout(&scratch);
let r = run(Embed::new().tab_face(), Some(&dir), Some("1"));
match r.result {
Err(Error::HashMismatch { manifest, .. }) => assert_eq!(manifest, dir.join("fonts/latin-manifest.txt")),
other => panic!("{other:?}"),
}
}
+5
View File
@@ -67,6 +67,11 @@ The app keeps its `tl!` macro, its language setting (`"auto"` → `I18N.system_l
returns the bad locales, and each locale's rows are parsed (and its bad rows logged with
`log::warn!`) on the first lookup that reaches it, including as a fallback. `I18n::check_all()`
parses every locale and returns all problems (`<locale>/<common|app>: line N: …`), for a test.
- **Reading rows:** `catalog::parse(text, forms)` returns a catalog's rows (`catalog::Entry`, with
the columns unescaped) and its problems as `line N: …`, and `catalog::parse_row` checks one row;
both apply the checks the lookups apply. `plural_forms(locale)` gives `forms`.
`catalog::escape` writes a column's `\`, line breaks and tabs as `\\`, `\n` and `\t`, and
`catalog::unescape` reads them back.
- **Plurals:** forms are listed in CLDR order (zero, one, two, few, many, other) for the categories
whole numbers 0 to 1000 reach, from ICU4X's CLDR rules; `plural_form_counts` holds the counts
craft-i18n's checker expects. `trn_decimal` picks the form from the digits shown (ICU4X plural
+36 -5
View File
@@ -1,15 +1,25 @@
//! Reading one catalog. The rules are craft-i18n's `docs/catalog-format.md`; craft-i18n's CI
//! applies them strictly, and here a row that breaks one is skipped and reported, so an app built
//! against a newer catalog still runs, with that string in English.
//!
//! [`I18n`](crate::I18n) reads the embedded catalogs with these functions. An app's build script
//! or test that reads, merges or writes catalog rows can use them to read rows exactly as the
//! lookups do: [`parse`] for a catalog, [`parse_row`] for one line, and [`escape`] and [`unescape`]
//! for the columns. [`plural_forms`](crate::plural_forms) gives the `forms` argument for a locale.
use std::collections::HashSet;
use crate::message::Template;
/// A row that passed, with its columns unescaped.
pub(crate) struct Entry {
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Entry {
/// The context column: empty, a context such as `menu`, or `@plural`, `@id`, `@msg` or
/// `@msgplural`.
pub context: String,
/// The English source text; for `@plural` and `@msgplural`, its two forms joined by `|`.
pub source: String,
/// The translation; for `@plural` and `@msgplural`, its forms joined by `|`.
pub translation: String,
}
@@ -17,8 +27,9 @@ pub(crate) struct Entry {
const RESERVED: &[&str] = &["@plural", "@id", "@msg", "@msgplural"];
/// The rows of a catalog whose locale has `forms` plural forms, and one problem (`line N: …`) per
/// row skipped. Of a row defined twice, the first is kept, as in craft-i18n's checker.
pub(crate) fn parse(text: &str, forms: usize) -> (Vec<Entry>, Vec<String>) {
/// row skipped. Of a row defined twice, the first is kept, as in craft-i18n's checker. A leading
/// byte order mark, `\r` line ends, empty lines and `#` comment lines are skipped.
pub fn parse(text: &str, forms: usize) -> (Vec<Entry>, Vec<String>) {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let mut rows = Vec::new();
let mut problems = Vec::new();
@@ -39,7 +50,9 @@ pub(crate) fn parse(text: &str, forms: usize) -> (Vec<Entry>, Vec<String>) {
(rows, problems)
}
pub(crate) fn parse_row(text: &str, forms: usize) -> Result<Entry, String> {
/// One row, `context⇥source⇥translation` without its line end, checked as [`parse`] checks it;
/// the error is the problem `parse` reports after `line N: `.
pub fn parse_row(text: &str, forms: usize) -> Result<Entry, String> {
let columns: Vec<&str> = text.split('\t').collect();
let [context, source, translation] = columns.as_slice() else {
return Err(format!("{} columns; expected 3", columns.len()));
@@ -100,7 +113,25 @@ fn check_plural(source: &str, translation: &str, forms: usize) -> Result<(), Str
Ok(())
}
fn unescape(text: &str) -> Result<String, String> {
/// A column as a catalog writes it: `\` as `\\`, a line break as `\n` and a tab as `\t`. Other
/// characters are kept, so a column with another control character still gives a row that
/// [`parse_row`] rejects.
pub fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\t' => out.push_str("\\t"),
c => out.push(c),
}
}
out
}
/// A column as a catalog writes it, read back: `\n`, `\t` and `\\` are the only escapes, and any
/// other backslash is an error.
pub fn unescape(text: &str) -> Result<String, String> {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars();
while let Some(c) = chars.next() {
+9 -1
View File
@@ -12,7 +12,7 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod age;
mod catalog;
pub mod catalog;
#[cfg(feature = "collate")]
mod collate;
mod date;
@@ -688,6 +688,14 @@ fn fill(template: &str, args: &[(&str, &str)], isolated: bool, escapes: bool) ->
out
}
/// The forms an `@plural` row of `locale`'s catalog lists, the `forms` of [`catalog::parse`]: one
/// per category of `locale`'s CLDR plural rules that whole numbers 0 to 1000 reach (2 for `de`, 3
/// for `ru`), or 1 for a language CLDR has no plural rules for. [`I18n`] checks rows with the same
/// count.
pub fn plural_forms(locale: &str) -> usize {
plural_rules(&locale.to_ascii_lowercase()).map_or(1, |(_, c)| c.len())
}
#[cfg(test)]
mod message_tests;
#[cfg(test)]
+70
View File
@@ -0,0 +1,70 @@
//! Reading catalog rows from outside the crate, as an app's build script or test does.
use craft_i18n::catalog::{Entry, escape, parse, parse_row, unescape};
use craft_i18n::plural_forms;
fn entry(context: &str, source: &str, translation: &str) -> Entry {
Entry { context: context.into(), source: source.into(), translation: translation.into() }
}
#[test]
fn parse_reads_rows_as_the_lookups_do() {
let text =
"\u{feff}# comment\r\n\r\n\tOpen…\tÖffnen…\r\nmenu\tLine\\nbreak\tZeilen\\numbruch\n@plural\t{n} file|{n} files\t{n} Datei|{n} Dateien\n";
let (rows, problems) = parse(text, plural_forms("de"));
assert_eq!(problems, Vec::<String>::new());
assert_eq!(
rows,
[
entry("", "Open…", "Öffnen…"),
entry("menu", "Line\nbreak", "Zeilen\numbruch"),
entry("@plural", "{n} file|{n} files", "{n} Datei|{n} Dateien"),
]
);
}
#[test]
fn parse_reports_bad_and_repeated_rows_by_line() {
let text = "\tOpen\tÖffnen\n\tSave\n\tOpen\tAufmachen\n\tBad\\q\tSchlecht\n";
let (rows, problems) = parse(text, 2);
assert_eq!(rows, [entry("", "Open", "Öffnen")]);
assert_eq!(
problems,
["line 2: 2 columns; expected 3", "line 3: defined twice (same context and source text); the first is kept", "line 4: unknown escape \\q"]
);
}
#[test]
fn parse_row_checks_one_row() {
assert_eq!(parse_row("@id\tlanguage.name\tDeutsch", 2), Ok(entry("@id", "language.name", "Deutsch")));
assert_eq!(parse_row("\t{n} left\t{m} übrig", 2), Err("placeholders differ from the source text".into()));
assert_eq!(parse_row("@plural\t{n} file|{n} files\t{n} файл|{n} файла", plural_forms("ru")), Err("expected 3 nonempty plural forms".into()));
assert_eq!(
parse_row("@msgplural\t{n} file|{n} files\t{n} Datei|{n} Dateien", plural_forms("de")),
Ok(entry("@msgplural", "{n} file|{n} files", "{n} Datei|{n} Dateien"))
);
assert_eq!(parse_row("@msgplural\t{n}|{n}\t{n}|{n}", plural_forms("de")), Err("unmatchable message template".into()));
}
#[test]
fn escape_round_trips_through_unescape_and_parse_row() {
for text in ["plain", "a\\b", "two\nlines", "tab\there", "\\n is not a line break", "trailing \\"] {
let escaped = escape(text);
assert!(!escaped.contains(['\n', '\t']), "{escaped:?}");
assert_eq!(unescape(&escaped).as_deref(), Ok(text));
let row = parse_row(&format!("\t{escaped}\t{escaped}"), 2).map(|e| e.translation);
assert_eq!(row.as_deref(), Ok(text));
}
assert_eq!(escape("a\\b\nc\td"), "a\\\\b\\nc\\td");
assert_eq!(unescape("trailing \\"), Err("trailing backslash".into()));
}
#[test]
fn plural_forms_follow_the_cldr_rules() {
assert_eq!(plural_forms("de"), 2);
assert_eq!(plural_forms("pt-BR"), 2);
assert_eq!(plural_forms("ru"), 3);
assert_eq!(plural_forms("ar"), 6);
assert_eq!(plural_forms("ja"), 1);
assert_eq!(plural_forms("tlh"), 1);
}
+14
View File
@@ -64,6 +64,20 @@ impl Mods {
Mods { cmd: mods.ctrl || mods.command, ctrl: false, alt: mods.alt, shift: mods.shift }
}
}
/// The modifiers an egui key event carries for these keys on `platform`, for typing a chord
/// into egui in tests and remote control. On macOS cmd sets `mac_cmd` and `command`; elsewhere
/// cmd and ctrl both set `ctrl` and `command`, as egui-winit reports the Ctrl key.
/// [`Mods::from_egui`] reads the result back as these modifiers, with ctrl folded into cmd off
/// macOS.
pub fn to_egui(self, platform: Platform) -> Modifiers {
if platform.is_mac() {
Modifiers { alt: self.alt, ctrl: self.ctrl, shift: self.shift, mac_cmd: self.cmd, command: self.cmd }
} else {
let ctrl = self.cmd || self.ctrl;
Modifiers { alt: self.alt, ctrl, shift: self.shift, mac_cmd: false, command: ctrl }
}
}
}
impl Chord {
+53 -21
View File
@@ -102,6 +102,13 @@ pub enum AssignError {
UnknownScope(Scope),
/// The change needs a new [`Overrides`] entry and it already holds [`MAX_COMMANDS`].
Full,
/// A binding cannot be written and read back in the overrides format.
Unstorable {
/// The command whose bindings cannot be saved.
command: CommandRef,
/// The shortcut that cannot be saved.
trigger: Trigger,
},
/// A hold is a chord that types a character, alone or with Shift: never Space, Backtick, Cmd, Ctrl or Alt.
NotHoldable(Trigger),
}
@@ -115,6 +122,7 @@ impl fmt::Display for AssignError {
AssignError::Taken(h) => write!(f, "in use by {} other command(s)", h.len()),
AssignError::UnknownScope(s) => write!(f, "unknown scope {s}"),
AssignError::Full => write!(f, "more than {MAX_COMMANDS} changed commands"),
AssignError::Unstorable { command, trigger } => write!(f, "{trigger} for {} cannot be saved in its current scope", command.key()),
AssignError::NotHoldable(t) => write!(f, "{t} cannot be held"),
}
}
@@ -605,11 +613,21 @@ impl Keymap {
/// not have it, or when the change needs a new [`Overrides`] entry and the overrides are full
/// ([`AssignError::Full`]); nothing changes then.
pub fn remove(&mut self, command: &CommandRef, binding: &Binding) -> bool {
let Some(i) = self.find(command) else { return false };
self.try_remove(command, binding).unwrap_or(false)
}
/// Removes one binding and reports why an edit could not be saved. `Ok(false)` means the command did not have
/// that binding.
pub fn try_remove(&mut self, command: &CommandRef, binding: &Binding) -> Result<bool, AssignError> {
let i = self.find(command).ok_or(AssignError::UnknownCommand)?;
let gone = self.bound(i, binding);
let before = self.current[i].len();
let list: Vec<Bound> = self.current[i].iter().filter(|b| !self.same(b, &gone)).cloned().collect();
list.len() != before && self.commit(vec![(i, list)]).is_ok()
if list.len() == before {
return Ok(false);
}
self.commit(vec![(i, list)])?;
Ok(true)
}
/// Leaves a command without shortcuts, in every scope. `false` for an unknown command, or when
@@ -926,38 +944,52 @@ impl Keymap {
Ok(done)
}
/// Stores several commands' bindings, or none of them when the overrides lack room for the
/// new entries.
/// Prepares all entries before replacing live or stored bindings, including commands whose bindings were taken.
fn commit(&mut self, writes: Vec<(usize, Vec<Bound>)>) -> Result<(), AssignError> {
let needed = writes.iter().filter(|(i, list)| self.stored[*i].is_none() && !self.is_default(*i, list)).count();
let mut prepared = Vec::with_capacity(writes.len());
for (i, list) in writes {
let texts = self.store_texts(i, &list)?;
prepared.push((i, list, texts));
}
let needed = prepared.iter().filter(|(i, _, texts)| self.stored[*i].is_none() && texts.is_some()).count();
if self.overrides.len() + needed > MAX_COMMANDS {
return Err(AssignError::Full);
}
for (i, list) in writes {
self.store(i, list);
for (i, list, texts) in prepared {
self.remove_entries(i);
if let Some(texts) = texts {
self.overrides.insert(self.keys[i].clone(), texts);
self.stored[i] = Some(self.keys[i].clone());
}
self.set_current(i, list);
}
Ok(())
}
/// Writes a command's bindings to the overrides, dropping the entry when they equal the
/// Prepares a command's overrides, dropping the entry when its bindings equal the
/// defaults. Texts of the old entry this build cannot use stay in it, after the bindings and up
/// to [`MAX_BINDINGS`], unless the command is left without bindings: an entry of only such
/// texts loads as the defaults. Callers check for room first ([`Keymap::commit`]); texts always
/// fit, since a scope name, `": "` and the longest double press stay under
/// [`MAX_BINDING_TEXT`].
fn store(&mut self, i: usize, list: Vec<Bound>) {
/// to [`MAX_BINDINGS`], unless the command is left without bindings. An entry of only such texts loads as the defaults.
fn store_texts(&self, i: usize, list: &[Bound]) -> Result<Option<Vec<String>>, AssignError> {
let mut kept = if list.is_empty() { Vec::new() } else { self.unusable_texts(i) };
kept.truncate(MAX_BINDINGS.saturating_sub(list.len()));
self.remove_entries(i);
if !kept.is_empty() || !self.is_default(i, &list) {
let home = &self.catalog[i].scope;
let mut texts: Vec<String> = list.iter().map(|b| self.public(i, b).text(home)).collect();
texts.extend(kept);
if self.overrides.insert(self.keys[i].clone(), texts) {
self.stored[i] = Some(self.keys[i].clone());
if kept.is_empty() && self.is_default(i, list) {
return Ok(None);
}
let saved = self.stored[i].as_deref().and_then(|key| self.overrides.get(key)).unwrap_or_default();
let mut texts = Vec::with_capacity(list.len() + kept.len());
for bound in list {
let binding = self.public(i, bound);
let text = binding.to_string();
if Binding::parse(&text).as_ref() == Ok(&binding) {
texts.push(text);
} else if let Some(existing) = saved.iter().find(|text| Binding::parse(text).as_ref() == Ok(&binding)) {
texts.push(existing.clone());
} else {
return Err(AssignError::Unstorable { command: self.catalog[i].command.clone(), trigger: binding.trigger });
}
}
self.set_current(i, list);
texts.extend(kept);
Ok(Some(texts))
}
/// Removes a command's overrides entries: the one it reads and hand-written variants of its
+37
View File
@@ -0,0 +1,37 @@
//! Integration tests of craft-keymap: the egui conversions.
use ::egui::Modifiers;
use craft_keymap::egui::matches;
use craft_keymap::{Chord, Mods, Platform};
fn chord(text: &str) -> Chord {
Chord::parse(text).unwrap_or_else(|e| panic!("{text}: {e}"))
}
#[test]
fn modifiers_convert_to_egui_and_back_on_every_platform() {
let all = (0..16u8).map(|b| Mods { cmd: b & 1 != 0, ctrl: b & 2 != 0, alt: b & 4 != 0, shift: b & 8 != 0 });
for mods in all {
assert_eq!(Mods::from_egui(&mods.to_egui(Platform::Mac), Platform::Mac), mods, "{mods:?} on Mac");
for platform in [Platform::Windows, Platform::Linux] {
let folded = Mods { cmd: mods.cmd || mods.ctrl, ctrl: false, ..mods };
assert_eq!(Mods::from_egui(&mods.to_egui(platform), platform), folded, "{mods:?} on {platform:?}");
}
}
// What egui-winit reports for the Command key on macOS and the Ctrl key elsewhere.
assert_eq!(Mods::CMD.to_egui(Platform::Mac), Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE });
assert_eq!(Mods::CTRL.to_egui(Platform::Mac), Modifiers { ctrl: true, ..Modifiers::NONE });
let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE };
assert_eq!(Mods::CMD.to_egui(Platform::Windows), ctrl);
assert_eq!(Mods::CTRL.to_egui(Platform::Linux), ctrl);
let alt_shift = Mods { alt: true, shift: true, ..Mods::NONE };
assert_eq!(alt_shift.to_egui(Platform::Windows), Modifiers { alt: true, shift: true, ..Modifiers::NONE });
// A press built from a chord matches that chord on its platform.
let presses = [("Cmd+Shift+Z", Platform::Mac), ("Ctrl+Alt+K", Platform::Mac), ("Cmd+S", Platform::Windows), ("Ctrl+S", Platform::Linux)];
for (text, platform) in presses {
let c = chord(text);
assert!(matches(&c, c.key.to_egui(), &c.mods.to_egui(platform), platform), "{text} on {platform:?}");
}
}
+55
View File
@@ -26,6 +26,61 @@ fn app(id: &str, keys: &[&str]) -> CommandDef {
keys.iter().fold(CommandDef::new(id, id, Scope::app()), |e, k| e.with_default(b(k)))
}
#[test]
fn a_replacement_that_is_too_long_to_store_leaves_both_commands_intact() {
let context = "Text".repeat(16);
let scope = scope(&context);
let command = cmd("text.save");
let other = cmd("text.export");
let trigger = Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap();
let held = Binding::new(trigger);
let catalog = || vec![app("text.save", &["Cmd+S"]), CommandDef::new("text.export", "Export Text", scope.clone()).with_default(held.clone())];
let mut km = Keymap::new(catalog(), Scopes::new().with_context(&context), Platform::Mac);
let original = Binding::in_scope(Trigger::parse("Cmd+K").unwrap(), scope.clone());
km.set_bindings(&command, vec![original.clone()], Policy::Keep).unwrap();
let saved = km.overrides().clone();
let replacement = Binding::in_scope(trigger, scope.clone());
assert!(matches!(km.set_bindings(&command, vec![replacement], Policy::Steal), Err(craft_keymap::AssignError::Unstorable { .. })));
assert_eq!(km.bindings(&command), std::slice::from_ref(&original));
assert_eq!(km.bindings(&other), std::slice::from_ref(&held));
assert_eq!(km.overrides(), &saved);
let mut reopened = Keymap::new(catalog(), Scopes::new().with_context(&context), Platform::Mac);
reopened.set_overrides(km.overrides().clone());
assert_eq!(reopened.bindings(&command), [original]);
}
#[test]
fn a_binding_that_would_reload_in_another_scope_is_refused() {
let command = cmd("text.save");
let mut km = Keymap::new(vec![app("text.save", &["Cmd+S"])], Scopes::new().with_context("Cmd+"), Platform::Mac);
let binding = Binding::in_scope(Trigger::parse("Cmd+:").unwrap(), scope("Cmd+"));
assert!(matches!(km.set_bindings(&command, vec![binding], Policy::Keep), Err(craft_keymap::AssignError::Unstorable { .. })));
assert_eq!(km.bindings(&command), [b("Cmd+S")]);
assert!(km.overrides().is_empty());
}
#[test]
fn editing_one_shortcut_keeps_a_saved_spelling_that_can_be_read_back() {
let command = cmd("text.save");
let catalog = || vec![app("text.save", &["Cmd+S"])];
let scopes = || Scopes::new().with_context("Cmd+");
let mut km = Keymap::new(catalog(), scopes(), Platform::Mac);
let scoped = Binding::in_scope(Trigger::parse("Cmd+:").unwrap(), scope("Cmd+"));
let stored = "Cmd+: Cmd + :";
let mut overrides = Overrides::new();
assert!(overrides.insert(command.key(), vec![stored.into(), "Cmd+S".into()]));
km.set_overrides(overrides);
assert!(km.bindings(&command).contains(&scoped));
assert!(km.remove(&command, &b("Cmd+S")));
assert_eq!(km.overrides().get(&command.key()).unwrap(), [stored]);
let mut reopened = Keymap::new(catalog(), scopes(), Platform::Mac);
reopened.set_overrides(km.overrides().clone());
assert_eq!(reopened.bindings(&command), [scoped]);
}
fn in_scope(id: &str, home: &str, keys: &[&str]) -> CommandDef {
keys.iter().fold(CommandDef::new(id, id, scope(home)), |e, k| e.with_default(b(k)))
}
+2
View File
@@ -2,6 +2,8 @@
mod chord;
mod editor;
#[cfg(feature = "egui")]
mod egui;
mod import;
mod keymap;
mod layout;
+9 -2
View File
@@ -116,8 +116,15 @@ mod tests {
fn deflated_entries_are_read_and_path_traversal_is_skipped() {
let mut writer = Writer::new();
writer.add("animations/main.json", br#"{"w":1,"h":1}"#, Compression::Deflated).unwrap();
writer.add("../outside.json", b"{}", Compression::Deflated).unwrap();
let bytes = writer.finish().unwrap();
writer.add("xx/outside.json", b"{}", Compression::Deflated).unwrap();
let mut bytes = writer.finish().unwrap();
let target = b"xx/outside.json";
let replacement = b"../outside.json";
for i in 0..bytes.len().saturating_sub(target.len()) {
if &bytes[i..i + target.len()] == target {
bytes[i..i + target.len()].copy_from_slice(replacement);
}
}
assert_eq!(read_entries(&bytes).unwrap(), [("animations/main.json".into(), br#"{"w":1,"h":1}"#.to_vec())]);
assert!(read_entries_with_limits(&bytes, Limits { max_entries: 10, max_total_bytes: 4 }).is_err());
}
+25 -5
View File
@@ -248,11 +248,31 @@ mod tests {
fn rejects_ambiguous_or_nonlocal_resource_members() {
for name in ["resources/../../x", "resources/a\\x", "/x", "maps/color.png", "resources/C:/x", "preview.png"] {
assert!(write(b"x", [(name, &b"x"[..])]).is_err());
let mut zip = Writer::new();
zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap();
zip.add(SOURCE_ENTRY, b"x", Compression::Deflated).unwrap();
zip.add(name, b"x", Compression::Stored).unwrap();
assert!(Material::open(&zip.finish().unwrap(), Limits::default()).is_err());
let placeholder = "x".repeat(name.len());
let bytes = {
let mut zip = Writer::new();
zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap();
zip.add(SOURCE_ENTRY, b"x", Compression::Deflated).unwrap();
match zip.add(name, b"x", Compression::Stored) {
Ok(()) => zip.finish().unwrap(),
Err(_) => {
let mut zip = Writer::new();
zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap();
zip.add(SOURCE_ENTRY, b"x", Compression::Deflated).unwrap();
zip.add(&placeholder, b"x", Compression::Stored).unwrap();
let mut b = zip.finish().unwrap();
let p = placeholder.as_bytes();
let n = name.as_bytes();
for i in 0..b.len().saturating_sub(p.len()) {
if &b[i..i + p.len()] == p {
b[i..i + p.len()].copy_from_slice(n);
}
}
b
}
}
};
assert!(Material::open(&bytes, Limits::default()).is_err());
}
assert!(write(b"x", [("resources/A", &b"a"[..]), ("resources/a", &b"b"[..])]).is_err());
}
+2
View File
@@ -476,6 +476,7 @@ impl<'a> ShortcutsDialog<'a> {
return Err(inactive());
}
state.assign_field(env);
state.edit_result()?;
}
serde_json::Value::Bool(false) => {}
_ => return Err(rejects()),
@@ -487,6 +488,7 @@ impl<'a> ShortcutsDialog<'a> {
return Err(rejects());
}
state.remove(env, &command, &wanted);
state.edit_result()?;
}
_ => return Err(FieldRefusal::Unknown.message(field)),
}
+3 -9
View File
@@ -12,7 +12,7 @@ use serde::Serialize;
use craft_keymap::{CommandDef, CommandKind, CommandRef, Keymap};
use super::state::{Review, Target};
use super::state::Review;
use super::view::area_key;
use super::{Area, DialogState, ShortcutsDialog};
@@ -241,18 +241,12 @@ impl DialogState {
selected: self.selected.clone(),
overrides: keymap.overrides().iter().filter_map(|(key, texts)| Some((command(key)?, texts.to_vec()))).collect(),
conflict: self.conflict.as_ref().map(|c| (c.binding.to_string(), c.holders.iter().map(|h| h.command.clone()).collect())),
recording: self.recording.as_ref().and_then(|r| match &r.target {
Target::Cell { command, .. } | Target::HoldCell { command, .. } | Target::Field { command } => Some(command.clone()),
Target::Search | Target::Code { .. } => None,
}),
recording: self.recording.as_ref().and_then(|r| r.target.command().cloned()),
set: self.set.clone(),
can_undo: self.can_undo(),
// The switch sets the setting and the keymap's holds in one step, so the keymap's flag is the setting's.
holds: self.holds_shown.then(|| keymap.holds()),
recording_hold: self.recording.as_ref().and_then(|r| match &r.target {
Target::HoldCell { command, .. } => Some(command.clone()),
_ => None,
}),
recording_hold: self.recording.as_ref().filter(|r| r.target.is_hold()).and_then(|r| r.target.command().cloned()),
review: self.review.as_ref().map(ReviewSnapshot::of),
pressed: self.field.as_ref().map(|f| f.binding.to_string()),
holders: self.field.as_ref().map(|f| f.holders.iter().map(|h| h.command.clone()).collect()).unwrap_or_default(),
+15 -4
View File
@@ -3,7 +3,7 @@
//!
//! One component serves both states. Idle, the field has the plain widget keys (Tab leaves, Enter and Space start
//! recording). Recording, its key use is `KeyUse::RECORDER` (every key is a chord; bare Tab stays a chord because
//! the field keeps Tab). The recording field takes key focus on every run it lacks it.
//! the field keeps Tab). A recording field can take key focus when its caller allows it.
use craft_behavior::{Metrics, Proposal, Sense};
use craft_keymap::{Chord, Key};
@@ -85,6 +85,7 @@ struct Recorder {
shown: Label,
chords: Vec<Chord>,
started: bool,
take_focus: bool,
}
impl Component for Recorder {
@@ -114,6 +115,9 @@ impl Component for Recorder {
fn update(&mut self, cx: &mut Cx<'_, Self>) {
if self.recording {
if !cx.response.has_focus() {
if !self.take_focus {
return;
}
focus::request(&cx.response.ctx, FocusTarget::Id(cx.response.id));
}
self.chords.extend(cx.intents().take_chords());
@@ -147,12 +151,13 @@ pub(crate) struct ChordRecorder {
recording: bool,
shown: Label,
salt: Option<&'static str>,
take_focus: bool,
}
impl ChordRecorder {
/// A recorder named `label` showing `shown`.
pub(crate) fn new(label: impl Into<Label>, recording: bool, shown: impl Into<Label>) -> Self {
ChordRecorder { label: label.into(), recording, shown: shown.into(), salt: None }
ChordRecorder { label: label.into(), recording, shown: shown.into(), salt: None, take_focus: true }
}
/// Salts the field's id.
@@ -162,9 +167,15 @@ impl ChordRecorder {
self
}
/// Whether a recording may take focus when the field does not have it.
pub(crate) fn take_focus(mut self, take_focus: bool) -> Self {
self.take_focus = take_focus;
self
}
fn component(self) -> (Recorder, Option<&'static str>) {
let ChordRecorder { label, recording, shown, salt } = self;
(Recorder { common: Common::new(), recording, shown, chords: Vec::new(), started: false }.label(label), salt)
let ChordRecorder { label, recording, shown, salt, take_focus } = self;
(Recorder { common: Common::new(), recording, shown, chords: Vec::new(), started: false, take_focus }.label(label), salt)
}
/// Shows the field.
+81 -12
View File
@@ -71,6 +71,8 @@ pub(crate) enum Target {
/// A row's hold cell: the chord recorded becomes a hold that replaces the hold `old`, or adds one when `None`.
/// Commits at once.
HoldCell { command: CommandRef, old: Option<Binding> },
/// An existing binding in the detail pane. Commits a replacement in the binding's scope.
Detail { command: CommandRef, old: Binding },
/// The detail pane's New Shortcut field: the chord waits for Assign.
Field { command: CommandRef },
/// Search by key: the chord's text becomes the query.
@@ -80,10 +82,27 @@ pub(crate) enum Target {
}
impl Target {
pub(crate) fn command(&self) -> Option<&CommandRef> {
match self {
Target::Cell { command, .. } | Target::HoldCell { command, .. } | Target::Detail { command, .. } | Target::Field { command } => {
Some(command)
}
Target::Search | Target::Code { .. } => None,
}
}
pub(crate) fn is_hold(&self) -> bool {
match self {
Target::HoldCell { .. } => true,
Target::Detail { old, .. } => old.trigger.is_hold(),
_ => false,
}
}
/// A single press waits for a second one ([`Options::double_press`]) only where a double press means something:
/// a hold or a code takes the chord alone.
fn takes_double(&self) -> bool {
!matches!(self, Target::HoldCell { .. } | Target::Code { .. })
!self.is_hold() && !matches!(self, Target::Code { .. })
}
}
@@ -510,7 +529,7 @@ impl DialogState {
self.conflict = None;
self.message = None;
self.recorder.reset();
if let Target::Cell { command, .. } | Target::HoldCell { command, .. } | Target::Field { command } = &target {
if let Some(command) = target.command() {
self.select_row(command);
}
self.recording = Some(Recording { target, waiting: None, started: false });
@@ -521,8 +540,25 @@ impl DialogState {
self.recorder.reset();
}
/// Commits a single press whose double-press window has ended.
/// Clears unavailable editing targets and settles timers outside the detail pane.
pub(crate) fn tick(&mut self, env: &mut Env, now: f64) {
if !env.options.editable {
self.conflict = None;
if self.recording.as_ref().is_some_and(|r| r.target.command().is_some()) {
self.stop_recording();
}
}
if self.recording.as_ref().is_some_and(|r| matches!(r.target, Target::Detail { .. })) {
if env.options.layout != Layout::Table {
self.stop_recording();
}
} else {
self.settle_recording(env, now);
}
}
/// Commits a single press whose double-press window has ended. The detail pane calls this after checking focus.
pub(crate) fn settle_recording(&mut self, env: &mut Env, now: f64) {
let expired = self.recording.as_ref().and_then(|r| r.waiting).filter(|(_, at)| now < *at || now - *at >= DOUBLE_PRESS);
if let Some((trigger, _)) = expired {
self.commit_recorded(env, trigger);
@@ -538,7 +574,9 @@ impl DialogState {
let target = rec.target.clone();
self.stop_recording();
match target {
Target::Cell { command, old: Some(old) } | Target::HoldCell { command, old: Some(old) } => self.remove(env, &command, &old),
Target::Cell { command, old: Some(old) } | Target::HoldCell { command, old: Some(old) } | Target::Detail { command, old } => {
self.remove(env, &command, &old);
}
Target::Field { .. } => self.field = None,
_ => {}
}
@@ -569,6 +607,12 @@ impl DialogState {
self.refuse(word!(env, press_a_key_without_modifiers));
}
}
Target::Detail { command, old } => {
if self.selected.as_ref() == Some(&command) && env.keymap.bindings(&command).contains(&old) {
let trigger = if old.trigger.is_hold() { Trigger::hold(trigger.chord) } else { trigger };
self.commit_cell(env, &command, Some(old), trigger);
}
}
}
}
@@ -659,11 +703,20 @@ impl DialogState {
let text = fill!(env, chord_is_used_by_label, ("chord", &chord), ("label", &env.holder_labels(&holders)));
self.conflict = Some(ConflictBar { command: command.clone(), old, binding, holders, text });
}
ConflictMode::Steal => self.apply_and_say(env, command, old, binding, Policy::Steal),
ConflictMode::Keep => self.apply_and_say(env, command, old, binding, Policy::Keep),
ConflictMode::Steal => {
self.apply_and_say(env, command, old, binding, Policy::Steal);
}
ConflictMode::Keep => {
self.apply_and_say(env, command, old, binding, Policy::Keep);
}
}
}
/// Reports the same refusal to an automation caller that the dialog shows to the user.
pub(crate) fn edit_result(&self) -> Result<(), String> {
self.message.as_ref().filter(|message| message.refused).map_or(Ok(()), |message| Err(message.text.clone()))
}
fn refuse(&mut self, text: String) {
self.message = Some(Message { text, refused: true, goto: None, undo: false, chord: None });
}
@@ -687,6 +740,10 @@ impl DialogState {
}
Err(e) => {
let text = assign_error(env, &e);
let chord = match &e {
AssignError::Unstorable { trigger, .. } => env.chord_text(trigger),
_ => chord,
};
self.refuse_chord(text, chord);
None
}
@@ -694,12 +751,12 @@ impl DialogState {
}
/// Applies with Steal or Keep and says what it did, with Go to Conflict (and Undo for Steal).
fn apply_and_say(&mut self, env: &mut Env, command: &CommandRef, old: Option<Binding>, binding: Binding, policy: Policy) {
fn apply_and_say(&mut self, env: &mut Env, command: &CommandRef, old: Option<Binding>, binding: Binding, policy: Policy) -> bool {
let chord = env.chord_text(&binding.trigger);
let Some(a) = self.apply(env, command, old, binding, policy) else { return };
let Some(a) = self.apply(env, command, old, binding, policy) else { return false };
let (holders, steal) = if policy == Policy::Steal { (&a.taken_from, true) } else { (&a.clashes, false) };
if holders.is_empty() {
return;
return true;
}
let label = env.holder_labels(holders);
let text = if steal {
@@ -709,6 +766,7 @@ impl DialogState {
};
let goto = holders.first().map(|h| h.command.clone());
self.message = Some(Message { text, refused: false, goto, undo: policy == Policy::Steal, chord: Some(chord) });
true
}
/// Take It.
@@ -722,8 +780,9 @@ impl DialogState {
pub(crate) fn take_it_and_go(&mut self, env: &mut Env) {
if let Some(c) = self.conflict.take() {
let first = c.holders.first().map(|h| h.command.clone());
self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal);
if let Some(holder) = first {
if self.apply_and_say(env, &c.command, c.old, c.binding, Policy::Steal)
&& let Some(holder) = first
{
self.go_to(env, &holder);
}
}
@@ -770,7 +829,14 @@ impl DialogState {
/// × on a chip, or Remove.
pub(crate) fn remove(&mut self, env: &mut Env, command: &CommandRef, binding: &Binding) {
self.edit(env, |s, km| s.remove(km, command, binding));
self.message = None;
let km = &mut *env.keymap;
let result = self.session.get_or_insert_with(|| EditSession::begin(km)).edit(km, |km| km.try_remove(command, binding));
match result {
Ok(true) => self.edited(env),
Ok(false) => {}
Err(error) => self.refuse(assign_error(env, &error)),
}
}
/// Remove in [`Layout::CommandLists`]: takes away the key picked among the selected command's keys.
@@ -1293,6 +1359,9 @@ fn assign_error(env: &Env, e: &AssignError) -> String {
AssignError::TooMany => fill!(env, a_command_can_have_at_most, ("n", &MAX_BINDINGS.to_string())),
AssignError::UnknownScope(s) => fill!(env, the_scope_scope_is_unknown, ("scope", s.as_str())),
AssignError::Full => word!(env, too_many_shortcuts_are_assigned),
AssignError::Unstorable { command, trigger } => {
fill!(env, shortcut_cannot_be_saved_in_its_scope, ("chord", &env.chord_text(trigger)), ("command", &env.label(command)))
}
AssignError::UnknownCommand => word!(env, this_command_is_unknown),
AssignError::Taken(holders) => fill!(env, also_used_by_label, ("label", &env.holder_labels(holders))),
AssignError::NotHoldable(t) => fill!(env, not_holdable, ("chord", &env.chord_text(t))),
+82 -26
View File
@@ -1,9 +1,10 @@
//! The detail pane: the selected command's name and place, its current shortcuts with Remove, the New Shortcut
//! The detail pane: the selected command's name and place, its current shortcuts with Replace and Remove, the New Shortcut
//! field (recording, or typed entry), Context, the holders of the new chord, and Assign, Use Default and Clear.
use craft_keymap::command::CommandRef;
use craft_keymap::keymap::Binding;
use craft_keymap::scope::Scope;
use craft_keymap::{Chord, Key};
use craft_ui::buttons::{Button, IconButton, Link};
use craft_ui::contract::{Bind, BodyCx, Entry, Props as _, Scroll, Show as _, ShowContainer as _, clicked};
use craft_ui::display::{Shade, Text};
@@ -16,7 +17,7 @@ use craft_ui::style::TypeRole;
use craft_ui::text::TextField;
use egui::Ui;
use crate::shortcuts::recorder::ChordRecorder;
use crate::shortcuts::recorder::{ChordRecorder, RecorderOutput};
use crate::shortcuts::state::{DialogState, Env, Target};
use crate::shortcuts::view::recording_text;
use crate::shortcuts::words::around_chord;
@@ -27,6 +28,11 @@ const PATH_SEPARATOR: &str = " \u{203a} ";
pub(super) fn show(ui: &mut Ui, _cx: &mut BodyCx<'_>, now: f64, env: &mut Env<'_>, state: &mut DialogState) {
Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| {
let selected = state.selected.clone().filter(|command| env.keymap.bindable(command).is_some());
if let Some(Target::Detail { command, old }) = state.recording.as_ref().map(|recording| &recording.target)
&& (selected.as_ref() != Some(command) || !env.keymap.bindings(command).contains(old))
{
state.stop_recording();
}
match selected {
Some(command) => of_command(ui, now, env, state, &command),
None => {
@@ -79,25 +85,71 @@ fn of_command(ui: &mut Ui, now: f64, env: &mut Env<'_>, state: &mut DialogState,
if bindings.is_empty() {
Text::new(words.none.clone()).shade(Shade::Muted).show(ui);
}
let command_key = command.key();
let mut remove = None;
for (n, binding) in bindings.iter().enumerate() {
for (index, binding) in bindings.iter().enumerate() {
let text = binding_text(env, binding, &home);
let shown = if defaults.contains(binding) { words.chord_default.fill(&[("chord", &text)]) } else { text.clone() };
let chord = env.text.trigger(&binding.trigger, env.keymap.platform());
Row::new().show(ui, |ui, _| {
Text::new(around_chord(env.text.rtl(), &shown, &chord)).show(ui);
if editable {
let target = Target::Detail { command: command.clone(), old: binding.clone() };
let recording = state.recording.as_ref().filter(|r| r.target == target);
let started = recording.is_some_and(|r| r.started);
let recording = recording.is_some();
let shown = around_chord(env.text.rtl(), &shown, &chord);
let row = Row::new()
.id_salt(("shortcut", &command_key, index))
.wrap(true)
.show(ui, |ui, _| {
Text::new(shown.clone()).show(ui);
if !editable {
return None;
}
let (out, replace) = if recording {
let prompt = recording_text(env, state);
(Some(ChordRecorder::new(prompt.clone(), true, prompt).id_salt("replace").take_focus(false).show(ui)), false)
} else {
let name = words.replace_chord_for_label.fill(&[("chord", &text), ("label", &label)]);
let icon = IconSpec::svg(craft_behavior::IconId::new("pencil"));
let button = IconButton::new(icon).id_salt("replace").label(name.clone()).tooltip(name).show(ui);
(None, clicked(&button))
};
let name = words.remove_chord_from_label.fill(&[("chord", &text), ("label", &label)]);
let button = IconButton::new(IconSpec::svg(craft_behavior::IconId::new("close")))
.id_salt(("remove", n))
.label(name.clone())
.tooltip(name)
.show(ui);
if clicked(&button) {
remove = Some(binding.clone());
let icon = IconSpec::svg(craft_behavior::IconId::new("close"));
let button = IconButton::new(icon).id_salt("remove").label(name.clone()).tooltip(name).show(ui);
Some((out, replace, clicked(&button)))
})
.inner
.flatten();
if let Some((out, replace, removed)) = row
&& !ui.is_sizing_pass()
&& !craft_ui::runtime::measure::active(ui.ctx())
{
if replace {
state.record(env, target);
// Switch key routing to the recorder before the next input frame.
craft_ui::runtime::frame::discard_pass(ui.ctx(), "shortcuts detail recorder activated");
} else if let Some(out) = out {
let response = &out.response;
let bounds = ui.ctx().layer_transform_to_global(response.layer_id).map_or(response.interact_rect, |map| map * response.interact_rect);
let pressed_elsewhere = craft_ui::runtime::pointer::frame(ui.ctx()).press.is_some_and(|press| !bounds.contains(press.origin));
if out.chords.contains(&Chord::plain(Key::Escape)) || pressed_elsewhere || (started && !out.response.has_focus()) {
state.stop_recording();
} else {
if !started {
// Replacing the button with a wider recorder can wrap to a different line in this scroll.
focus::request(ui.ctx(), FocusTarget::Id(response.id));
}
if out.response.has_focus() {
state.settle_recording(env, now);
receive_recorded_keys(env, state, now, out);
}
}
}
});
if removed {
remove = Some(binding.clone());
}
}
}
if let Some(binding) = remove {
state.remove(env, command, &binding);
@@ -172,7 +224,8 @@ pub(super) fn new_shortcut(ui: &mut Ui, now: f64, env: &mut Env<'_>, state: &mut
}
return;
}
let recording = matches!(state.recording.as_ref().map(|r| &r.target), Some(Target::Field { command: c }) if c == command);
let target = Target::Field { command: command.clone() };
let recording = state.recording.as_ref().is_some_and(|r| r.target == target);
let shown = if recording {
recording_text(env, state)
} else {
@@ -188,18 +241,10 @@ pub(super) fn new_shortcut(ui: &mut Ui, now: f64, env: &mut Env<'_>, state: &mut
})
.inner;
let Some((out, type_more)) = shown_row else { return };
if out.started && !recording {
state.record(env, Target::Field { command: command.clone() });
}
if recording {
if let Some(recording) = state.recording.as_mut() {
recording.started = true;
}
if !out.chords.is_empty() {
state.feed(env, &out.chords, now);
} else if out.response.lost_focus() {
state.stop_recording();
}
receive_recorded_keys(env, state, now, out);
} else if out.started {
state.record(env, target);
}
if type_more {
state.stop_recording();
@@ -209,6 +254,17 @@ pub(super) fn new_shortcut(ui: &mut Ui, now: f64, env: &mut Env<'_>, state: &mut
}
}
fn receive_recorded_keys(env: &mut Env<'_>, state: &mut DialogState, now: f64, out: RecorderOutput) {
if let Some(recording) = state.recording.as_mut() {
recording.started = true;
}
if !out.chords.is_empty() {
state.feed(env, &out.chords, now);
} else if out.response.lost_focus() {
state.stop_recording();
}
}
fn context(ui: &mut Ui, env: &Env<'_>, state: &mut DialogState, command: &CommandRef) {
let words = env.text.words();
let contexts = DialogState::contexts(env, command);
+2
View File
@@ -68,6 +68,7 @@ craft_ui::words! {
not_assigned: "keyboardShortcuts.notAssigned" = "Not assigned";
label_scope_both_work: template "keyboardShortcuts.labelScopeBothWork" = "{label} ({scope}, both work)";
add_a_shortcut_to_label: template "keyboardShortcuts.addAShortcutToLabel" = "Add a shortcut to {label}";
replace_chord_for_label: template "keyboardShortcuts.replaceChordForLabel" = "Replace {chord} for {label}";
remove_chord_from_label: template "keyboardShortcuts.removeChordFromLabel" = "Remove {chord} from {label}";
restore_the_default_for_label: template "keyboardShortcuts.restoreTheDefaultForLabel" = "Restore the default for {label}";
label_chord: template "keyboardShortcuts.labelChord" = "{label}: {chord}";
@@ -113,6 +114,7 @@ craft_ui::words! {
also_used_by_label: template "keyboardShortcuts.alsoUsedByLabel" = "Also used by {label}";
chord_is_reserved_by_the_system: template "keyboardShortcuts.chordIsReservedByTheSystem" = "{chord} is reserved by the system";
a_command_can_have_at_most: template "keyboardShortcuts.aCommandCanHaveAtMost" = "A command can have at most {n} shortcuts";
shortcut_cannot_be_saved_in_its_scope: template "keyboardShortcuts.shortcutCannotBeSavedInItsScope" = "{chord} for {command} cannot be saved in its current scope";
the_scope_scope_is_unknown: template "keyboardShortcuts.theScopeScopeIsUnknown" = "The scope {scope} is unknown";
too_many_shortcuts_are_assigned: "keyboardShortcuts.tooManyShortcutsAreAssigned" = "Too many shortcuts are assigned";
this_command_is_unknown: "keyboardShortcuts.thisCommandIsUnknown" = "This command is unknown";
+21
View File
@@ -83,3 +83,24 @@ fn toggling_holds_rebuilds_the_rows_and_the_keymap_view() {
rig.click("Hold Shortcuts");
assert!(rig.has("Save: Hold K"), "switched on again, the hold is back");
}
#[trial]
fn replacing_a_hold_in_the_detail_pane_records_another_hold() {
let command = CommandRef::from("file.save");
let mut km = fixture::keymap(Platform::Mac);
km.set_holds(true);
km.assign(&command, Binding::parse("Hold K").unwrap(), Policy::Keep).unwrap();
let mut options = fixture::options();
options.double_press = true;
let mut rig = Rig::with_holds(km, options, setting(true));
rig.shared.borrow_mut().state.select(&command);
rig.pass();
rig.click("Replace Hold K for Save");
{
let shared = rig.shared.borrow();
assert_eq!(shared.state.snapshot(&shared.km).unwrap().recording_hold, Some(command));
}
rig.press(Modifiers::NONE, Key::J);
assert_eq!(holds_of(&rig, "file.save"), ["Hold J"]);
}
+22 -2
View File
@@ -1,11 +1,12 @@
//! The Customize Keyboard layout: each change is applied at once and Escape closes without rolling back.
use craft_keymap::{Binding, CommandRef, Platform};
use craft_keymap::{Binding, CommandDef, CommandRef, Keymap, Platform, Scope, Scopes, Trigger};
use craft_menu::shortcuts::{Layout, Outcome};
use craft_ui::contract::Role;
use craft_ui::testing::trial;
use egui::{Key, Modifiers};
use super::fixture::Rig;
use super::fixture::{Rig, options};
/// Records `key` with the command modifier in the New Shortcut field.
fn record(rig: &mut Rig, key: Key) {
@@ -18,6 +19,25 @@ fn keys(rig: &Rig) -> Vec<Binding> {
rig.shared.borrow().km.bindings(&CommandRef::from("object.front")).to_vec()
}
#[trial]
fn remove_identifies_the_retained_shortcut_that_blocks_saving() {
let context = "Text".repeat(16);
let trigger = Trigger::parse("Cmd+Ctrl+Alt+Shift+IntlBackslash Cmd+Ctrl+Alt+Shift+IntlBackslash").unwrap();
let retained = Binding::in_scope(trigger, Scope::new(&context).unwrap());
let command =
CommandDef::new("text.save", "Save Text", Scope::app()).with_default(retained.clone()).with_default(Binding::parse("Cmd+S").unwrap());
let keymap = Keymap::new(vec![command], Scopes::new().with_context(&context), Platform::Mac);
let mut options = options();
options.layout = Layout::CommandLists;
let mut rig = Rig::new(keymap, options, None);
rig.click("Save Text");
rig.click("⌘S");
rig.click("Remove");
assert_eq!(rig.bindings("text.save"), [retained.to_string(), "Cmd+S".into()]);
assert!([Role::STATUS, Role::ALERT].into_iter().any(|role| !rig.names_with(role, "for Save Text cannot be saved").is_empty()));
}
/// Production applies each change at once and has no Cancel: an Escape that rolled back would silently lose them.
#[trial]
fn command_lists_assign_remove_and_close_apply_each_change_at_once() {
+208 -2
View File
@@ -1,10 +1,216 @@
//! Recording through the dialog: the recorder takes every key, the state decides what a chord means.
use craft_keymap::Platform;
use craft_keymap::{Binding, CommandRef, Platform, Policy};
use craft_menu::shortcuts::Layout;
use craft_ui::testing::trial;
use egui::{Key, Modifiers};
use super::fixture::Rig;
use super::fixture::{self, Rig};
/// At a compact opening size, replacing the last long shortcut through the detail pane preserves its scope
/// and keeps the other bindings.
#[trial]
fn the_detail_pane_can_replace_a_shortcut_that_does_not_fit_inline() {
let command = CommandRef::from("file.save");
let mut km = fixture::keymap(Platform::Windows);
let original = ["Ctrl+Alt+Shift+PageUp", "Ctrl+Alt+Shift+PageDown", "Text: Ctrl+Alt+Shift+End"];
let bindings: Vec<_> = original.into_iter().map(|text| Binding::parse(text).unwrap()).collect();
km.set_bindings(&command, bindings, Policy::Keep).unwrap();
let mut options = fixture::options();
options.size = Some(egui::vec2(640.0, 560.0));
let mut rig = Rig::new(km, options, None);
rig.shared.borrow_mut().state.select(&command);
rig.pass();
let replace = rig.find("Replace Ctrl+Alt+Shift+End (Text) for Save");
assert!(replace.rect.width() >= 16.0, "the replace control fits: {:?}", replace.rect);
rig.fixture.click(&replace);
rig.pass();
rig.press(Modifiers::NONE, Key::F11);
let expected = [original[0], original[1], "Text: F11"].map(|text| Binding::parse(text).unwrap().to_string());
assert_eq!(rig.bindings("file.save"), expected);
rig.click("Undo");
assert_eq!(rig.bindings("file.save"), original.map(|text| Binding::parse(text).unwrap().to_string()));
}
#[trial]
fn going_read_only_cancels_a_pending_detail_replacement() {
let command = CommandRef::from("file.save");
let mut rig = Rig::tuned(Platform::Windows, |options| options.double_press = true);
let original = rig.bindings("file.save");
rig.shared.borrow_mut().state.select(&command);
rig.pass();
rig.click("Replace Ctrl+S for Save");
rig.press(Modifiers::NONE, Key::F11);
{
let mut shared = rig.shared.borrow_mut();
assert_eq!(shared.state.snapshot(&shared.km).unwrap().recording, Some(command));
shared.options.editable = false;
}
rig.fixture.advance(1.0);
rig.pass();
assert_eq!(rig.bindings("file.save"), original);
let shared = rig.shared.borrow();
assert_eq!(shared.state.snapshot(&shared.km).unwrap().recording, None);
}
#[trial]
fn going_read_only_dismisses_a_pending_detail_conflict() {
let command = CommandRef::from("file.save");
let mut rig = Rig::mac();
let original = rig.bindings("file.save");
rig.shared.borrow_mut().state.select(&command);
rig.pass();
rig.click("Replace ⌘S for Save");
rig.press(Modifiers::COMMAND, Key::E);
{
let mut shared = rig.shared.borrow_mut();
assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_some());
shared.options.editable = false;
}
rig.pass();
assert_eq!(rig.bindings("file.save"), original);
let shared = rig.shared.borrow();
assert!(shared.state.snapshot(&shared.km).unwrap().conflict.is_none());
}
#[trial]
fn clicking_search_leaves_detail_recording() {
let mut rig = Rig::mac();
let original = rig.bindings("file.save");
rig.shared.borrow_mut().state.select(&CommandRef::from("file.save"));
rig.pass();
rig.click("Replace ⌘S for Save");
rig.click("Search:");
rig.fixture.type_key(Key::F, "f");
rig.pass();
assert_eq!(rig.bindings("file.save"), original);
let shared = rig.shared.borrow();
let snapshot = shared.state.snapshot(&shared.km).unwrap();
assert_eq!(snapshot.query, "f");
assert_eq!(snapshot.recording, None);
}
#[trial]
fn clicking_search_cancels_the_pending_detail_timeout() {
let mut rig = Rig::tuned(Platform::Windows, |options| options.double_press = true);
let original = rig.bindings("file.save");
rig.shared.borrow_mut().state.select(&CommandRef::from("file.save"));
rig.pass();
rig.click("Replace Ctrl+S for Save");
rig.press(Modifiers::NONE, Key::F11);
let search = rig.find("Search:");
let pos = search.center();
rig.fixture.advance(1.0).frame(vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
]);
rig.fixture.release(&search);
rig.pass();
assert_eq!(rig.bindings("file.save"), original);
let shared = rig.shared.borrow();
assert_eq!(shared.state.snapshot(&shared.km).unwrap().recording, None);
}
#[trial]
fn a_focused_detail_recording_commits_when_the_timeout_expires() {
let mut rig = Rig::tuned(Platform::Windows, |options| options.double_press = true);
rig.shared.borrow_mut().state.select(&CommandRef::from("file.save"));
rig.pass();
let original = rig.bindings("file.save");
rig.click("Replace Ctrl+S for Save");
rig.press(Modifiers::NONE, Key::F11);
assert_eq!(rig.bindings("file.save"), original);
rig.fixture.advance(1.0);
rig.pass();
assert_eq!(rig.bindings("file.save"), ["F11"]);
}
#[trial]
fn escape_cancels_detail_recording_on_the_timeout_frame() {
let mut rig = Rig::tuned(Platform::Windows, |options| options.double_press = true);
rig.shared.borrow_mut().state.select(&CommandRef::from("file.save"));
rig.pass();
let original = rig.bindings("file.save");
rig.click("Replace Ctrl+S for Save");
rig.press(Modifiers::NONE, Key::F11);
rig.fixture.advance(1.0);
rig.press(Modifiers::NONE, Key::Escape);
assert!(rig.is_open());
assert_eq!(rig.bindings("file.save"), original);
}
#[trial]
fn an_accessibility_action_can_start_an_unfocused_detail_recorder() {
use egui::accesskit::{Action, ActionRequest, NodeId, TreeId};
let mut rig = Rig::mac();
rig.shared.borrow_mut().state.select(&CommandRef::from("file.save"));
rig.pass();
rig.click("Search:");
let replace = rig.find("Replace ⌘S for Save");
rig.fixture.frame(vec![egui::Event::AccessKitActionRequest(ActionRequest {
action: Action::Click,
target_tree: TreeId::ROOT,
target_node: NodeId(replace.node.raw()),
data: None,
})]);
rig.press(Modifiers::NONE, Key::F11);
assert_eq!(rig.bindings("file.save"), ["F11"]);
}
#[trial]
fn clicking_search_as_recording_opens_leaves_focus_in_search() {
use egui::accesskit::{Action, ActionRequest, NodeId, TreeId};
let mut rig = Rig::mac();
let original = rig.bindings("file.save");
rig.shared.borrow_mut().state.select(&CommandRef::from("file.save"));
rig.pass();
let replace = rig.find("Replace ⌘S for Save");
let search = rig.find("Search:");
rig.fixture.frame(vec![egui::Event::AccessKitActionRequest(ActionRequest {
action: Action::Click,
target_tree: TreeId::ROOT,
target_node: NodeId(replace.node.raw()),
data: None,
})]);
let pos = search.center();
rig.fixture.frame(vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE },
]);
rig.fixture.release(&search).type_key(Key::F, "f");
rig.pass();
let shared = rig.shared.borrow();
let snapshot = shared.state.snapshot(&shared.km).unwrap();
assert_eq!(snapshot.query, "f");
assert_eq!(snapshot.recording, None);
assert_eq!(snapshot.keys, original);
}
#[trial]
fn changing_layout_cancels_a_pending_detail_replacement() {
let mut rig = Rig::tuned(Platform::Windows, |options| options.double_press = true);
let original = rig.bindings("file.save");
rig.shared.borrow_mut().state.select(&CommandRef::from("file.save"));
rig.pass();
rig.click("Replace Ctrl+S for Save");
rig.press(Modifiers::NONE, Key::F11);
rig.shared.borrow_mut().options.layout = Layout::CommandLists;
rig.fixture.advance(1.0);
rig.pass();
assert_eq!(rig.bindings("file.save"), original);
let shared = rig.shared.borrow();
assert_eq!(shared.state.snapshot(&shared.km).unwrap().recording, None);
}
/// While recording, Tab, an arrow and Shift+Escape are chords, not focus moves or a close.
#[trial]
+31 -15
View File
@@ -25,6 +25,20 @@ fn open_zip<'a>(bytes: &'a [u8], limits: &Limits, max_total: u64) -> Result<Zip<
Ok(zip)
}
/// Every entry that can be a part, as (index, name). Part names are a virtual namespace, never
/// joined to a filesystem path, so a legacy writer's leading `/` is no hazard and its part stays
/// readable; names with traversal components (`..`, a drive prefix, a NUL) are left out
/// ([`craft_zip::Archive::virtual_entry_name`]).
fn entries(zip: &mut Zip<'_>) -> Result<Vec<(usize, String)>, Error> {
let mut out = Vec::new();
for index in 0..zip.len() {
if let Some(name) = zip.virtual_entry_name(index).map_err(crate::zip_error)? {
out.push((index, name));
}
}
Ok(out)
}
/// A part name as stored: `\` as `/` (code that splits paths on `/` must not meet a `\`), no
/// leading `/`.
fn stored_name(name: &str) -> String {
@@ -59,8 +73,8 @@ impl Package {
let mut files = BTreeMap::new();
let mut skipped = Vec::new();
let (mut total, mut work) = (0u64, 0u64);
let entries: Vec<String> = zip.names().map(|n| n.into_owned()).collect();
for (i, entry) in entries.iter().enumerate() {
let entries = entries(&mut zip)?;
for (i, (index, entry)) in entries.iter().enumerate() {
if skip && work >= limits.max_work {
log::warn!("opc: decompression budget spent; skipping the remaining {} entries", entries.len().saturating_sub(i));
break;
@@ -69,7 +83,7 @@ impl Package {
continue;
}
let name = stored_name(entry);
let size = zip.declared_size(entry).unwrap_or(0);
let size = zip.virtual_entry_size(*index).ok().flatten().unwrap_or(0);
if size > limits.max_part {
if skip {
log::warn!("opc: skipping oversized part {name} ({size} bytes)");
@@ -87,7 +101,7 @@ impl Package {
}
return Err(Error::PackageTooLarge { limit: limits.max_total.min(limits.max_work) });
}
match zip.read(entry, room) {
match zip.read_virtual_index(*index, room) {
Ok(Some(buf)) => {
work = work.saturating_add(buf.len() as u64);
total = total.saturating_add(buf.len() as u64);
@@ -207,8 +221,8 @@ impl Package {
/// reader that needs a few parts of a large file, or one part at a time.
pub struct LazyPackage<'a> {
zip: Zip<'a>,
/// Normalized part name → entry name (the first entry of a name).
names: HashMap<String, String>,
/// Normalized part name → entry index and name (the first entry of a name).
names: HashMap<String, (usize, String)>,
total: u64,
limits: Limits,
}
@@ -218,10 +232,10 @@ impl<'a> LazyPackage<'a> {
/// [`Limits::oversized`] are not used.
pub fn open(bytes: &'a [u8], limits: &Limits) -> Result<LazyPackage<'a>, Error> {
// This reader keeps its own count, which a failed read spends (see `read_limited`).
let zip = open_zip(bytes, limits, u64::MAX)?;
let mut zip = open_zip(bytes, limits, u64::MAX)?;
let mut names = HashMap::new();
for n in zip.names() {
names.entry(normalize(&n)).or_insert_with(|| n.into_owned());
for (index, n) in entries(&mut zip)? {
names.entry(normalize(&n)).or_insert((index, n));
}
Ok(LazyPackage { zip, names, total: 0, limits: *limits })
}
@@ -240,7 +254,7 @@ impl<'a> LazyPackage<'a> {
/// The stored spelling of part `name` (leading `/` ignored; case-insensitive), as
/// [`Package::canonical`] gives it: for a writer that keeps the package's part names.
pub fn canonical(&self, name: &str) -> Option<String> {
self.names.get(&normalize(name)).map(|n| n.trim_start_matches('/').replace('\\', "/"))
self.names.get(&normalize(name)).map(|(_, n)| n.trim_start_matches('/').replace('\\', "/"))
}
/// Bytes charged to [`Limits::max_total`] so far. It is the whole of it once a read has
@@ -275,10 +289,10 @@ impl<'a> LazyPackage<'a> {
/// pay it again and again. Every later read is then a cheap error.
pub fn read_limited(&mut self, part: &str, maximum: u64) -> Result<Option<Vec<u8>>, Error> {
let maximum = maximum.min(self.limits.max_part);
let Some(entry) = self.names.get(&normalize(part)) else {
let Some(&(index, _)) = self.names.get(&normalize(part)) else {
return Ok(None);
};
let size = self.zip.declared_size(entry).unwrap_or(0);
let size = self.zip.virtual_entry_size(index).ok().flatten().unwrap_or(0);
if size > maximum {
return Err(Error::PartTooLarge { part: part.to_string(), limit: maximum });
}
@@ -287,7 +301,7 @@ impl<'a> LazyPackage<'a> {
self.total = self.limits.max_total;
return Err(Error::PackageTooLarge { limit: self.limits.max_total });
}
match self.zip.read(entry, maximum.min(remaining)) {
match self.zip.read_virtual_index(index, maximum.min(remaining)) {
Ok(Some(out)) => {
self.total = self.total.saturating_add(out.len() as u64);
Ok(Some(out))
@@ -321,8 +335,10 @@ impl<'a> LazyPackage<'a> {
/// the user which part made a package too large.
pub fn declared_oversized(bytes: &[u8], limits: &Limits) -> Option<(String, u64)> {
let mut zip = open_zip(bytes, limits, u64::MAX).ok()?;
let names: Vec<String> = zip.names().map(|n| n.into_owned()).collect();
names.into_iter().find_map(|n| zip.declared_size(&n).filter(|size| *size > limits.max_part).map(|size| (n, size)))
entries(&mut zip)
.ok()?
.into_iter()
.find_map(|(index, n)| zip.virtual_entry_size(index).ok().flatten().filter(|size| *size > limits.max_part).map(|size| (n, size)))
}
#[cfg(test)]
+43 -1
View File
@@ -182,10 +182,24 @@ fn skipped_parts_count_against_the_inflate_budget() {
assert_eq!(Package::open(&z, &refuse).err(), Some(Error::PackageTooLarge { limit: 100 }));
}
/// Renames every entry spelled `from` to `to`, a name of the same length, in its local and
/// central headers: for names the writer refuses to store.
fn rename_entries(z: &mut [u8], from: &[u8], to: &[u8]) {
assert_eq!(from.len(), to.len());
let found: Vec<usize> = z.windows(from.len()).enumerate().filter(|(_, w)| *w == from).map(|(i, _)| i).collect();
assert_eq!(found.len(), 2, "one local and one central header");
for at in found {
z[at..at + to.len()].copy_from_slice(to);
}
}
#[test]
fn backslash_zip_entry_names_are_found() {
let z = zip_of(&[("PPT\\Slides\\Slide1.xml", b"<a/>".to_vec()), ("/docProps/core.xml", b"<b/>".to_vec())]);
// A legacy writer's leading `/` stays a readable part: part names are never filesystem paths.
let mut z = zip_of(&[("PPT\\Slides\\Slide1.xml", b"<a/>".to_vec()), ("xdocProps/core.xml", b"<b/>".to_vec())]);
rename_entries(&mut z, b"xdocProps/core.xml", b"/docProps/core.xml");
let p = Package::open(&z, &LIMITS).unwrap();
assert_eq!(p.get("docProps/core.xml"), Some(&b"<b/>"[..]));
assert!(p.get("ppt/slides/slide1.xml").is_some());
assert_eq!(p.canonical("ppt/slides/slide1.xml"), Some("PPT/Slides/Slide1.xml"));
assert_eq!(p.canonical("docprops/core.xml"), Some("docProps/core.xml"));
@@ -195,6 +209,34 @@ fn backslash_zip_entry_names_are_found() {
assert_eq!(lazy.canonical("/DOCPROPS/core.xml").as_deref(), Some("docProps/core.xml"));
assert_eq!(lazy.canonical("nothing"), None);
assert_eq!(lazy.read("PPT/slides/slide1.xml").unwrap().as_deref(), Some(&b"<a/>"[..]));
assert_eq!(lazy.read("docProps/core.xml").unwrap().as_deref(), Some(&b"<b/>"[..]));
}
#[test]
fn traversal_zip_entry_names_are_not_parts() {
let mut z = zip_of(&[("a.xml", b"<a/>".to_vec()), ("xx/evil.xml", b"<e/>".to_vec()), ("C_/evil2.xml", b"<f/>".to_vec())]);
rename_entries(&mut z, b"xx/evil.xml", b"../evil.xml");
rename_entries(&mut z, b"C_/evil2.xml", b"C:/evil2.xml");
let p = Package::open(&z, &LIMITS).unwrap();
assert_eq!(p.names().collect::<Vec<_>>(), ["a.xml"]);
let mut lazy = LazyPackage::open(&z, &LIMITS).unwrap();
assert_eq!(lazy.names(), ["a.xml"]);
assert_eq!(lazy.read("../evil.xml").unwrap(), None);
assert_eq!(lazy.read("evil.xml").unwrap(), None);
}
/// Indexing part names reads only the central directory: one part whose local header is
/// damaged leaves the others readable.
#[test]
fn a_damaged_local_header_does_not_stop_the_package_opening() {
let mut z = zip_of(&[("a.xml", b"<a/>".to_vec()), ("bad.xml", b"<b/>".to_vec())]);
let local = z.windows(7).position(|w| w == b"bad.xml").unwrap() - 30;
assert_eq!(&z[local..local + 4], b"PK\x03\x04");
z[local] = b'X';
let p = Package::open(&z, &LIMITS).unwrap();
assert_eq!(p.get("a.xml"), Some(&b"<a/>"[..]));
let mut lazy = LazyPackage::open(&z, &LIMITS).unwrap();
assert_eq!(lazy.read("a.xml").unwrap().as_deref(), Some(&b"<a/>"[..]));
}
#[test]
+3
View File
@@ -175,6 +175,9 @@ impl<'b> Archive<'b> {
if zip.has_duplicate_names() {
return Err(corrupt("duplicate ZIP member names"));
}
if zip.has_traversal_component() {
return Err(corrupt("unsafe ZIP member path"));
}
// Reject oversized logical archives before decoding any JSON. This guards against ZIP bombs
// whose compressed size is innocuous but whose advertised uncompressed size is enormous.
let names: Vec<String> = zip.names().map(|n| n.into_owned()).collect();
+10 -2
View File
@@ -778,9 +778,17 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256)
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)(IO)R").output().unwrap();
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
let sddl = sddl_of(&dir).unwrap();
assert!(sddl.contains(";IO;") && sddl.contains(";S-1-5-32-545)"), "the inherit-only entry for Users is read: {sddl}");
let users = sddl
.split('(')
.filter_map(|ace| ace.split(')').next())
.find(|ace| ace.split(';').nth(1).is_some_and(|flags| flags.contains("IO")) && ace.ends_with(";S-1-5-32-545"));
let users = users.unwrap_or_else(|| panic!("the inherit-only entry for Users is read: {sddl}"));
// The folder also inherits the temp folder's entries (Administrators on a CI runner), which the check reports
// first, so it is asked about the Users entry alone.
let me = current_user_sid().unwrap();
assert!(foreign_folder_access(&sddl, &me).is_some_and(|p| p.contains("S-1-5-32-545")), "{sddl}");
let only_users = format!("O:{}D:({users})", section(&sddl, "O:").unwrap());
assert!(foreign_folder_access(&only_users, &me).is_some_and(|p| p.contains("S-1-5-32-545")), "{sddl}");
assert_eq!(foreign_access(&only_users, &me), None, "a file's check skips the inherit-only entry: {sddl}");
let _ = std::fs::remove_dir_all(&dir);
}
+1
View File
@@ -19,6 +19,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "<commit>
| French (fr-FR, fr-CA and other French pack locales) | the installed Language pack or Hunspell dictionary; dictionary-driven elisions and accent-oriented suggestions | conservative typography and basic checks, with Quebec punctuation spacing in fr-CA | the Language pack (generic fr fallback) |
| German | — | — | TeX patterns (embedded, or a Language pack) |
| Bulgarian | — | — | syllable rules |
| Gujarati, Hindi | the installed Hunspell dictionary (Hindi: nukta letters spelled either way) | generic checks | akshara rules (or a Language pack) |
Grammar rules, suggestion tuning and the rule-based hyphenation are code: they work in every
build.
+88
View File
@@ -0,0 +1,88 @@
//! What the proofing of a language written in Devanagari (Hindi now) needs to know about the
//! script, for the shared checks ([`crate::script_checks`]): its letters (as the akshara rules
//! classify them, [`crate::indic::Script::Devanagari`]), its digits and the two spellings of its
//! nukta letters.
use crate::indic;
use crate::script_checks::Script;
/// Devanagari for the shared checks.
pub(crate) const SCRIPT: Script =
Script { in_words: is_letter, is_letter, is_digit: is_devanagari_digit, variant: Some(nukta_variant as fn(&str) -> Option<String>) };
fn is_letter(c: char) -> bool {
indic::Script::Devanagari.is_letter(c)
}
/// Is `c` a Devanagari digit (`०`..=`९`, U+0966..=U+096F)?
fn is_devanagari_digit(c: char) -> bool {
('\u{0966}'..='\u{096F}').contains(&c)
}
/// The consonants with a precomposed nukta letter (U+0958..=U+095F): the base consonant, then
/// the precomposed letter.
const NUKTA_LETTERS: [(char, char); 8] = [
('\u{0915}', '\u{0958}'),
('\u{0916}', '\u{0959}'),
('\u{0917}', '\u{095A}'),
('\u{091C}', '\u{095B}'),
('\u{0921}', '\u{095C}'),
('\u{0922}', '\u{095D}'),
('\u{092B}', '\u{095E}'),
('\u{092F}', '\u{095F}'),
];
/// The nukta sign (U+093C).
const NUKTA: char = '\u{093C}';
/// `w` with its nukta letters spelled the other way, if it has any: precomposed ones (`क़`,
/// U+0958) as consonant and nukta (`क` + `़`), else consonant-and-nukta pairs precomposed.
/// Composition (NFC) always gives the pair, since the precomposed letters are excluded from it,
/// but a dictionary may list either spelling.
pub(crate) fn nukta_variant(w: &str) -> Option<String> {
let precomposed = |c: char| NUKTA_LETTERS.iter().find(|&&(_, p)| p == c).map(|&(base, _)| base);
if w.chars().any(|c| precomposed(c).is_some()) {
let mut out = String::with_capacity(w.len() + 4);
for c in w.chars() {
match precomposed(c) {
Some(base) => {
out.push(base);
out.push(NUKTA);
}
None => out.push(c),
}
}
return Some(out);
}
let mut out = String::with_capacity(w.len());
let mut changed = false;
let mut chars = w.chars().peekable();
while let Some(c) = chars.next() {
if let Some(&(_, p)) = NUKTA_LETTERS.iter().find(|&&(base, _)| base == c)
&& chars.peek() == Some(&NUKTA)
{
chars.next();
out.push(p);
changed = true;
} else {
out.push(c);
}
}
changed.then_some(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nukta_letters_have_two_spellings() {
// ज़मीन precomposed and as ज + nukta; सड़क the same.
assert_eq!(nukta_variant("\u{095B}मीन").as_deref(), Some("ज\u{093C}मीन"));
assert_eq!(nukta_variant("ज\u{093C}मीन").as_deref(), Some("\u{095B}मीन"));
assert_eq!(nukta_variant("सड\u{093C}क").as_deref(), Some("स\u{095C}क"));
// A nukta on a consonant with no precomposed letter, and no nukta at all: one spelling.
assert_eq!(nukta_variant("स\u{093C}"), None);
assert_eq!(nukta_variant("किताब"), None);
}
}
+71
View File
@@ -0,0 +1,71 @@
//! Generic repeated-word and spacing checks, shared with the other languages proofed by their
//! script, with Gujarati messages. No Gujarati-specific grammar or case rules are inferred.
use crate::script_checks::Rules;
use crate::{Issue, ProofLang};
/// Checks `text` for repeated words and spacing problems, with Gujarati messages.
pub fn check(text: &str) -> Vec<Issue> {
crate::script_checks::check(text, &RULES)
}
const RULES: Rules = Rules {
lang: ProofLang::Gu,
script: &super::SCRIPT,
repeated_word: "પુનરાવર્તિત શબ્દ",
space_before_punctuation: "વિરામચિહ્ન પહેલાં જગ્યા",
double_space: "બેવડી જગ્યા",
flag_repeat: |w| !ALLOWED_REPEATS.contains(&w),
};
/// Words Gujarati repeats on purpose (`હા હા`, `ના ના`, `ધીમે ધીમે`, `સાચે સાચે`).
const ALLOWED_REPEATS: &[&str] = &["હા", "ના", "ધીમે", "જલ્દી", "વારંવાર", "સાચે", "રોજે", "ખરેખર", "જરા", "થોડું", "સાથે", "પાસે"];
#[cfg(test)]
mod tests {
use super::*;
use crate::IssueKind;
#[test]
fn intentional_repeats_are_fine() {
for text in ["હા હા, હું આવીશ.", "ના ના, આ નથી.", "ધીમે ધીમે ચાલ.", "સાચે સાચે બોલ."]
{
assert!(check(text).is_empty(), "{text}: {:?}", check(text));
}
assert_eq!(check("પુસ્તક પુસ્તક છે.").len(), 1);
assert!(check("1 1").is_empty());
assert!(check("૧ ૧").is_empty());
}
#[test]
fn repeated_words_and_spaces_have_gujarati_messages() {
let text = "ઘર ઘર , શાળા.";
let issues = check(text);
assert_eq!(issues.len(), 3, "{issues:?}");
assert_eq!(issues[0].message, "પુનરાવર્તિત શબ્દ: “ઘર”");
assert_eq!(issues[0].suggestions, ["ઘર"]);
assert!(issues.iter().any(|i| i.message == "વિરામચિહ્ન પહેલાં જગ્યા" && &text[i.start..i.end] == " ,"));
assert!(issues.iter().any(|i| i.message == "બેવડી જગ્યા"));
assert!(issues.iter().all(|i| i.lang == ProofLang::Gu && i.kind == IssueKind::Grammar));
}
#[test]
fn ratios_and_scores_keep_their_spaces() {
for text in ["3 : 1", "1 : 2", "સ્કોર 12 : 10.", "૩ : ૧", "૧ : ૨", "સ્કોર ૧૨ : ૧૦."] {
assert!(check(text).is_empty(), "{text}: {:?}", check(text));
}
for text in ["શબ્દ : બીજો", "3 : શબ્દ", "3 :", "૩ : શબ્દ", "૩ :"] {
assert!(check(text).iter().any(|i| i.message == "વિરામચિહ્ન પહેલાં જગ્યા"), "{text}");
}
}
proptest::proptest! {
#[test]
fn never_panics_and_ranges_are_valid(s in "\\PC{0,80}") {
for issue in check(&s) {
proptest::prop_assert!(issue.start <= issue.end && issue.end <= s.len());
proptest::prop_assert!(s.is_char_boundary(issue.start) && s.is_char_boundary(issue.end));
}
}
}
}
+177
View File
@@ -0,0 +1,177 @@
//! Gujarati proofing using the installed Hunspell `gu_IN` dictionary (never bundled).
//! Suggestions use its runtime MAP/REP/TRY/KEY tables. Generic grammar checks have Gujarati
//! messages. Hyphenation is by akshara ([`crate::indic`]).
pub mod grammar;
pub(crate) mod suggest;
#[cfg(test)]
pub(crate) mod test_dict;
use std::sync::Arc;
use crate::affix::AffixDict;
use crate::script_checks::Script;
use crate::slot::DictSlot;
pub use suggest::suggest;
/// File names of a Gujarati Hunspell dictionary.
const NAMES: &[&str] = &["gu_IN", "gu-IN", "gu"];
/// The Gujarati dictionary, found on first use (see [`DictSlot`]).
pub(crate) static DICT: DictSlot<AffixDict> = DictSlot::new(NAMES, "Gujarati");
/// The Gujarati dictionary: the installed Hunspell `gu_IN` (read on first use), one given with
/// [`install_dictionary`], or an empty one when none is available (Gujarati spelling is off
/// then; see [`has_dictionary`]).
pub fn dictionary() -> Arc<AffixDict> {
DICT.get()
}
/// Use this Gujarati dictionary from now on (Hunspell `.aff` and `.dic` text, decoded to
/// UTF-8), for example one the user picked. On error the current dictionary stays.
pub fn install_dictionary(aff: &str, dic: &str) -> Result<(), String> {
DICT.install(aff, dic)
}
/// Is a Gujarati dictionary available (spelling is checked)?
pub fn has_dictionary() -> bool {
DICT.has_dictionary()
}
/// Returns `true` when `c` is in the Gujarati Unicode block (U+0A80..=U+0AFF).
pub fn is_gujarati_char(c: char) -> bool {
('\u{0A80}'..='\u{0AFF}').contains(&c)
}
/// Is `word` spelled correctly in Gujarati? Numbers, single letters, short words with digits and words in other scripts are accepted, and so
/// is every word when no Gujarati dictionary is installed.
pub fn is_correct(word: &str) -> bool {
is_correct_with(&dictionary(), word)
}
/// [`is_correct`] with the File › Options › Proofing choices: with Ignore words that contain numbers off, words with digits are checked.
pub fn is_correct_with_options(word: &str, opts: &crate::Options) -> bool {
check(&dictionary(), word, opts)
}
/// [`is_correct`] against a given dictionary (an empty one accepts everything).
pub fn is_correct_with(d: &AffixDict, word: &str) -> bool {
check(d, word, &crate::Options::default())
}
/// [`is_correct_with_options`] against a given dictionary.
fn check(d: &AffixDict, word: &str, opts: &crate::Options) -> bool {
crate::script_checks::is_correct(&SCRIPT, d, word, opts)
}
/// Gujarati for the shared checks: the whole block is kept in words, its letters are everything
/// in it but the digits.
pub(crate) const SCRIPT: Script = Script { in_words: is_gujarati_char, is_letter, is_digit: is_gujarati_digit, variant: None };
fn is_letter(c: char) -> bool {
is_gujarati_char(c) && !c.is_numeric()
}
/// Is `c` a Gujarati digit (U+0AE6..=U+0AEF)?
fn is_gujarati_digit(c: char) -> bool {
('\u{0AE6}'..='\u{0AEF}').contains(&c)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dictionary_lookup_accepts_gujarati_file_names() {
let dir = std::env::temp_dir().join(format!("wordcraft-gu-aliases-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
for name in ["gu_IN", "gu-IN", "gu"] {
std::fs::write(dir.join(format!("{name}.aff")), test_dict::AFF).unwrap();
std::fs::write(dir.join(format!("{name}.dic")), test_dict::DIC).unwrap();
let (aff, dic) = crate::hunspell::find_in(&dir, NAMES).unwrap();
let d = crate::hunspell::load(&aff, &dic).unwrap();
assert!(is_correct_with(&d, "ઘરો"));
std::fs::remove_file(aff).unwrap();
std::fs::remove_file(dic).unwrap();
}
std::fs::remove_dir(dir).unwrap();
}
#[test]
fn gujarati_words_affixes_and_case_markers() {
test_dict::install();
let d = dictionary();
assert!(has_dictionary());
assert_eq!(d.len(), 15);
for w in [
"ઘર",
"ઘરો",
"ઘરોને",
"ઘરોમાં",
"પુસ્તક",
"પુસ્તકો",
"પુસ્તકોમાં",
"પાણી",
"શાળા",
"ભાષા",
"પરીક્ષણ",
"પ્રેમ",
"શહેર",
"ગામ",
"મિત્ર",
"અઘર",
"શાળા-શહેર",
] {
assert!(is_correct(w), "{w}");
}
for w in ["ઘરર", "પુસ્તકક", "પાણીઈ", "શાળળા", "zqપ્રતિબંધિત"] {
assert!(!is_correct(w), "{w}");
}
}
#[test]
fn forbidden_words_are_rejected() {
test_dict::install();
assert!(!is_correct("zqપ્રતિબંધિત"));
}
#[test]
fn missing_dictionary_and_ignored_inputs_are_quiet() {
let empty = AffixDict::default();
assert!(is_correct_with(&empty, "શાળા"));
assert!(install_dictionary("FLAG bogus\n", "1\nઘર\n").is_err());
let d = AffixDict::from_hunspell(test_dict::AFF, test_dict::DIC, &[]).unwrap();
for w in ["", "2026", "૧૨", "૨૦૨૬", "અ", "English", "日本語"] {
assert!(is_correct_with(&d, w), "{w}");
}
let no_ignore = crate::Options { ignore_numbers: false, ..Default::default() };
assert!(check(&d, "૧૨", &no_ignore));
assert!(check(&d, "2026", &no_ignore));
}
#[test]
fn user_dictionary_applies() {
test_dict::install();
assert!(!is_correct("નવોશબ્દગુજરાતી"));
crate::add_word("નવોશબ્દગુજરાતી");
assert!(is_correct("નવોશબ્દગુજરાતી"));
}
#[test]
fn gujarati_dispatch_messages_options_and_mixed_spans() {
crate::hold_dictionary_tests();
test_dict::install();
assert!(crate::has_dictionary(Some("gu-IN")));
assert!(crate::is_correct_for("ઘરો", Some("guj")));
let text = "ઘર પુસ્તકક";
let issues = crate::check_text(text, &[(0..text.len(), crate::ProofLang::Gu)]);
assert_eq!(issues.len(), 1, "{issues:?}");
assert_eq!(&text[issues[0].start..issues[0].end], "પુસ્તકક");
assert_eq!(issues[0].message, "શક્ય જોડણી ભૂલ");
assert_eq!(issues[0].lang, crate::ProofLang::Gu);
let text = "ઘર this is is wrong";
let issues = crate::check_text(text, &[(0..3, crate::ProofLang::Gu), (4..text.len(), crate::ProofLang::En)]);
assert!(issues.iter().any(|i| i.lang == crate::ProofLang::En && i.message.starts_with("Repeated word")));
}
}
+100
View File
@@ -0,0 +1,100 @@
//! Gujarati suggestions: the shared ranking ([`crate::affix_suggest`]) with the installed
//! dictionary's own MAP/REP/TRY/KEY tables and nothing Gujarati hard-coded.
use crate::affix::AffixDict;
use crate::affix_suggest::Tuning;
/// Spelling suggestions for a Gujarati word, best first, at most `max`.
pub fn suggest(word: &str, max: usize) -> Vec<String> {
suggest_in(&super::dictionary(), word, max)
}
/// [`suggest`] against a given dictionary.
pub fn suggest_in(d: &AffixDict, word: &str, max: usize) -> Vec<String> {
crate::affix_suggest::suggest_in(d, word, max, &Tuning::DEFAULT)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn suggestion_results_stay_bounded_on_complex_inputs() {
crate::gu::test_dict::install();
for word in ["zqખૂબલાંબોશબ્દગુજરાતી", "પુસતક", "પરીક્ષણણ"] {
let res = suggest(word, 6);
assert!(res.len() <= 6, "{word}: got {} suggestions", res.len());
assert!(!res.contains(&"zqપ્રતિબંધિત".to_string()));
for s in &res {
assert!(!s.is_empty());
assert!(super::super::is_correct(s), "suggested word {s} should be valid");
}
}
}
/// A NOSUGGEST stem stays correct spelling, but the Gujarati collector never offers it or any
/// prefixed, suffixed, REP-reached or recased form of it; ordinary stems are still offered.
#[test]
fn nosuggest_stems_and_forms_are_never_offered() {
let aff = "SET UTF-8\nNOSUGGEST N\nFORBIDDENWORD F\nTRY abeklmnostxy\nMAP 1\nMAP ae\nKEY ak\nREP 2\nREP xy toka\nREP zz normal\nPFX X Y 1\nPFX X 0 pre .\nSFX A Y 1\nSFX A 0 ble/B .\nSFX B Y 1\nSFX B 0 s .\n";
let d = AffixDict::from_hunspell(aff, "4\ntoka/NXA\nnormal/XA\nTkname/N\nbanned/F\n", &[]).unwrap();
for word in d.forms("toka").into_iter().chain(["TOKA".into(), "Toka".into(), "Tkname".into(), "TKNAME".into()]) {
assert!(d.check(&word), "NOSUGGEST is still correct: {word}");
assert!(!d.can_suggest(&word), "NOSUGGEST form: {word}");
}
for input in ["tokax", "tokablesx", "pretokax", "pretokablesx", "toka", "TOKA", "tkname", "teka", "xy", "normaltoka", "toak", "taak"] {
let got = suggest_in(&d, input, 32);
assert!(got.iter().all(|w| w.split(' ').all(|part| d.can_suggest(part))), "{input}: {got:?}");
assert!(got.iter().all(|w| !w.to_lowercase().contains("toka") && w.to_lowercase() != "tkname"), "{input}: {got:?}");
}
assert!(suggest_in(&d, "norrmal", 8).contains(&"normal".into()));
assert!(suggest_in(&d, "zz", 8).contains(&"normal".into()));
// Filtering happens before display casing: an ordinary mixed-case stem keeps its all-caps
// suggestion, with and without a NOSUGGEST declaration.
for aff in ["", "NOSUGGEST N\n"] {
let ordinary = AffixDict::from_hunspell(aff, "2\nmixCase\nhidden/N\n", &[]).unwrap();
assert!(suggest_in(&ordinary, "MIXCASX", 8).contains(&"MIXCASE".into()));
}
// The same contract in Gujarati script, with Gujarati affixes and REP pairs.
let aff = "SET UTF-8\nNOSUGGEST N\nTRY ગુપ્તસામાન્યઅોં\nREP 2\nREP ગુપત ગુપ્ત\nREP સામાનય સામાન્ય\nPFX X Y 1\nPFX X 0 અ .\nSFX A Y 1\nSFX A 0 ો/B .\nSFX B Y 1\nSFX B 0 માં .\n";
let d = AffixDict::from_hunspell(aff, "2\nગુપ્ત/NXA\nસામાન્ય/XA\n", &[]).unwrap();
let hidden = d.forms("ગુપ્ત");
assert!(hidden.contains(&"અગુપ્તો".into()) && hidden.contains(&"ગુપ્તોમાં".into()), "{hidden:?}");
for word in hidden.iter().chain(&["અગુપ્તોમાં".to_string()]) {
assert!(d.check(word), "NOSUGGEST is still correct: {word}");
assert!(!d.can_suggest(word), "NOSUGGEST form: {word}");
}
for input in ["ગુપત", "અગુપત", "ગુપતો", "અગુપતોમાં", "ગુપ્તત", "અગુપ્તોમા"]
{
let got = suggest_in(&d, input, 32);
assert!(got.iter().all(|w| w.split(' ').all(|part| d.can_suggest(part))), "{input}: {got:?}");
assert!(got.iter().all(|w| !w.contains("ગુપ્ત")), "{input}: {got:?}");
}
assert!(suggest_in(&d, "સામાનય", 8).contains(&"સામાન્ય".into()));
assert!(suggest_in(&d, "અસામાનયો", 8).contains(&"અસામાન્યો".into()));
}
#[test]
fn gujarati_suggestions_use_runtime_tables() {
crate::gu::test_dict::install();
for (word, want) in [("શાલા", "શાળા"), ("પાની", "પાણી"), ("પ્રેમમ", "પ્રેમ"), ("પરીકશણ", "પરીક્ષણ")]
{
let s = suggest(word, 8);
assert!(s.contains(&want.into()), "{word}: {s:?}");
}
}
#[test]
fn suggestions_stay_bounded_and_skip_forbidden_words() {
crate::gu::test_dict::install();
for w in ["", "બે શબ્દો", &"શ".repeat(41)] {
assert!(suggest(w, 4).is_empty());
}
assert!(suggest("ઘર", 0).is_empty());
assert!(suggest_in(&AffixDict::default(), "ઘર", 4).is_empty());
assert!(suggest("ઘર", 4).len() <= 4);
assert!(!suggest("ઘર", 4).contains(&"ઘર".into()));
assert!(!suggest("zqપ્રતિબંધિત", 8).contains(&"zqપ્રતિબંધિત".into()));
}
}
+51
View File
@@ -0,0 +1,51 @@
//! Hand-written synthetic Gujarati test data. No words, rules or suggestion tables were copied
//! from a system dictionary. This is a small fixture, not a redistributable Gujarati dictionary.
pub const AFF: &str = "SET UTF-8
FLAG UTF-8
FORBIDDENWORD F
TRY અઆઇઈઉઊઋએઐઓઔકખગઘઙચછજઝઞટઠડઢણતથદધનપફબભમયરલવશષસહળક્ષજ્ઞાિીુૂૃૄેૈોૌ્ંઃઁ
KEY ષસ|તર
MAP 4
MAP ઇઈિી
MAP ઉઊુૂ
MAP સશષ
MAP ણન
REP 1
REP કશ ક્ષ
SFX N Y 4
SFX N 0 ો/C .
SFX N 0 ો .
SFX N 0 ઓ/C .
SFX N 0 ઓ .
SFX C Y 4
SFX C 0 ને .
SFX C 0 માં .
SFX C 0 થી .
SFX C 0 નો .
PFX X Y 1
PFX X 0 અ .
";
pub const DIC: &str = "15
ઘર/NX
પુસ્તક/NX
પાણી
શાળા
ભાષા
પરીક્ષણ
પ્રેમ
શહેર
ગામ/NX
મિત્ર/NX
ઝાડ
ફળ
કમળ
સૂર્ય
zqપ્રતિબંધિત/F
";
pub fn install() {
crate::hold_dictionary_tests();
super::install_dictionary(AFF, DIC).unwrap();
}
Loaded 100 of 395 files, more files were not shown because too many files have changed in this diff. Show more