mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-24 06:44:18 -06:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c25a859e52 | ||
|
|
72626054f2 | ||
|
|
4af551c178 |
@@ -1,4 +1,4 @@
|
||||
# Exercise the native print host and all UI tests on Windows and macOS on PRs; the broad FreeBSD/ARM64 gates
|
||||
# Exercise the native print host and all UI tests on PRs; the broad FreeBSD/ARM64 gates
|
||||
# stay on their existing nightly/release schedule.
|
||||
name: Printing
|
||||
|
||||
@@ -30,32 +30,31 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# The print host and UI tests on Windows and macOS, through the suite's shared gate: it checks out
|
||||
# craft-i18n (craft-i18n.rev) and craft-fonts. Linux is not repeated here: ci.yml's gate runs
|
||||
# `cargo xtask ci` there, which already covers fmt, workspace clippy, every test and the wasm build.
|
||||
# The print host and UI tests on Linux, Windows and macOS, through the suite's shared gate: it
|
||||
# checks out craft-i18n (craft-i18n.rev) and craft-fonts, and installs the Ubuntu packages through
|
||||
# install-apt-packages, which falls back to mirrors outside ubuntu.com (as on 11 Nov 2026).
|
||||
native:
|
||||
name: Print
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: '["windows-latest","macos-latest"]'
|
||||
os: '["ubuntu-24.04","windows-latest","macos-latest"]'
|
||||
timeout-minutes: 90
|
||||
# The catalogs include CJK interface languages, so the UI tests need the suite's fonts, as in
|
||||
# the gate (same commit as ci.yml and release.yml).
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
packages: >-
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev
|
||||
libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev libvulkan1 mesa-vulkan-drivers
|
||||
# No nextest: the tests run with cargo test, as before.
|
||||
tools: ""
|
||||
# Its own cache, apart from ci.yml's gate, which builds the whole workspace.
|
||||
cache-version: v1-printing
|
||||
# Test binaries without debug info: they link faster and shrink to about a third, and panics
|
||||
# keep their file:line.
|
||||
dev-strip: true
|
||||
# Clippy on its own leg beside the tests, off their critical path. fmt is platform-independent
|
||||
# and runs in ci.yml. The web app's wasm build, once: ci.yml's `cargo xtask wasm` checks the
|
||||
# library crates and ui-egui, not apps/wordcraft-web.
|
||||
lint-command: |
|
||||
command: |
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy -p wordcraft -p wordcraft-ui-egui --all-targets --locked -- -D warnings
|
||||
if [ "$RUNNER_OS" = macOS ]; then
|
||||
cargo test -p wordcraft -p wordcraft-ui-egui --locked
|
||||
# Browser compatibility, once.
|
||||
if [ "$RUNNER_OS" = Linux ]; then
|
||||
cargo check -p wordcraft-web --target wasm32-unknown-unknown --locked
|
||||
fi
|
||||
command: cargo test -p wordcraft -p wordcraft-ui-egui --locked
|
||||
|
||||
@@ -60,4 +60,3 @@ jobs:
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
# Accessibility
|
||||
|
||||
Source: `standards/app-accessibility.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib/blob/main/standards/app-accessibility.md); do not edit this copy directly. Propose changes to the shared statement in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib).
|
||||
|
||||
We want people who use screen readers, braille displays, screen magnifiers, voice control, high contrast, large text, reduced motion, or keyboard navigation to be able to get their work done in the Craft applications.
|
||||
|
||||
## Supported environments and how accessibility works
|
||||
|
||||
The Craft applications draw their own interface in Rust with `egui` and expose accessibility information through **AccessKit**:
|
||||
|
||||
- **Windows:** UI Automation (for tools such as NVDA, JAWS, and Narrator)
|
||||
- **macOS:** NSAccessibility (VoiceOver)
|
||||
- **Linux and FreeBSD:** AT-SPI (Orca)
|
||||
- **Web (WebAssembly):** Browser accessibility tree in modern evergreen browsers
|
||||
- **Display and motion:** Light and dark themes, along with ongoing work to honour system high-contrast, text-scaling, and reduced-motion settings
|
||||
- **Headless and command-line workflows:** Most Craft applications also ship a command-line and automation binary (`<app>-cli`) that can inspect and edit documents from a terminal without using the graphical interface; see [This application](#this-application) below
|
||||
|
||||
**Current status:** The Craft suite is in early-alpha development. We use WCAG 2.2 and W3C's [WCAG2ICT](https://www.w3.org/TR/wcag2ict-22/) as practical reference points for user needs ([RFC-0014](https://github.com/storytold/craft-contrib/blob/main/rfcs/0014-accessibility.md)), while manual testing with assistive technologies across every tool and surface is still in progress.
|
||||
|
||||
## Known limitations and workarounds
|
||||
|
||||
Shared framework improvements are tracked in [storytold/craft-libs#437](https://github.com/storytold/craft-libs/issues/437). Current suite-wide gaps include:
|
||||
|
||||
- **Custom drawn surfaces (canvases, pages, grids, timelines, node graphs, and layer lists):** Some custom-painted views do not yet publish complete `AccessKit` nodes, caret bounds for magnifiers, or editable states (for example, `AccessKit`'s Windows adapter reporting `Document` nodes as read-only, which can prevent typing echo in screen readers). *Workaround:* Use structured inspector panels where available, or run headless commands through `<app>-cli` when a task does not need direct canvas interaction.
|
||||
- **Focus in menus, toolbars, and dialogs:** Some popups, menus, or keyboard access-key overlays may leave focus in the underlying document or not yet restore focus cleanly when dismissed. *Workaround:* Press `Escape` to close open popups, `Alt` or `F10` for menu/toolbar navigation, and `F6` to move between major regions where supported.
|
||||
- **Unannounced state changes:** Shortcuts or background tasks that change state away from focus do not yet consistently announce updates through a live region.
|
||||
- **Pointer-heavy interactions:** Certain timeline, node-wiring, or object-placement gestures do not yet have non-dragging keyboard alternatives.
|
||||
|
||||
See [This application](#this-application) below for repository-specific links and details.
|
||||
|
||||
## Reporting an accessibility barrier
|
||||
|
||||
If you run into an accessibility barrier, please open an issue using the link in [This application](#this-application) below (or let us know in the [ArtCraft Discord](https://discord.gg/artcraft) if GitHub's issue form gets in the way).
|
||||
|
||||
- **No personal disclosure needed:** You never have to disclose a disability or explain why you use assistive technology.
|
||||
- **Screenshots and recordings are optional:** Plain-text descriptions are always welcome and sufficient.
|
||||
- **Helpful details to share (when convenient):**
|
||||
- What you were trying to do, what happened, and what you expected
|
||||
- Application version (or commit) and operating system or browser
|
||||
- Input method, display settings, or assistive technology and version (for example, NVDA, JAWS, Narrator, VoiceOver, Orca, screen magnifier, high contrast, text scaling, or keyboard-only)
|
||||
|
||||
## How we respond
|
||||
|
||||
- **Triage and labels:** Maintainers and triagers label barrier reports with `accessibility` and set priority during triage based on impact—barriers that block a core workflow are treated as high-priority bugs, and barriers that risk losing work are critical.
|
||||
- **Assistive-technology verification (`needs screen reader test`):** Pull requests that fix a reported assistive-technology barrier or add custom accessibility-tree or focus behaviour are labelled `needs screen reader test` so someone using assistive technology can verify a build and share what they observed; if the barrier remains, we reopen the issue.
|
||||
|
||||
## Note for contributors and coding agents
|
||||
|
||||
`ACCESSIBILITY.md` is a user-facing overview, **not** an extra rule set or audit checklist for coding agents:
|
||||
|
||||
- **Follow `AGENTS.md` and [`standards/accessibility.md`](https://github.com/storytold/craft-contrib/blob/main/standards/accessibility.md) for engineering work,** and keep every pull request scoped strictly to its issue. Do not widen an unrelated change to audit or rework surrounding UI.
|
||||
- **Design for the actual user need—do not overbuild or apply naive readings of standards.** Accessibility guidelines exist to support real workflows and give flexible ways to meet them. Understand what a criterion genuinely requires in context before changing UI: for example, a button whose label or icon is legible and whose focus or selection ring already has clear contrast does **not** need its resting fill or border restyled to hit a 3:1 ratio, and inherently spatial or freehand tools should not have artificial keyboard grids bolted onto them.
|
||||
- **Preserve visual design and shared primitives.** Use shared theme tokens and shared widgets from `storytold/craft-libs` instead of inventing one-off styling, contrast overrides, focus shims, or live-region scaffolding inside an application.
|
||||
- **Be candid in pull requests.** Automated accessibility-tree checks never prove a change works with a real screen reader; describe only what was actually verified.
|
||||
|
||||
## Ownership
|
||||
|
||||
Maintained by the `craft-app-team` maintainers in [`storytold`](https://github.com/storytold). Shared updates belong in [`storytold/craft-contrib`](https://github.com/storytold/craft-contrib); repository-specific facts follow below.
|
||||
|
||||
## This application
|
||||
|
||||
**WordCraft** (`storytold/wordcraft`) is an open-source word processor written in pure Rust.
|
||||
|
||||
- **Published application builds:** macOS, Windows, Linux, FreeBSD, and Web (WebAssembly)
|
||||
- **Command-line and automation interface:** `wordcraft-cli` provides headless terminal and automation access for scripted workflows without the graphical interface
|
||||
- **Report an accessibility barrier:** [Open an issue in `storytold/wordcraft`](https://github.com/storytold/wordcraft/issues/new)
|
||||
- **Tracked accessibility issues:** [Open issues labelled `accessibility` in `storytold/wordcraft`](https://github.com/storytold/wordcraft/issues?q=is%3Aissue+state%3Aopen+label%3Aaccessibility)
|
||||
- **Pull requests awaiting assistive-technology verification:** [Pull requests labelled `needs screen reader test` in `storytold/wordcraft`](https://github.com/storytold/wordcraft/pulls?q=is%3Apr+label%3A%22needs+screen+reader+test%22)
|
||||
- **Contributor and agent rules for this repository:** [`AGENTS.md`](AGENTS.md)
|
||||
@@ -135,7 +135,6 @@ The UI icons are SVG files in `crates/ui-egui/icons/`, one row each below. Gener
|
||||
| `crates/ui-egui/icons/designMode.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/dictate.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/discord.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/discordPill.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/distributeCols.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/distributeRows.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
| `crates/ui-egui/icons/docPrefs.svg` | WordCraft contributors | original: exported from WordCraft's own code-drawn icons (`crates/ui-egui/src/icons.rs` before the craft port), text glyphs redrawn as paths | MIT OR Apache-2.0 | UI icon |
|
||||
|
||||
Generated
+281
-178
File diff suppressed because it is too large
Load Diff
+52
-52
@@ -37,20 +37,20 @@ wordcraft-pdf = { path = "crates/pdf" }
|
||||
# reads the ca-valencia pack), #589 (French elision suggestions first), #497 (flag-based
|
||||
# compounding), #496 (review follow-ups, en-AU) and the merged #482–#490/#495 stack; the font
|
||||
# store's `language-pack` kind is #486 (CP4.1).
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
wordcraft-engine = { path = "crates/engine" }
|
||||
wordcraft-mcp = { path = "crates/mcp" }
|
||||
wordcraft-zotero = { path = "crates/zotero" }
|
||||
wordcraft-control-key = { path = "crates/control-key" }
|
||||
wordcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", default-features = false }
|
||||
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -81,28 +81,28 @@ wuff = "0.2.9"
|
||||
brotli-decompressor = "5"
|
||||
vello_cpu = "0.2"
|
||||
image = { version = "0.25", default-features = false }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", default-features = false, features = ["write"] }
|
||||
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", version = "=0.1.0" }
|
||||
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["doc"] }
|
||||
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["text"] }
|
||||
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["flow"] }
|
||||
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0", features = ["detect"] }
|
||||
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", version = "=0.1.0" }
|
||||
# zlib streams (compressed metafile pictures in `.doc` drawings); already in the lock as a dependency of other crates.
|
||||
miniz_oxide = "0.9"
|
||||
cfb = "0.15"
|
||||
@@ -170,27 +170,27 @@ debug = 0
|
||||
# The framework's patches, which Cargo does not carry over to dependents: its vendored crates from craft-libs,
|
||||
# and the egui and winit forks it builds with.
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "7e1c30d142bc7879d043e74b5ceb3ecfe7f51329" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
|
||||
+2
-12
File diff suppressed because one or more lines are too long
@@ -37,7 +37,7 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use craft::host::{FileError, Files, PickId, PickRequest, Picked, WriteIntent};
|
||||
use craft::host::{FileError, Files, PickId, PickRequest, Picked};
|
||||
use craft::platform::browser_files::BrowserFiles;
|
||||
use craft::platform::open::{DropTarget, DroppedFile, IntakeSender};
|
||||
use craft::web_host::web::{FileData, Host, Message};
|
||||
@@ -175,8 +175,8 @@ impl Files for HostedFiles {
|
||||
self.inner.read(path)
|
||||
}
|
||||
|
||||
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError> {
|
||||
self.inner.write(path, bytes, intent)
|
||||
fn write(&self, path: &Path, bytes: &[u8]) -> Result<(), FileError> {
|
||||
self.inner.write(path, bytes)
|
||||
}
|
||||
|
||||
fn last_folder(&self, purpose: &str) -> Option<PathBuf> {
|
||||
|
||||
@@ -64,7 +64,7 @@ fn save(doc: &wordcraft_doc::Document) -> BTreeMap<String, Vec<u8>> {
|
||||
}
|
||||
|
||||
const SETTINGS: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
|
||||
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:mailMerge><w:mainDocumentType w:val="formLetters"/><w:dataSource r:id="rId9"/></w:mailMerge><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
|
||||
|
||||
fn pos(s: &str, needle: &str) -> usize {
|
||||
s.find(needle).unwrap_or_else(|| panic!("{needle} missing from {s}"))
|
||||
|
||||
@@ -66,15 +66,7 @@ const SETTINGS: &str = r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?
|
||||
<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" mc:Ignorable="w14 w15"><w:zoom w:percent="120"/><w:removePersonalInformation/><w:removeDateAndTime/><w:proofState w:spelling="clean" w:grammar="clean"/><w:mailMerge><w:mainDocumentType w:val="formLetters"/><w:dataSource r:id="rId9"/></w:mailMerge><w:trackRevisions/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/></w:compat><w:docVars><w:docVar w:name="ClauseSet" w:val="B"/></w:docVars><w:rsids><w:rsidRoot w:val="00A1B2C3"/><w:rsid w:val="00A1B2C3"/></w:rsids><m:mathPr><m:mathFont m:val="Cambria Math"/><m:smallFrac m:val="0"/></m:mathPr><w:themeFontLang w:val="pl-PL"/><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w14:docId w14:val="1A2B3C4D"/></w:settings>"#;
|
||||
|
||||
fn with_settings(settings: &str) -> Vec<u8> {
|
||||
let sources = format!(
|
||||
r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId9" Type="{REL}/mailMergeSource" Target="file:///__wordcraft_missing_source__/letters.xlsx" TargetMode="External"/></Relationships>"#
|
||||
);
|
||||
package(
|
||||
"<w:p><w:r><w:t>Text</w:t></w:r></w:p>",
|
||||
&[("rId1", &format!("{REL}/settings"), "settings.xml")],
|
||||
&[],
|
||||
&[("word/settings.xml", settings), ("word/_rels/settings.xml.rels", &sources)],
|
||||
)
|
||||
package("<w:p><w:r><w:t>Text</w:t></w:r></w:p>", &[("rId1", &format!("{REL}/settings"), "settings.xml")], &[], &[("word/settings.xml", settings)])
|
||||
}
|
||||
|
||||
fn pos(s: &str, needle: &str) -> usize {
|
||||
@@ -105,12 +97,11 @@ fn unmodelled_settings_survive_a_save_and_owned_ones_follow_the_model() {
|
||||
] {
|
||||
assert!(s.contains(kept), "{kept} lost: {s}");
|
||||
}
|
||||
// Owned: Track Changes was turned off; one compatibility mode. Mail merge keeps its external
|
||||
// source relationship.
|
||||
// Owned: Track Changes was turned off; one compatibility mode; the mail merge source (a
|
||||
// relationship that isn't carried) is dropped rather than left dangling.
|
||||
assert!(!s.contains("trackRevisions"), "{s}");
|
||||
assert_eq!(s.matches("compatibilityMode").count(), 1, "{s}");
|
||||
assert!(s.contains("mailMerge"), "{s}");
|
||||
assert!(text(&files, "word/_rels/settings.xml.rels").contains("file:///__wordcraft_missing_source__/letters.xlsx"));
|
||||
assert!(!s.contains("mailMerge") && !s.contains("rId9"), "{s}");
|
||||
// The privacy options are the model's (#1062): written once each, and gone when turned off.
|
||||
assert_eq!(s.matches("removePersonalInformation").count(), 1, "{s}");
|
||||
assert_eq!(s.matches("removeDateAndTime").count(), 1, "{s}");
|
||||
|
||||
@@ -16,8 +16,7 @@ mod objects;
|
||||
pub(crate) use header_footer::saved_copy;
|
||||
use header_footer::{create_hf, edit_hf, header_footer, new_empty_headers, strip_headers};
|
||||
pub use items::{
|
||||
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_at_in, format_date_in, format_date_parts,
|
||||
format_date_parts_in,
|
||||
DropCapState, default_date_picture, drop_cap_state, format_date, format_date_at, format_date_in, format_date_parts, format_date_parts_in,
|
||||
};
|
||||
use items::{cover_page, date_time, drop_cap, drop_cap_off, field, page_number, symbol};
|
||||
use links::{bookmark, delete_bookmark, link, link_targets};
|
||||
|
||||
@@ -188,30 +188,6 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether `story` is a header in a document of Word 2010's layout or older (compatibility mode
|
||||
/// below 15), whose text keeps its place beside the header's own floating objects (#6805).
|
||||
fn is_legacy_header(ctx: &Ctx, story: StoryRef) -> bool {
|
||||
ctx.doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT
|
||||
&& matches!(story, StoryRef::Part(id) if ctx.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::Header))
|
||||
}
|
||||
|
||||
/// Where a top and bottom object at `r` starts and ends for such a header.
|
||||
/// The distance below it counts (Word: 14.4 pt more for 14.4 pt); the one above neither moves it
|
||||
/// nor makes the header taller.
|
||||
fn legacy_reach_of(float: &wordcraft_doc::para::Float, r: Rect) -> Option<(f32, f32)> {
|
||||
let below = if float.dist_bottom.is_finite() { float.dist_bottom.clamp(0.0, 1584.0) } else { 0.0 };
|
||||
let bounds = float.spin().bounds(r);
|
||||
(float.wrap == Wrap::TopAndBottom).then_some((bounds.y, bounds.bottom() + below))
|
||||
}
|
||||
|
||||
/// The bottom of the lowest top and bottom object (`reach`) that starts above `text_bottom`, the
|
||||
/// end of the header's text with the space after its last paragraph (Word counts an object
|
||||
/// starting in it). Word also counts one starting a little further down (about 25 pt below one
|
||||
/// line of text), not modelled here. Zero when there is none.
|
||||
fn legacy_header_reach(text_bottom: f32, reach: &[(f32, f32)]) -> f32 {
|
||||
reach.iter().filter(|(top, _)| *top < text_bottom).map(|(_, bottom)| *bottom).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
/// Lay out a block list into a free-standing box of `width` (no page breaks): table cells,
|
||||
/// headers, footers, notes, text boxes. Returns items relative to (0, 0) and the height. `frame`
|
||||
/// says where the box sits on its page, for floating objects positioned relative to the page or
|
||||
@@ -241,14 +217,6 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
// bottom edge (#3108). Behind-text and in-front-of-text objects don't: a page-anchored logo or
|
||||
// watermark behind a cell's text must not stretch its row (see `align_h` in table.rs).
|
||||
let mut float_objects_bottom = 0.0f32;
|
||||
// A header in a document of Word 2010's layout or older (compatibility mode below 15): its
|
||||
// text keeps its place beside its own objects, which wrap nothing, and only a top and bottom
|
||||
// object reaching down from the text makes the header taller (#6805). Not in a table cell.
|
||||
let legacy_header = !in_cell && is_legacy_header(ctx, story);
|
||||
// Contour wraps were measured in mode 14; earlier modes keep using their existing rule.
|
||||
let legacy_header_contours = legacy_header && ctx.doc.settings.compat_mode == 14;
|
||||
// Top and bottom objects of such a header: where each starts and ends.
|
||||
let mut legacy_reach: Vec<(f32, f32)> = Vec::new();
|
||||
let mut table_areas = Vec::new();
|
||||
let mut page_table_wraps = Vec::new();
|
||||
let mut y = 0.0f32;
|
||||
@@ -339,15 +307,8 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
{
|
||||
r.x = keep_in_cell(r.x, r.w, left, right);
|
||||
}
|
||||
if (legacy_header && matches!(float.wrap, Wrap::TopAndBottom | Wrap::Square))
|
||||
|| (legacy_header_contours && matches!(float.wrap, Wrap::Tight | Wrap::Through))
|
||||
{
|
||||
// These objects do not reflow the legacy header's own text in Word.
|
||||
legacy_reach.extend(legacy_reach_of(float, r));
|
||||
} else {
|
||||
let outline = ctx.wrap_outline(o);
|
||||
excl.extend(wrap_area(r, float, outline.as_deref().map(Vec::as_slice)));
|
||||
}
|
||||
let outline = ctx.wrap_outline(o);
|
||||
excl.extend(wrap_area(r, float, outline.as_deref().map(Vec::as_slice)));
|
||||
floats.insert(oi, r);
|
||||
}
|
||||
let rel = rel_exclusions(&excl, 0.0, y);
|
||||
@@ -442,7 +403,6 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
|
||||
}
|
||||
}
|
||||
}
|
||||
y = y.max(legacy_header_reach(y, &legacy_reach));
|
||||
let floats_bottom = float_tables.iter().map(|r| r.bottom()).fold(float_objects_bottom, f32::max);
|
||||
ctx.hide_deleted = outer_hide;
|
||||
BoxLayout { items, height: y.max(0.0), floats_bottom, last_top: last_top.max(0.0), table_areas, page_table_wraps }
|
||||
|
||||
+25
-178
@@ -346,19 +346,10 @@ impl<'a> Flow<'a> {
|
||||
if !(rp.keep_lines || (rp.keep_next && pb.y + height <= pb.bottom + 0.01)) {
|
||||
return before;
|
||||
}
|
||||
// A paragraph closing a section that the next one starts on a new page keeps with
|
||||
// nothing: what follows is not on this page (Word ignores Keep with next there; measured for a next-page break, odd and even by analogy).
|
||||
let closes_page = pb.next_starts_page && self.p.section.is_some();
|
||||
let need = height
|
||||
+ if rp.keep_next && !closes_page {
|
||||
next_first_line(ctx, self.block, self.laid_width, 0, pb.next_starts_page, &mut ctx.counters.clone())
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let need = height + if rp.keep_next { next_first_line(ctx, self.block, self.width, 0, &mut ctx.counters.clone()) } else { 0.0 };
|
||||
// (Against the whole column: balanced columns grow to hold it.)
|
||||
// With the 0.01 pt of slack the other fit checks take. Balancing from Word 2013's layout
|
||||
// keeps the lines and the next paragraph together at the top of a column too (#6821).
|
||||
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
|
||||
// With the 0.01 pt of slack the other fit checks take.
|
||||
if pb.y + need > pb.bottom + 0.01 && !pb.fresh() && need <= pb.next_room(self.body_top) {
|
||||
pb.advance(self.block, self.body_top);
|
||||
pb.y += rp.space_before.min(0.0);
|
||||
return rp.space_before.min(0.0);
|
||||
@@ -366,25 +357,6 @@ impl<'a> Flow<'a> {
|
||||
before
|
||||
}
|
||||
|
||||
/// Balancing from Word 2013's layout, a paragraph that was moved to the top of a column by
|
||||
/// the lines before it (not by `keep_together`) keeps its lines, or itself with the next
|
||||
/// paragraph, together there too: asks again, and places the paragraph's floats again where it
|
||||
/// ends up (#6821).
|
||||
fn keep_again(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, rooms: Rooms) {
|
||||
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && pb.fresh() && Self::strict_widow_control(ctx, pb) {
|
||||
let (col, pages) = (pb.col, pb.pages.len());
|
||||
let before = self.keep_together(ctx, pb, rooms, 0.0);
|
||||
if (pb.col, pb.pages.len()) == (col, pages) {
|
||||
break;
|
||||
}
|
||||
// Reflow before testing the new column: wraps can change the paragraph's height.
|
||||
let y0 = pb.y;
|
||||
self.reanchor(ctx, pb, (y0, before), &[]);
|
||||
self.anchor_y = y0 - before;
|
||||
(self.rechecked, self.forced) = (false, Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines going into a new column (or page) were broken around the wrap areas where the
|
||||
/// paragraph started: break them again around this column's (the lines before stay as they
|
||||
/// were, and so do the paragraph's own floating objects), when they differ (#1374).
|
||||
@@ -475,19 +447,14 @@ impl<'a> Flow<'a> {
|
||||
fit
|
||||
}
|
||||
|
||||
/// Whether the line (the paragraph's line `l0`) may overflow the page: one holding nothing but
|
||||
/// a page or column break, with text after it in the paragraph, stays at the bottom of the
|
||||
/// page even when it doesn't fit (it only ends the page, and moving it would leave a blank
|
||||
/// page behind it, as in Word), and so does an empty paragraph closing a section before a new
|
||||
/// page (measured in Word: it stays on a full page instead of starting one of its own).
|
||||
/// Measured in Word: a paragraph of only a page break is an ordinary line, and when its mark's
|
||||
/// text doesn't fit it goes to the next page, blank page and all.
|
||||
/// Whether the line may overflow the page: one holding nothing but a page or column break stays
|
||||
/// at the bottom of the page even when it doesn't fit (it only ends the page, and moving it
|
||||
/// would leave a blank page behind it, as in Word), and so does an empty paragraph closing a
|
||||
/// section before a new page (measured in Word: it stays on a full page instead of starting
|
||||
/// one of its own).
|
||||
fn stays_at_bottom(&self, pb: &PageBuilder, l: ¶::Line) -> bool {
|
||||
let p = self.p;
|
||||
let mark_only_after =
|
||||
l.end == LineEnd::PageBreak && self.pl.lines.get(self.l0 + 1..).is_some_and(|rest| rest.iter().all(|m| only_markers(p, m.start..m.stop)));
|
||||
let only_break = matches!(l.end, LineEnd::PageBreak | LineEnd::ColumnBreak)
|
||||
&& !mark_only_after
|
||||
&& p.text
|
||||
.get(l.start..l.stop)
|
||||
.is_some_and(|t| t.chars().all(|c| matches!(c, wordcraft_doc::para::PAGE_BREAK | wordcraft_doc::para::COLUMN_BREAK)));
|
||||
@@ -510,46 +477,25 @@ impl<'a> Flow<'a> {
|
||||
|
||||
/// The end of the lines on this page after widow/orphan control, and keeping the rows beside
|
||||
/// floating objects together.
|
||||
/// Also says whether, balancing from Word 2013's layout, widow/orphan control alone moved every
|
||||
/// line back (the next column has them, #6821).
|
||||
fn settled_end(&self, ctx: &Ctx, pb: &PageBuilder, fit: &Fit) -> (usize, bool) {
|
||||
fn settled_end(&self, pb: &PageBuilder, fit: &Fit) -> usize {
|
||||
let (n, l0, mut l1) = (self.n(), self.l0, fit.l1);
|
||||
// Widow/orphan control (2-line minimum at either end). Balancing the columns of a
|
||||
// section's last page from Word 2013's layout (compatibility mode 15) applies it at the
|
||||
// top of a column too, where moving on is no loss, and never leaves one line of a
|
||||
// paragraph that goes on in the next column, even when the paragraph began in an earlier
|
||||
// one (#6821).
|
||||
let strict = Self::strict_widow_control(ctx, pb);
|
||||
// Widow/orphan control (2-line minimum at either end).
|
||||
if fit.forced.is_none() && l1 < n && self.pl.rp.widow_control && n >= 2 {
|
||||
if l1 - l0 == 1 && l0 == 0 && (!pb.fresh() || strict) {
|
||||
if l1 - l0 == 1 && l0 == 0 && !pb.fresh() {
|
||||
l1 = l0; // orphan: move the first line to the next page
|
||||
} else if n - l1 == 1 && (l1 - l0 >= 3 || (l0 > 0 && l1 - l0 >= 2)) {
|
||||
l1 -= 1; // widow: take one more line along
|
||||
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!pb.fresh() || strict) {
|
||||
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && !pb.fresh() {
|
||||
// Neither split of a three-line paragraph is allowed (two and a widow, or an
|
||||
// orphan and two): it moves whole, as in Word.
|
||||
l1 = l0;
|
||||
}
|
||||
// One line of a continued paragraph, with more after it (what was left of two lines
|
||||
// after the widow line went along included): the rest moves with it.
|
||||
if strict && l0 > 0 && l1 - l0 == 1 && l1 < n {
|
||||
l1 = l0;
|
||||
}
|
||||
}
|
||||
let moved_on = strict && fit.l1 > l0 && l1 == l0;
|
||||
// A row (text both sides of a floating object) stays together.
|
||||
while l1 > l0 && l1 < n && self.pl.lines.get(l1).is_some_and(|l| l.beside) {
|
||||
l1 -= 1;
|
||||
}
|
||||
(l1, moved_on)
|
||||
}
|
||||
|
||||
/// Whether the columns of this page are being balanced (`balance_columns`) and the document
|
||||
/// has Word 2013's layout: Word then keeps the lines of a paragraph together that widow or
|
||||
/// orphan control would split, at the top of a column as anywhere (#6821). Before compatibility
|
||||
/// mode 15 it splits them.
|
||||
fn strict_widow_control(ctx: &Ctx, pb: &PageBuilder) -> bool {
|
||||
ctx.doc.settings.compat_mode >= 15 && !pb.relaxed && pb.balance.is_some_and(|(page, _)| page + 1 == pb.pages.len())
|
||||
l1
|
||||
}
|
||||
|
||||
/// Nothing fits on this page: move to the next column or page, and place the floats again
|
||||
@@ -710,16 +656,16 @@ impl<'a> Flow<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Late floats placed for lines past `l1` wait for the next piece. An overflow line keeps
|
||||
/// its floats because it is still emitted here. Whether the lines from `l0` are to be broken
|
||||
/// again without the released floats. Does nothing once the wrap relays are used up
|
||||
/// Late floats placed for lines that went on after all (past `l1`) wait for the next piece;
|
||||
/// one whose own wrap pushed its line on stays, as before. Whether the lines from `l0` are to
|
||||
/// be broken again without them. Does nothing once the wrap relays are used up
|
||||
/// ([`MAX_WRAP_RELAYS`]).
|
||||
fn settle_late(&mut self, pb: &mut PageBuilder, l1: usize, overflow: bool) -> bool {
|
||||
fn settle_late(&mut self, pb: &mut PageBuilder, l1: usize) -> bool {
|
||||
let l0 = self.l0;
|
||||
if l0 == 0 || pb.web || self.late.placed.is_empty() || self.wrap_relays >= MAX_WRAP_RELAYS {
|
||||
return false;
|
||||
}
|
||||
let end = l1 + usize::from(overflow);
|
||||
let end = if l1 == l0 && pb.fresh() { l0 + 1 } else { l1 }; // what the overflow keeps
|
||||
let moved = self.late.release(self.p, &self.pl, end, &mut pb.excl) || self.late.keep_back(self.p, &self.pl, l0..end);
|
||||
moved && l1 > l0
|
||||
}
|
||||
@@ -904,7 +850,6 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
f.anchor_y = y0 - applied_before;
|
||||
}
|
||||
while f.l0 < f.n() {
|
||||
f.keep_again(ctx, pb, rooms);
|
||||
f.place_due_late(ctx, pb);
|
||||
f.relay_wrap(ctx, pb);
|
||||
f.relay_pages(ctx, pb);
|
||||
@@ -915,20 +860,12 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
|
||||
let lead = if f.l0 == 0 { first.top.max(0.0) + rooms.top } else { 0.0 };
|
||||
let notes = para_notes(ctx.doc, p, &f.pl);
|
||||
let mut fit = f.fit_lines(ctx, pb, ¬es, lead);
|
||||
let (end, widowed) = f.settled_end(ctx, pb, &fit);
|
||||
fit.l1 = end;
|
||||
// On a fresh column an unfitting line can overflow. Strict widow control instead moves
|
||||
// the lines on without emitting anything and must release their late floats as well.
|
||||
let overflow = end == f.l0 && pb.fresh() && !widowed;
|
||||
if f.settle_late(pb, end, overflow) {
|
||||
fit.l1 = f.settled_end(pb, &fit);
|
||||
if f.settle_late(pb, fit.l1) {
|
||||
continue;
|
||||
}
|
||||
if fit.l1 == f.l0 {
|
||||
// Balancing: widow/orphan control moved all the lines that fit on to the next column
|
||||
// (or, short of room, the page after, which fails the try), where the lines of a
|
||||
// column's first paragraph would otherwise overflow it. Lines pushed back for a row
|
||||
// beside a floating object keep the overflow as before.
|
||||
if !overflow {
|
||||
if !pb.fresh() {
|
||||
f.move_on(ctx, pb);
|
||||
continue;
|
||||
}
|
||||
@@ -1068,9 +1005,8 @@ fn space_after_kept(ctx: &Ctx, block: usize, rp: &wordcraft_doc::resolve::Resolv
|
||||
/// of a three-line one under that control (two would leave a widow), or all
|
||||
/// of it under keep lines together — or all of it and what it keeps with in turn when it is
|
||||
/// kept with the next too (a chain moves together in Word). Word carries a kept heading over
|
||||
/// when the paragraph after it cannot start on the page (#966). `new_page`: the next section starts
|
||||
/// on a new page, so the chain ends at the paragraph closing this one.
|
||||
fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_page: bool, counters: &mut Counters) -> f32 {
|
||||
/// when the paragraph after it cannot start on the page (#966).
|
||||
fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, counters: &mut Counters) -> f32 {
|
||||
match ctx.doc.body.get(block + 1).map(|b| &**b) {
|
||||
Some(Block::Para(p)) => {
|
||||
// Keep list indents and label metrics without consuming the document counters.
|
||||
@@ -1105,16 +1041,9 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
// Its border room, unless it joins the paragraph before (or after) in one box.
|
||||
let own = Edges::own(&pl, 0, pl.lines.len());
|
||||
let top = if joined(ctx.doc, &ctx.doc.body, block + 1, Some(block), None) { 0.0 } else { own.top };
|
||||
// The paragraph closing the section, when the next section starts a new page, keeps
|
||||
// with nothing on this page (Word ignores its Keep with next).
|
||||
if pl.rp.keep_next && depth < 8 && !(new_page && p.section.is_some()) {
|
||||
if pl.rp.keep_next && depth < 8 {
|
||||
let bottom = if joined(ctx.doc, &ctx.doc.body, block + 1, Some(block + 2), None) { 0.0 } else { own.bottom };
|
||||
pl.rp.space_before
|
||||
+ top
|
||||
+ pl.height
|
||||
+ bottom
|
||||
+ pl.rp.space_after
|
||||
+ next_first_line(ctx, block + 1, width, depth + 1, new_page, counters)
|
||||
pl.rp.space_before + top + pl.height + bottom + pl.rp.space_after + next_first_line(ctx, block + 1, width, depth + 1, counters)
|
||||
} else {
|
||||
// The room this one needs to start on the page with the kept paragraph before
|
||||
// it (#966).
|
||||
@@ -1138,85 +1067,3 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
|
||||
None => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use wordcraft_doc::Pos;
|
||||
use wordcraft_doc::para::{Anchor, Float, LINE_BREAK, Wrap, WrapText};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
|
||||
#[test]
|
||||
fn strict_balancing_remeasures_kept_lines_in_the_next_column() {
|
||||
crate::test_fonts();
|
||||
let mut doc = Document::new();
|
||||
doc.settings.compat_mode = 15;
|
||||
doc.last_section.columns.count = 2;
|
||||
let mut p = Paragraph::with_text("One two three four five six", Default::default());
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
p.props.keep_lines = Some(true);
|
||||
doc.body = vec![wordcraft_doc::para_block(p)];
|
||||
let p = doc.body[0].as_para().unwrap();
|
||||
|
||||
crate::pass::with_flow_page(&doc, |ctx, pb| {
|
||||
let top = pb.top;
|
||||
pb.balance = Some((0, 28.1));
|
||||
pb.cap_columns();
|
||||
// A preceding floating object leaves a narrow strip of the first column, but does
|
||||
// not occupy the second column. The same kept paragraph fits there in one line.
|
||||
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, false));
|
||||
place_para_in_flow(ctx, pb, p, 0, top);
|
||||
|
||||
assert_eq!(pb.pages.len(), 1, "a fitting candidate kept the balance attempt on its page");
|
||||
assert_eq!(pb.col, 1);
|
||||
assert!(
|
||||
pb.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.any(|item| { matches!(item, Placed::Lines { x, l0: 0, l1: 1, story: StoryRef::Body, .. } if (*x - pb.col_x()).abs() < 0.01) })
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_widow_control_releases_a_late_float_when_no_line_is_emitted() {
|
||||
crate::test_fonts();
|
||||
let mut doc = Document::new();
|
||||
doc.settings.compat_mode = 15;
|
||||
doc.last_section.columns.count = 2;
|
||||
let mut p = Paragraph::with_text(&format!("First{LINE_BREAK}Second{LINE_BREAK}Third"), Default::default());
|
||||
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
|
||||
p.props.widow_control = Some(true);
|
||||
doc.body = vec![wordcraft_doc::para_block(p)];
|
||||
let anchor = Pos::body(0, "First".len() + LINE_BREAK.len_utf8());
|
||||
let float = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
|
||||
doc.insert_object(&anchor, crate::tests::rect_shape(20.0, 20.0, float), &Default::default()).unwrap();
|
||||
let p = doc.body[0].as_para().unwrap();
|
||||
|
||||
crate::pass::with_flow_page(&doc, |ctx, pb| {
|
||||
let top = pb.top;
|
||||
let height = 14.1;
|
||||
pb.advance(0, top); // start in the last column of the previous page
|
||||
pb.bottom = top + height;
|
||||
pb.balance = Some((1, height));
|
||||
let mut flow = Flow::new(ctx, pb, p, (0, top));
|
||||
assert!(pb.excl.is_empty(), "the float waits for its anchor line");
|
||||
|
||||
// Continue after the first line. The balance attempt can fit only one of the two lines left.
|
||||
flow.l0 = 1;
|
||||
pb.advance(0, top);
|
||||
assert!(pb.fresh());
|
||||
assert!((pb.bottom - pb.top - height).abs() < 0.01);
|
||||
flow.place_due_late(ctx, pb);
|
||||
assert_eq!(pb.excl.len(), 1, "the anchor line fits before widow control");
|
||||
|
||||
let fit = flow.fit_lines(ctx, pb, &[], 0.0);
|
||||
assert_eq!(fit.l1, 2);
|
||||
let (end, widowed) = flow.settled_end(ctx, pb, &fit);
|
||||
assert_eq!((end, widowed), (1, true));
|
||||
let overflow = end == flow.l0 && pb.fresh() && !widowed;
|
||||
assert!(!flow.settle_late(pb, end, overflow));
|
||||
assert!(pb.excl.is_empty(), "no text is emitted here, so no wrap area may remain here");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,9 +71,6 @@ pub(crate) struct PageBuilder<'a> {
|
||||
/// Balancing columns: (page index, column height) — that page's columns end `height` below
|
||||
/// the top of the section on it.
|
||||
pub(crate) balance: Option<(usize, f32)>,
|
||||
/// Balancing without the strict widow/orphan and keep rules of Word 2013's layout (#6821): the
|
||||
/// last try when even the full column height does not hold the text with them.
|
||||
pub(crate) relaxed: bool,
|
||||
/// The page with the last explicit column break.
|
||||
pub(crate) col_break_page: Option<usize>,
|
||||
/// The section's footnotes go right below its text, not at the page bottom ...
|
||||
|
||||
@@ -856,11 +856,8 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec
|
||||
// keeps a hyphen and a number together (LB25), and when a slash and a letter follow
|
||||
// ("Dataprotection-" / "/Secrecyviolation", #3408), where LB13 forbids a break before the
|
||||
// slash: add those positions back. Word keeps "fitness-/1589" whole, so a slash before a digit
|
||||
// gains no break. Word also breaks between two hyphens in a row ("--------" is a ruled line
|
||||
// that wraps at any hyphen), where UAX #14 keeps them together (LB21): without it a row of
|
||||
// hyphens after a gap moves to the next line whole instead of filling the line first. Only
|
||||
// U+002D is added here; a non-breaking hyphen (U+2011) and a minus sign (U+2212) stay
|
||||
// unbreakable, and the other dashes keep their ordinary UAX #14 breaks.
|
||||
// gains no break. Only U+002D is added here; a non-breaking hyphen (U+2011) and a minus sign
|
||||
// (U+2212) stay unbreakable, and the other dashes keep their ordinary UAX #14 breaks.
|
||||
let hyphen_breaks: Vec<usize> = text
|
||||
.match_indices('-')
|
||||
.filter_map(|(pos, _)| {
|
||||
@@ -869,7 +866,6 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec
|
||||
match next.next() {
|
||||
Some(n) if n.is_ascii_digit() => Some(i),
|
||||
Some('/') => next.next().is_some_and(char::is_alphabetic).then_some(i),
|
||||
Some('-') => Some(i),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -225,7 +225,6 @@ fn new_page_builder<'p>(
|
||||
max_y: 0.0,
|
||||
content_bottom: 0.0,
|
||||
balance: None,
|
||||
relaxed: false,
|
||||
col_break_page: None,
|
||||
sect_beneath: false,
|
||||
beneath: false,
|
||||
@@ -237,18 +236,6 @@ fn new_page_builder<'p>(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn with_flow_page(doc: &Document, test: impl FnOnce(&mut Ctx<'_>, &mut PageBuilder<'_>)) {
|
||||
let mut cache = LayoutCache::new();
|
||||
let opts = LayoutOptions::default();
|
||||
let mut ctx = new_ctx(doc, &mut cache, &opts, (&HashMap::new(), None, &Totals::first_guess(1)));
|
||||
let sect = &doc.last_section;
|
||||
let early = EarlyFloats::new();
|
||||
let mut page = new_page_builder(sect, sect.page_num_format, &early, false, false);
|
||||
page.new_page(0, sect.margin_top);
|
||||
test(&mut ctx, &mut page);
|
||||
}
|
||||
|
||||
/// Endnotes in document order, with the section of their reference; placed at the end of a
|
||||
/// section that keeps them there, else at the end of the document.
|
||||
fn endnote_queue(ctx: &Ctx) -> VecDeque<(u32, usize)> {
|
||||
@@ -707,9 +694,7 @@ fn balance_pass<'a>(
|
||||
(page, top, h): (usize, f32, f32),
|
||||
body_top: f32,
|
||||
) -> bool {
|
||||
let relaxed = pb.relaxed;
|
||||
snap.restore(pb, ctx);
|
||||
pb.relaxed = relaxed;
|
||||
pb.balance = Some((page, h));
|
||||
pb.cap_columns();
|
||||
for block in first..end {
|
||||
@@ -788,26 +773,13 @@ fn balance_columns<'a>(ctx: &mut Ctx, pb: &mut PageBuilder<'a>, blocks: (usize,
|
||||
last = Some((mid, ok));
|
||||
}
|
||||
// End on the best height (the full column, as laid out first, when none was shorter).
|
||||
let mut fits = true;
|
||||
if last != Some((hi, true)) {
|
||||
thrown = discard(ctx);
|
||||
fits = pass(ctx, pb, hi);
|
||||
if !fits && hi < full {
|
||||
if !pass(ctx, pb, hi) && hi < full {
|
||||
thrown = discard(ctx);
|
||||
fits = pass(ctx, pb, full);
|
||||
pass(ctx, pb, full);
|
||||
}
|
||||
}
|
||||
// From Word 2013's layout the strict widow/orphan and keep rules (`Flow::strict_widow_control`)
|
||||
// can push text past even the full column (on a page whose columns are only a couple of lines
|
||||
// high, where moving a line on to the next column never helps). The layout first made, without
|
||||
// them, always fit it, so lay the page out as it was then rather than leave the pass that
|
||||
// spilled to a new page.
|
||||
if !fits {
|
||||
thrown = discard(ctx);
|
||||
pb.relaxed = true;
|
||||
pass(ctx, pb, full);
|
||||
pb.relaxed = false;
|
||||
}
|
||||
thrown
|
||||
}
|
||||
|
||||
|
||||
@@ -926,18 +926,6 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
|
||||
let own_depth = row.items.iter().filter_map(|it| if let Placed::Cell { table, .. } = it { Some(table.0.len()) } else { None }).min();
|
||||
// The first line of each paragraph that moves on (`l1` when all of them stay), by cell and
|
||||
// item.
|
||||
// The top of a cell's text on this page decides which paragraph starts the cell's part of the
|
||||
// page. Only text in the flow counts: a floating picture or shape anchored in the cell can sit
|
||||
// above it without the text being any less the first.
|
||||
let content_top = |it: &Placed| -> Option<f32> {
|
||||
if background(it) {
|
||||
return None;
|
||||
}
|
||||
if let Some((_, _, _, y)) = text_lines(it) {
|
||||
return Some(y);
|
||||
}
|
||||
it.turned_bounds().map(|r| r.y)
|
||||
};
|
||||
let splits: Vec<Vec<usize>> = cells
|
||||
.iter()
|
||||
.zip(&ends)
|
||||
@@ -945,18 +933,13 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
|
||||
// Where the cell's text ends: the paragraph ending lowest is the cell's last.
|
||||
let lowest =
|
||||
items.iter().filter_map(|it| text_lines(it).and_then(|(p, l0, l1, y)| crate::item_bottom(y, p, l0, l1))).fold(f32::MIN, f32::max);
|
||||
// The top of what the cell holds on this page: a paragraph there starts the cell's
|
||||
// part of the page, so a row that doesn't start below other content has nowhere to
|
||||
// move it to (see `line_split`).
|
||||
let cell_top = items.iter().filter_map(&content_top).fold(f32::MAX, f32::min);
|
||||
items
|
||||
.iter()
|
||||
.map(|it| {
|
||||
let Some((para, l0, l1, y)) = text_lines(it) else { return 0 };
|
||||
// The cell's last paragraph ends with the cell's content (its space after).
|
||||
let last = l1 == para.lines.len() && crate::item_bottom(y, para, l0, l1).is_some_and(|b| b >= lowest - 0.01);
|
||||
let first = !whole_cells && y <= cell_top + 0.01;
|
||||
line_split(para, (l0, l1), y, limit, end.filter(|_| last), first)
|
||||
line_split(para, (l0, l1), y, limit, end.filter(|_| last))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
@@ -1279,16 +1262,7 @@ fn text_lines(it: &Placed) -> Option<(&ParaLayout, usize, usize, f32)> {
|
||||
/// above `limit`: the last line of a cell's last paragraph needs room down to the cell's content
|
||||
/// `end`, its space after. Widow control keeps two lines on either side of the break, or moves
|
||||
/// the paragraph on whole.
|
||||
///
|
||||
/// `first`: the paragraph is the topmost content of its cell on a page the row doesn't start
|
||||
/// below other content on (the row continues from the page before, or starts the page). Moving
|
||||
/// it whole would gain nothing, and Word then splits it where the lines fall (measured with
|
||||
/// synthetic documents, Word for Windows 16.0, compatibility mode 15): a lone first line stays,
|
||||
/// and a three-line paragraph with room for two splits two and one, not leaving the first line
|
||||
/// alone (a continuation's lone line stays too). A paragraph of four lines or more still takes
|
||||
/// one more line along with its widow.
|
||||
/// Without this, nothing was kept and the row ran off the bottom of the page (#6823).
|
||||
fn line_split(para: &ParaLayout, (l0, l1): (usize, usize), y: f32, limit: f32, end: Option<f32>, first: bool) -> usize {
|
||||
fn line_split(para: &ParaLayout, (l0, l1): (usize, usize), y: f32, limit: f32, end: Option<f32>) -> usize {
|
||||
let n = para.lines.len();
|
||||
let mut k = l0;
|
||||
while k < l1 {
|
||||
@@ -1302,16 +1276,12 @@ fn line_split(para: &ParaLayout, (l0, l1): (usize, usize), y: f32, limit: f32, e
|
||||
// The body's rule differs: there a widow takes a line along only when three or more lines are
|
||||
// on the page (`place_para_in_flow`).
|
||||
if para.rp.widow_control && k > l0 && k < l1 {
|
||||
// A widow: take one more line along, unless that leaves nothing of a paragraph that
|
||||
// starts the page on it, or its first line alone.
|
||||
// A widow: take one more line along.
|
||||
if n - k == 1 {
|
||||
let taken = k - 1;
|
||||
if !(first && (taken <= l0 || (l0 == 0 && taken == 1))) {
|
||||
k = taken;
|
||||
}
|
||||
k -= 1;
|
||||
}
|
||||
// An orphan (the first line alone): the paragraph moves on whole.
|
||||
if l0 == 0 && k == 1 && !first {
|
||||
if l0 == 0 && k == 1 {
|
||||
k = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,13 +255,6 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
.rows
|
||||
.get(ri)
|
||||
.is_some_and(|r| r.props.cant_split || (r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
|
||||
// A Can't Split row (not an exact one) that is taller than a page splits where the page
|
||||
// ends, as in Word (measured with synthetic documents): it moves to a new page first
|
||||
// when it fits there, and only on a page it still doesn't fit does it break.
|
||||
let splits_when_too_tall = ri >= header_rows.len()
|
||||
&& t.rows
|
||||
.get(ri)
|
||||
.is_some_and(|r| r.props.cant_split && !(r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
|
||||
let mut rest: Option<table::RowLayout> = None;
|
||||
// On a new page holding only the repeated header rows.
|
||||
let mut fresh = false;
|
||||
@@ -297,9 +290,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
|
||||
// (#4272): moving on can give the cell room there.
|
||||
let first_part = rest.is_none() && !pb.at_top() && !fresh && !under_top_headers;
|
||||
let moves_on = first_part && short_of_min(ri, room);
|
||||
// A row that fits the room but for the border below it is still placed whole.
|
||||
let too_tall_to_keep = splits_when_too_tall && !first_part && cur.height > room + 0.01;
|
||||
let split = match ((splittable || too_tall_to_keep) && !moves_on && !defer_kept, first_part) {
|
||||
let split = match (splittable && !moves_on && !defer_kept, first_part) {
|
||||
(false, _) => None,
|
||||
(true, true) => split_keeping_nested(ctx.doc, cur, room),
|
||||
// On a fresh page, a nested row taller than the room splits rather than overflowing.
|
||||
|
||||
+1
-100
@@ -5,15 +5,12 @@ use wordcraft_doc::props::{Align, Border, BorderStyle, Borders, ParaProps, TextD
|
||||
use wordcraft_doc::{Pos, Table};
|
||||
|
||||
mod autospace;
|
||||
mod balanced_tail;
|
||||
mod bidi;
|
||||
mod budget;
|
||||
mod cell_floats;
|
||||
mod complex;
|
||||
mod float_top;
|
||||
mod grid;
|
||||
mod header_legacy_float;
|
||||
mod keep_next_section;
|
||||
mod ligature;
|
||||
pub(crate) mod linear;
|
||||
mod missing_glyphs;
|
||||
@@ -23,7 +20,6 @@ mod numeral;
|
||||
mod pages;
|
||||
mod styleref;
|
||||
mod table_contact;
|
||||
mod table_first_line;
|
||||
mod textbox;
|
||||
mod vertical;
|
||||
|
||||
@@ -4668,8 +4664,7 @@ fn tall_rows_split_across_pages() {
|
||||
.find_map(|i| if let Placed::Lines { path, para, .. } = i { (path.0 == vec![1, 0, 0, 0]).then_some(para.lines.len()) } else { None })
|
||||
.unwrap_or(0);
|
||||
assert_eq!(total, n);
|
||||
// A "can't split" row taller than a page splits too, from the top of a page, as in Word (#6823);
|
||||
// a shorter one moves on whole (`table_first_line`).
|
||||
// "Can't split" rows move whole instead.
|
||||
let mut d2 = Document::from_text("before\nafter");
|
||||
t.rows[0].props.cant_split = true;
|
||||
d2.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
|
||||
@@ -8028,46 +8023,6 @@ fn a_page_break_at_the_bottom_of_a_full_page_leaves_no_blank_page() {
|
||||
assert!(last_on_2, "the text after the break is on page 2");
|
||||
}
|
||||
|
||||
/// Measured in Word for Mac: a paragraph holding only a page break is an ordinary line. When it
|
||||
/// doesn't fit at the bottom of a full page it goes to the next one, and its break leaves that
|
||||
/// page blank. Only a break with text after it in its paragraph stays on the full page (#534).
|
||||
/// WordCraft kept both on the page, so a paper's references started a page early.
|
||||
#[test]
|
||||
fn a_paragraph_of_only_a_page_break_moves_when_it_does_not_fit() {
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let doc = |spacing: LineSpacing, room: f32, tail: &[&str]| {
|
||||
let para = |text: &str| {
|
||||
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
|
||||
p.mark = chr.clone();
|
||||
p.props = ParaProps { line_spacing: Some(spacing), space_before: Some(0.0), space_after: Some(0.0), ..Default::default() };
|
||||
wordcraft_doc::para_block(p)
|
||||
};
|
||||
let mut d = Document::new();
|
||||
d.body = (0..20).map(|i| para(&format!("Line {i}"))).chain(tail.iter().map(|t| para(t))).collect();
|
||||
let l = lay(&d);
|
||||
let pitch = l.caret(&Pos::body(1, 0)).unwrap().top - l.caret(&Pos::body(0, 0)).unwrap().top;
|
||||
d.last_section.margin_bottom = d.last_section.page_h - d.last_section.margin_top - 20.0 * pitch - room;
|
||||
d
|
||||
};
|
||||
let pages = |d: &Document| lay(d).pages.len();
|
||||
let single = {
|
||||
let l = lay(&doc(LineSpacing::Multiple(1.0), 600.0, &[]));
|
||||
l.caret(&Pos::body(1, 0)).unwrap().top - l.caret(&Pos::body(0, 0)).unwrap().top
|
||||
};
|
||||
let only = ["\u{000C}", "After"];
|
||||
let start = ["\u{000C}After"];
|
||||
// Exactly 24 pt lines, 10 pt left: the break's own paragraph moves, a blank page follows.
|
||||
assert_eq!(pages(&doc(LineSpacing::Exactly(24.0), 10.0, &only)), 3, "exact, break only");
|
||||
assert_eq!(pages(&doc(LineSpacing::Exactly(24.0), 10.0, &start)), 2, "exact, break before text");
|
||||
// Double spacing: the paragraph moves when its text cannot fit. Its leading can hang into
|
||||
// the bottom margin once the paragraph mark fits.
|
||||
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), single - 0.2, &only)), 3, "double, text doesn't fit");
|
||||
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), single + 0.2, &only)), 2, "double, leading hangs");
|
||||
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), 2.0 * single + 0.2, &only)), 2, "double, line fits");
|
||||
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), single - 0.2, &start)), 2, "double, break before text");
|
||||
}
|
||||
|
||||
/// #534: indents in characters (`w:firstLineChars`) are measured in the paragraph mark's font
|
||||
/// size and win over the indent in points.
|
||||
#[test]
|
||||
@@ -15250,60 +15205,6 @@ fn a_hyphen_before_a_slash_is_a_break_opportunity_like_word() {
|
||||
panic!("no width in the sweep wrapped the paragraph");
|
||||
}
|
||||
|
||||
/// A row of hyphens wraps at any hyphen in Word: after a gap, the row first fills the line and
|
||||
/// its rest goes on the next, where UAX #14 (LB21) keeps the hyphens together and the whole row
|
||||
/// moved to the next line. The first width that wraps must leave `Deed ` and part of the row on
|
||||
/// the first line. A row of non-breaking hyphens (U+2011) stays whole, so the first wrap moves it
|
||||
/// whole, breaking at the space.
|
||||
#[test]
|
||||
fn a_row_of_hyphens_wraps_at_any_hyphen_like_word() {
|
||||
let lines_of = |text: &str, margin_right: f32| -> Vec<String> {
|
||||
let mut d = Document::from_text(text);
|
||||
d.last_section.margin_right = margin_right;
|
||||
let l = lay(&d);
|
||||
l.pages[0]
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|it| {
|
||||
if let Placed::Lines { para, l0, l1, .. } = it {
|
||||
Some(para.lines[*l0..*l1].iter().map(|line| text[line.start..line.stop].to_string()).collect::<Vec<_>>())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
};
|
||||
|
||||
let text = format!("Deed {}", "-".repeat(16));
|
||||
let mut wrapped = false;
|
||||
for m in 100..=540 {
|
||||
let lines = lines_of(&text, m as f32);
|
||||
if lines.len() < 2 {
|
||||
continue; // still fits on one line at this width
|
||||
}
|
||||
assert!(lines[0].starts_with("Deed -"), "the first line takes part of the row: {lines:?}");
|
||||
assert!(lines[1].starts_with('-'), "the rest of the row follows: {lines:?}");
|
||||
assert_eq!(lines.concat(), text, "no hyphen is lost or added: {lines:?}");
|
||||
wrapped = true;
|
||||
break;
|
||||
}
|
||||
assert!(wrapped, "no width in the sweep wrapped the row of hyphens");
|
||||
|
||||
let row = "\u{2011}".repeat(16);
|
||||
let text = format!("Deed {row}");
|
||||
for m in 100..=540 {
|
||||
let lines = lines_of(&text, m as f32);
|
||||
if lines.len() < 2 {
|
||||
continue; // still fits on one line at this width
|
||||
}
|
||||
assert_eq!(lines[0], "Deed ", "the only break is at the space: {lines:?}");
|
||||
assert_eq!(lines[1], row, "the row of non-breaking hyphens stays whole: {lines:?}");
|
||||
return;
|
||||
}
|
||||
panic!("no width in the sweep wrapped the non-breaking row");
|
||||
}
|
||||
|
||||
/// docxide-pdf `dot-open-token*`: UAX #14 allows a break between a full stop and an opening
|
||||
/// parenthesis, Word doesn't. The first width that wraps `Deed 2023.(Example` breaks at the space.
|
||||
#[test]
|
||||
|
||||
@@ -1,376 +0,0 @@
|
||||
//! The last page of a section whose columns are balanced before a continuous break, when it holds
|
||||
//! only the end of a paragraph that began on the page before, or a whole paragraph of two or three
|
||||
//! lines (#6821). Measured in Word for Windows with exact 14 pt lines and no spacing, in three and
|
||||
//! in two columns, one case per document, saved as compatibility mode 15 and as 14: from mode 15
|
||||
//! Word keeps such lines together in the first column that can hold them (the later columns may be
|
||||
//! left short or empty), keeps a paragraph with "keep lines together" or "keep with next" whole
|
||||
//! there when those rules fit, including in a section that starts and ends on one page. In mode
|
||||
//! 14 Word splits two lines one per column. Synthetic tests also cover a footnote and a floating
|
||||
//! picture. Mode 14's other layouts (a three-line tail, two and one; the text after the section)
|
||||
//! and keep with next on the last lines of a paragraph that began on the page before remain open.
|
||||
use crate::*;
|
||||
use wordcraft_doc::para::{Anchor, Float, InlineObject, NoteKind, ShapeKind, Wrap};
|
||||
use wordcraft_doc::props::{LineSpacing, ParaProps};
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
use wordcraft_doc::{PartKind, Pos, para_block};
|
||||
|
||||
const LINE: f32 = 14.0;
|
||||
|
||||
fn lay(doc: &Document) -> DocLayout {
|
||||
let mut c = LayoutCache::new();
|
||||
layout(doc, &mut c, &LayoutOptions::default())
|
||||
}
|
||||
|
||||
fn para_with(text: &str, keep_lines: bool, keep_next: bool) -> Arc<Block> {
|
||||
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
|
||||
let mut p = Paragraph::with_text(text, chr);
|
||||
p.props = ParaProps {
|
||||
space_before: Some(0.0),
|
||||
space_after: Some(0.0),
|
||||
line_spacing: Some(LineSpacing::Exactly(LINE)),
|
||||
keep_lines: keep_lines.then_some(true),
|
||||
keep_next: keep_next.then_some(true),
|
||||
..Default::default()
|
||||
};
|
||||
para_block(p)
|
||||
}
|
||||
|
||||
fn para(text: &str) -> Arc<Block> {
|
||||
para_with(text, false, false)
|
||||
}
|
||||
|
||||
/// A paragraph of `k` lines, each ended by a line break: "P1", "P2"…
|
||||
fn lines_text(k: usize) -> String {
|
||||
(1..=k).map(|i| format!("P{i}")).collect::<Vec<_>>().join(&wordcraft_doc::para::LINE_BREAK.to_string())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Keep {
|
||||
No,
|
||||
Lines,
|
||||
Next,
|
||||
}
|
||||
|
||||
/// What follows the filler paragraphs: a paragraph of `k` lines ("P1"…), then optionally one more
|
||||
/// line ("Q1"), all in `cols` columns, then "After" in one column.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Case {
|
||||
cols: u32,
|
||||
/// How many one-line paragraphs come first, relative to the lines on a page: `-3` leaves room
|
||||
/// for three lines of the paragraph, `0` starts the paragraph on the next page, `1` puts one
|
||||
/// more line before it there. With `intro` it is the plain number of them.
|
||||
from_page_end: i32,
|
||||
k: usize,
|
||||
q: bool,
|
||||
compat: u32,
|
||||
/// A footnote referenced at the end of the paragraph.
|
||||
note: bool,
|
||||
/// A floating 28 pt tall picture-sized shape anchored in "Q1" (needs `q`).
|
||||
float: Option<Wrap>,
|
||||
/// This many lines of text and a one-column section break before the columns: the section
|
||||
/// starts mid-page and ends on the same page.
|
||||
intro: usize,
|
||||
/// Columns closed by a continuous break (balanced) or running to the end of the document.
|
||||
balanced: bool,
|
||||
keep: Keep,
|
||||
/// A page of this many lines of text (for a page too short for the rules).
|
||||
page_lines: Option<i32>,
|
||||
}
|
||||
|
||||
impl Case {
|
||||
fn new(cols: u32, from_page_end: i32, k: usize) -> Case {
|
||||
Case { cols, from_page_end, k, q: false, compat: 15, note: false, float: None, intro: 0, balanced: true, keep: Keep::No, page_lines: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The document of a case, the index of the `k`-line paragraph and of "Q1", and the offsets of the
|
||||
/// paragraph's lines.
|
||||
fn build(c: &Case) -> (Document, usize, Option<usize>, Vec<usize>) {
|
||||
crate::test_fonts();
|
||||
let mut d = Document::new();
|
||||
d.settings.compat_mode = c.compat;
|
||||
let mut s = SectionProps { start: SectionStart::Continuous, ..Default::default() };
|
||||
s.columns.count = c.cols;
|
||||
if let Some(n) = c.page_lines {
|
||||
s.page_h = s.margin_top + s.margin_bottom + n as f32 * LINE + 0.5;
|
||||
d.last_section.page_h = s.page_h;
|
||||
}
|
||||
let per_col = ((s.page_h - s.margin_top - s.margin_bottom) / LINE).floor() as i32;
|
||||
let fillers = if c.intro > 0 { c.from_page_end.max(0) } else { (per_col * c.cols as i32 + c.from_page_end).max(0) } as usize;
|
||||
let mut body: Vec<Arc<Block>> = (0..c.intro).map(|i| para(&format!("i{i}"))).collect();
|
||||
if c.intro > 0 {
|
||||
let mut one = SectionProps { start: SectionStart::Continuous, ..Default::default() };
|
||||
one.columns.count = 1;
|
||||
let mut mark = para("");
|
||||
if let Block::Para(p) = Arc::make_mut(&mut mark) {
|
||||
p.section = Some(Box::new(one));
|
||||
}
|
||||
body.push(mark);
|
||||
}
|
||||
body.extend((0..fillers).map(|i| para(&format!("r{i}"))));
|
||||
let first = body.len();
|
||||
let text = lines_text(c.k);
|
||||
body.push(para_with(&text, c.keep == Keep::Lines, c.keep == Keep::Next));
|
||||
let q = c.q.then_some(body.len());
|
||||
if c.q {
|
||||
body.push(para("Q1"));
|
||||
}
|
||||
let mark = body.len();
|
||||
if c.balanced {
|
||||
body.push(para(""));
|
||||
body.push(para("After"));
|
||||
}
|
||||
d.body = body;
|
||||
if c.balanced {
|
||||
if let Some(Block::Para(p)) = d.body.get_mut(mark).map(Arc::make_mut) {
|
||||
p.section = Some(Box::new(s));
|
||||
}
|
||||
d.last_section.start = SectionStart::Continuous;
|
||||
} else {
|
||||
d.last_section.columns.count = c.cols;
|
||||
}
|
||||
if let (Some(w), Some(qi)) = (c.float, q) {
|
||||
let float = Float { wrap: w, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 0.0, y: 0.0, ..Default::default() };
|
||||
let shape = InlineObject::Shape {
|
||||
kind: ShapeKind::Rectangle,
|
||||
w: if w == Wrap::TopAndBottom { 100.0 } else { 60.0 },
|
||||
h: 28.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float,
|
||||
story: None,
|
||||
freeform: None,
|
||||
effects: Default::default(),
|
||||
extra: Default::default(),
|
||||
};
|
||||
d.insert_object(&Pos::body(qi, 0), shape, &Default::default()).unwrap();
|
||||
}
|
||||
let breaks = text.char_indices().filter(|(_, ch)| *ch == wordcraft_doc::para::LINE_BREAK);
|
||||
let starts: Vec<usize> = std::iter::once(0).chain(breaks.map(|(i, ch)| i + ch.len_utf8())).collect();
|
||||
if c.note {
|
||||
let id = d.add_part(PartKind::Footnote, vec![para("Note")]);
|
||||
let end = text.len();
|
||||
d.insert_object(&Pos::body(first, end), InlineObject::NoteRef { kind: NoteKind::Footnote, id, custom: String::new() }, &Default::default())
|
||||
.unwrap();
|
||||
}
|
||||
(d, first, q, starts)
|
||||
}
|
||||
|
||||
/// The columns of the lines of the `k`-line paragraph (counted from the left, 0 to `cols - 1`),
|
||||
/// of "Q1" if there is one, and the number of pages.
|
||||
fn columns(c: &Case) -> (Vec<usize>, Option<usize>, usize) {
|
||||
let (d, first, q, starts) = build(c);
|
||||
let l = lay(&d);
|
||||
let carets: Vec<_> = starts.iter().map(|&o| l.caret(&Pos::body(first, o)).unwrap()).collect();
|
||||
let q_caret = q.map(|qi| l.caret(&Pos::body(qi, 0)).unwrap());
|
||||
// The columns' left edges, from the section's declared geometry so that an empty column keeps
|
||||
// its place. A line beside a float starts right of its column's edge, so a position is in the
|
||||
// last edge at or left of it.
|
||||
let sp = SectionProps::default();
|
||||
let n = c.cols.max(1);
|
||||
let width = (sp.page_w - sp.margin_left - sp.margin_right - sp.gutter - sp.columns.space * (n - 1) as f32) / n as f32;
|
||||
let xs: Vec<f32> = (0..n).map(|i| sp.margin_left + i as f32 * (width + sp.columns.space)).collect();
|
||||
let col = |x: f32| xs.iter().rposition(|e| *e <= x + 1.0).unwrap_or(usize::MAX);
|
||||
(carets.iter().map(|c| col(c.x)).collect(), q_caret.map(|c| col(c.x)), l.pages.len())
|
||||
}
|
||||
|
||||
fn of(c: &Case) -> Vec<usize> {
|
||||
columns(c).0
|
||||
}
|
||||
|
||||
// A: the last two lines of a paragraph whose first three lines closed the page before.
|
||||
#[test]
|
||||
fn the_last_two_lines_of_a_continued_paragraph_stay_in_the_first_column() {
|
||||
for cols in [3, 2] {
|
||||
let (v, _, pages) = columns(&Case::new(cols, -3, 5));
|
||||
assert_eq!(pages, 2, "{cols} columns");
|
||||
assert_eq!(v[3..], [0, 0], "{cols} columns: lines 4 and 5 together");
|
||||
}
|
||||
}
|
||||
|
||||
// B: three lines stay together too: not two and one, nor one and two.
|
||||
#[test]
|
||||
fn the_last_three_lines_of_a_continued_paragraph_stay_in_the_first_column() {
|
||||
for cols in [3, 2] {
|
||||
assert_eq!(of(&Case::new(cols, -3, 6))[3..], [0, 0, 0], "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// L: five lines are three and two (not two, one and two).
|
||||
#[test]
|
||||
fn the_last_five_lines_of_a_continued_paragraph_are_three_and_two() {
|
||||
for cols in [3, 2] {
|
||||
assert_eq!(of(&Case::new(cols, -3, 8))[3..], [0, 0, 0, 1, 1], "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// N: a one-line paragraph after the two lines goes to the second column.
|
||||
#[test]
|
||||
fn a_line_after_the_continued_two_lines_goes_to_the_next_column() {
|
||||
for cols in [3, 2] {
|
||||
let (v, q, _) = columns(&Case { q: true, ..Case::new(cols, -3, 5) });
|
||||
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// K, E: a paragraph of three lines (or two) that begins the last page stays together.
|
||||
#[test]
|
||||
fn a_whole_paragraph_of_two_or_three_lines_at_the_top_of_the_last_page_stays_together() {
|
||||
for cols in [3, 2] {
|
||||
assert_eq!(of(&Case::new(cols, 0, 3)), [0, 0, 0], "{cols} columns, three lines");
|
||||
assert_eq!(of(&Case::new(cols, 0, 2)), [0, 0], "{cols} columns, two lines");
|
||||
}
|
||||
}
|
||||
|
||||
// K2: the same after one line of another paragraph in the first column: it starts the second.
|
||||
#[test]
|
||||
fn a_three_line_paragraph_after_one_line_on_the_last_page_stays_together() {
|
||||
for cols in [3, 2] {
|
||||
let (v, _, pages) = columns(&Case::new(cols, 1, 3));
|
||||
assert_eq!((v, pages), (vec![1, 1, 1], 2), "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// F: with a footnote on the last page, referenced at the end of the paragraph.
|
||||
#[test]
|
||||
fn a_footnote_on_the_last_page_leaves_the_tail_together() {
|
||||
for cols in [3, 2] {
|
||||
let n = |off, k| of(&Case { note: true, ..Case::new(cols, off, k) });
|
||||
assert_eq!(n(-3, 5)[3..], [0, 0], "{cols} columns, two lines");
|
||||
assert_eq!(n(-3, 6)[3..], [0, 0, 0], "{cols} columns, three lines");
|
||||
assert_eq!(n(0, 2), [0, 0], "{cols} columns, whole paragraph of two lines");
|
||||
assert_eq!(n(0, 3), [0, 0, 0], "{cols} columns, whole paragraph of three lines");
|
||||
}
|
||||
}
|
||||
|
||||
// L2: beside a square-wrapped float in the next paragraph; a top-and-bottom one is the guard.
|
||||
#[test]
|
||||
fn a_square_wrapped_float_after_the_tail_leaves_it_together() {
|
||||
for cols in [3, 2] {
|
||||
let sq = |off, k| columns(&Case { q: true, float: Some(Wrap::Square), ..Case::new(cols, off, k) });
|
||||
let (v, q, _) = sq(-3, 5);
|
||||
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns, two lines");
|
||||
let (v, q, _) = sq(0, 3);
|
||||
assert_eq!((v, q), (vec![0, 0, 0], Some(1)), "{cols} columns, whole paragraph of three lines");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_and_bottom_float_after_the_tail_is_laid_out_as_before() {
|
||||
for cols in [3, 2] {
|
||||
let tb = |off, k| columns(&Case { q: true, float: Some(Wrap::TopAndBottom), ..Case::new(cols, off, k) });
|
||||
let (v, q, _) = tb(-3, 5);
|
||||
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns, two lines");
|
||||
let (v, q, _) = tb(0, 3);
|
||||
assert_eq!((v, q), (vec![0, 0, 0], Some(1)), "{cols} columns, whole paragraph of three lines");
|
||||
}
|
||||
}
|
||||
|
||||
// M: a section that starts and ends on one page (after two lines of text in one column).
|
||||
#[test]
|
||||
fn a_five_line_paragraph_balanced_mid_page_is_three_and_two() {
|
||||
assert_eq!(of(&Case { intro: 2, ..Case::new(3, 0, 5) }), [0, 0, 0, 1, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_section_balanced_mid_page_is_laid_out_as_before() {
|
||||
let mid = |cols, filler, k| of(&Case { intro: 2, ..Case::new(cols, filler, k) });
|
||||
assert_eq!(mid(3, 0, 2), [0, 0]);
|
||||
assert_eq!(mid(3, 0, 3), [0, 0, 0]);
|
||||
assert_eq!(mid(3, 0, 4), [0, 0, 1, 1]);
|
||||
assert_eq!(mid(3, 0, 6), [0, 0, 1, 1, 2, 2]);
|
||||
assert_eq!(mid(2, 0, 3), [0, 0, 0]);
|
||||
assert_eq!(mid(2, 0, 5), [0, 0, 0, 1, 1]);
|
||||
assert_eq!(mid(2, 0, 6), [0, 0, 0, 1, 1, 1]);
|
||||
// After one more line.
|
||||
assert_eq!(mid(3, 1, 3), [1, 1, 1]);
|
||||
assert_eq!(mid(3, 1, 4), [1, 1, 2, 2]);
|
||||
assert_eq!(mid(3, 1, 5), [0, 0, 1, 1, 1]);
|
||||
assert_eq!(mid(2, 1, 4), [0, 0, 1, 1]);
|
||||
assert_eq!(mid(2, 1, 6), [0, 0, 0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
// X: keep lines together, and keep with next, hold the paragraph whole in the first column.
|
||||
#[test]
|
||||
fn a_paragraph_kept_together_stays_whole_in_the_first_balanced_column() {
|
||||
for cols in [3, 2] {
|
||||
let kept = |off, k| of(&Case { keep: Keep::Lines, ..Case::new(cols, off, k) });
|
||||
assert_eq!(kept(0, 3), [0, 0, 0], "{cols} columns, three lines at the top");
|
||||
// Keep lines together moved it whole onto the last page.
|
||||
assert_eq!(kept(-3, 5), [0, 0, 0, 0, 0], "{cols} columns, five lines");
|
||||
assert_eq!(kept(-3, 6), [0, 0, 0, 0, 0, 0], "{cols} columns, six lines");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_kept_with_the_next_stays_with_it_in_the_first_balanced_column() {
|
||||
for cols in [3, 2] {
|
||||
let (v, q, _) = columns(&Case { keep: Keep::Next, q: true, ..Case::new(cols, 0, 3) });
|
||||
assert_eq!((v, q), (vec![0, 0, 0], Some(0)), "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// Guards, the same in Word and before the change.
|
||||
|
||||
// C, M: four lines are two and two, six are two, two and two.
|
||||
#[test]
|
||||
fn longer_tails_are_balanced_as_before() {
|
||||
for cols in [3, 2] {
|
||||
assert_eq!(of(&Case::new(cols, -3, 7))[3..], [0, 0, 1, 1], "{cols} columns, four lines");
|
||||
}
|
||||
assert_eq!(of(&Case::new(3, -3, 9))[3..], [0, 0, 1, 1, 2, 2], "three columns, six lines");
|
||||
}
|
||||
|
||||
// O: a four-line paragraph that begins the last page is two and two.
|
||||
#[test]
|
||||
fn a_four_line_paragraph_at_the_top_of_the_last_page_is_two_and_two() {
|
||||
for cols in [3, 2] {
|
||||
assert_eq!(of(&Case::new(cols, 0, 4)), [0, 0, 1, 1], "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// Columns not balanced (nothing follows them): the lines are not split without need.
|
||||
#[test]
|
||||
fn unbalanced_columns_keep_the_tail_in_the_first_column() {
|
||||
for cols in [3, 2] {
|
||||
let c = Case { balanced: false, ..Case::new(cols, -3, 5) };
|
||||
assert_eq!(of(&c)[3..], [0, 0], "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
// Before Word 2013's layout (mode 14) the two lines are split one per column, as Word does.
|
||||
#[test]
|
||||
fn mode_14_still_splits_the_last_two_lines_of_a_continued_paragraph() {
|
||||
for cols in [3, 2] {
|
||||
let c = Case { compat: 14, ..Case::new(cols, -3, 5) };
|
||||
assert_eq!(of(&c)[3..], [0, 1], "{cols} columns");
|
||||
}
|
||||
}
|
||||
|
||||
/// How many lines of body text are laid out, and on how many pages.
|
||||
fn shape(c: &Case) -> (usize, usize) {
|
||||
let (d, ..) = build(c);
|
||||
let l = lay(&d);
|
||||
let lines = l
|
||||
.pages
|
||||
.iter()
|
||||
.flat_map(|p| p.items.iter())
|
||||
.map(|it| match it {
|
||||
Placed::Lines { story: StoryRef::Body, l0, l1, .. } => l1 - l0,
|
||||
_ => 0,
|
||||
})
|
||||
.sum();
|
||||
(l.pages.len(), lines)
|
||||
}
|
||||
|
||||
// A page whose columns hold two lines is too short for the rules that keep three lines together:
|
||||
// not even the full column holds the paragraph with them, so the columns are laid out as before
|
||||
// (mode 14), with every line placed and no more pages.
|
||||
#[test]
|
||||
fn a_page_too_short_for_the_strict_rules_is_laid_out_as_in_mode_14() {
|
||||
let tiny = |compat| Case { compat, page_lines: Some(2), ..Case::new(2, 0, 3) };
|
||||
let (pages, lines) = shape(&tiny(14));
|
||||
assert!(lines >= 4, "the paragraph's three lines and After: {lines}");
|
||||
assert_eq!(shape(&tiny(15)), (pages, lines));
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
//! A header in a document of Word 2010's layout or older (compatibility mode below 15) keeps its
|
||||
//! text where it is beside its own floating objects, which wrap nothing there: a top and bottom
|
||||
//! object only makes the header taller when it starts above the end of the text (#6805). From
|
||||
//! Word 2013's layout (mode 15) the header's text goes below such an object.
|
||||
//!
|
||||
//! Measured in Word for Windows 16.0 on synthetic files (A4, Arial 10 pt, a header 17.3 pt down,
|
||||
//! 20 pt top margin or more, a text box 451.65 x 29.55 pt anchored to the header's paragraph and
|
||||
//! set 7.2 pt below its top, top and bottom wrapping, one line of text): at mode 14 the line stays
|
||||
//! at the header's top and the body's first line starts at 54.3 pt (the box's bottom, 54.05, and
|
||||
//! the line's rounding); at mode 15 the line goes below the box and the body starts at 65.9.
|
||||
//! A box set 78 pt below a 39 pt line changes nothing in either mode. A wrap distance below the
|
||||
//! box counts at both modes (14.4 pt: the body 14.4 pt lower), the one above changes nothing. A
|
||||
//! box starting in the space after the last paragraph makes the header end at its bottom. With
|
||||
//! three paragraphs and a box set 26 pt down the page, anchored in the second, no paragraph moves
|
||||
//! at mode 14 and the body starts at the box's bottom (55.9 pt). Square wrapping at mode 14 leaves
|
||||
//! the text as it is. Mode 11 (Word 2003's layout, measured on .doc files) behaves like 14: the
|
||||
//! single line stays at the top and the body starts at 54.0 pt (mode 12: 54.0, mode 14: 54.8), and
|
||||
//! no paragraph of the three-paragraph header moves. A 60 pt logo with Square, Tight or Through
|
||||
//! wrap leaves three short header paragraphs in place at mode 14. At mode 15 each line shifts
|
||||
//! right of the logo. Footers (which differ) and header table cells are outside this test.
|
||||
|
||||
use super::{lay, rect_shape};
|
||||
use crate::{DocLayout, Placed, StoryRef};
|
||||
use wordcraft_doc::para::{Anchor, Float, Wrap};
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::{Document, ParaProps, Paragraph, PartKind, Path, para_block};
|
||||
|
||||
const HEADER_TOP: f32 = 17.3;
|
||||
const BOX_H: f32 = 29.55;
|
||||
|
||||
/// A page whose header holds one line of text with a text-box-sized shape anchored to it, set
|
||||
/// `offset` below the paragraph's top with `wrap` (`None`: no shape), laid out as `mode` says.
|
||||
fn page(mode: u32, wrap: Option<Wrap>, offset: f32) -> DocLayout {
|
||||
page_with(mode, wrap, offset, (0.0, 0.0))
|
||||
}
|
||||
|
||||
/// [`page`] with a wrap distance below the object and a space after the header's paragraph.
|
||||
fn page_with(mode: u32, wrap: Option<Wrap>, offset: f32, (dist_bottom, after): (f32, f32)) -> DocLayout {
|
||||
crate::test_fonts();
|
||||
let mut d = Document::from_text("Body text.");
|
||||
d.settings.compat_mode = mode;
|
||||
d.last_section.header = HEADER_TOP;
|
||||
d.last_section.margin_top = 20.0;
|
||||
let mut p = Paragraph::with_text("Header line", Default::default());
|
||||
p.props = ParaProps { space_before: Some(0.0), space_after: Some(after), ..Default::default() };
|
||||
if let Some(wrap) = wrap {
|
||||
let float = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 31.6, y: offset, dist_bottom, ..Default::default() };
|
||||
p.insert_object(0, rect_shape(451.65, BOX_H, float), &Default::default()).unwrap();
|
||||
}
|
||||
let id = d.add_part(PartKind::Header, vec![para_block(p)]);
|
||||
d.last_section.headers.default = Some(id);
|
||||
lay(&d)
|
||||
}
|
||||
|
||||
fn body_top(l: &DocLayout) -> f32 {
|
||||
l.pages[0].items.iter().find_map(|i| if let Placed::Lines { y, story: StoryRef::Body, .. } = i { Some(*y) } else { None }).unwrap()
|
||||
}
|
||||
|
||||
fn header_line_top(l: &DocLayout) -> f32 {
|
||||
l.pages[0].header.iter().find_map(|i| if let Placed::Lines { y, story: StoryRef::Part(_), .. } = i { Some(*y) } else { None }).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_header_text_stays_beside_its_own_top_and_bottom_object() {
|
||||
let (old, new, none) = (page(14, Some(Wrap::TopAndBottom), 7.2), page(15, Some(Wrap::TopAndBottom), 7.2), page(14, None, 0.0));
|
||||
// The line stays at the header's top at mode 14, below the box at mode 15.
|
||||
assert!((header_line_top(&old) - header_line_top(&none)).abs() < 0.5, "line at {}", header_line_top(&old));
|
||||
assert!(header_line_top(&new) > HEADER_TOP + 7.2 + BOX_H - 0.5, "line at {}", header_line_top(&new));
|
||||
// The body starts below the box at mode 14 (it reaches past the text), a line lower at 15.
|
||||
assert!((body_top(&old) - (HEADER_TOP + 7.2 + BOX_H)).abs() < 0.5, "body at {}", body_top(&old));
|
||||
assert!(body_top(&new) > body_top(&old) + 5.0, "mode 15 body at {}, mode 14 at {}", body_top(&new), body_top(&old));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_object_set_below_the_header_text_adds_no_height() {
|
||||
// Starting 78 pt down, under the line: no room taken in either mode.
|
||||
let none = body_top(&page(14, None, 0.0));
|
||||
for mode in [14, 15] {
|
||||
let t = body_top(&page(mode, Some(Wrap::TopAndBottom), 78.0));
|
||||
assert!((t - none).abs() < 0.5, "mode {mode}: body at {t}, {none} without the object");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_square_object_leaves_header_text_and_height() {
|
||||
let (sq, none) = (page(14, Some(Wrap::Square), 7.2), page(14, None, 0.0));
|
||||
assert!((header_line_top(&sq) - header_line_top(&none)).abs() < 0.5, "line at {}", header_line_top(&sq));
|
||||
assert!((body_top(&sq) - body_top(&none)).abs() < 0.5, "body at {}, {} without", body_top(&sq), body_top(&none));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_header_text_ignores_a_narrow_logo_with_square_tight_or_through_wrap() {
|
||||
crate::test_fonts();
|
||||
let layout = |mode, wrap| {
|
||||
let mut d = Document::from_text("Body text.");
|
||||
d.settings.compat_mode = mode;
|
||||
d.last_section.header = 30.0;
|
||||
d.last_section.margin_top = 72.0;
|
||||
let mut blocks = Vec::new();
|
||||
for (i, text) in ["First line", "Second line", "Third line"].into_iter().enumerate() {
|
||||
let mut p = Paragraph::with_text(text, Default::default());
|
||||
p.props =
|
||||
ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(12.0)), ..Default::default() };
|
||||
if i == 0
|
||||
&& let Some(wrap) = wrap
|
||||
{
|
||||
let float = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, dist: 8.0, ..Default::default() };
|
||||
p.insert_object(0, rect_shape(60.0, 60.0, float), &Default::default()).unwrap();
|
||||
}
|
||||
blocks.push(para_block(p));
|
||||
}
|
||||
let id = d.add_part(PartKind::Header, blocks);
|
||||
d.last_section.headers.default = Some(id);
|
||||
lay(&d)
|
||||
};
|
||||
let header_positions = |layout: &DocLayout| {
|
||||
layout.pages[0]
|
||||
.header
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
Placed::Lines { x, y, para, l0, .. } => para.lines.get(*l0).map(|line| (x + line.left, *y)),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for mode in [11, 12, 13, 14, 15] {
|
||||
let plain = layout(mode, None);
|
||||
let control = header_positions(&plain);
|
||||
assert_eq!(control.len(), 3);
|
||||
for wrap in [Wrap::Square, Wrap::Tight, Wrap::Through] {
|
||||
let with_logo = layout(mode, Some(wrap));
|
||||
let positions = header_positions(&with_logo);
|
||||
assert_eq!(positions.len(), control.len(), "mode {mode}, {wrap:?}: {positions:?}");
|
||||
for (&(x, y), &(plain_x, plain_y)) in positions.iter().zip(&control) {
|
||||
assert!((y - plain_y).abs() < 0.5, "mode {mode}, {wrap:?}: line moved vertically from {plain_y} to {y}");
|
||||
if mode == 14 || (mode < 14 && wrap == Wrap::Square) {
|
||||
assert!((x - plain_x).abs() < 0.5, "mode {mode}, {wrap:?}: line moved from {plain_x} to {x}");
|
||||
} else {
|
||||
assert!(x > plain_x + 59.5, "mode {mode}, {wrap:?}: line at {x} does not clear the logo");
|
||||
}
|
||||
}
|
||||
assert!((body_top(&with_logo) - body_top(&plain)).abs() < 0.5, "mode {mode}, {wrap:?}: body moved vertically");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_body_text_still_goes_below_its_own_top_and_bottom_object() {
|
||||
crate::test_fonts();
|
||||
let top = |mode| {
|
||||
let mut d = Document::from_text("Body text.");
|
||||
d.settings.compat_mode = mode;
|
||||
d.last_section.margin_top = 20.0;
|
||||
let float = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 31.6, y: 7.2, ..Default::default() };
|
||||
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
|
||||
p.insert_object(0, rect_shape(451.65, BOX_H, float), &Default::default()).unwrap();
|
||||
body_top(&lay(&d))
|
||||
};
|
||||
let (old, new) = (top(14), top(15));
|
||||
assert!((old - new).abs() < 0.5 && old > 20.0 + 7.2 + BOX_H - 0.5, "mode 14 body line at {old}, mode 15 at {new}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_distance_below_the_object_counts_and_a_start_in_the_space_after_extends() {
|
||||
// Word: 14.4 pt below the box make the body 14.4 pt lower.
|
||||
let (plain, spaced) = (body_top(&page(14, Some(Wrap::TopAndBottom), 7.2)), body_top(&page_with(14, Some(Wrap::TopAndBottom), 7.2, (14.4, 0.0))));
|
||||
assert!((spaced - plain - 14.4).abs() < 0.5, "body at {spaced}, {plain} without the distance");
|
||||
// A box starting 15 pt down, past the 11.5 pt line but inside its 10 pt space after: the
|
||||
// header ends at the box's bottom (Word: 62.1 from the page's top).
|
||||
let inside = page_with(14, Some(Wrap::TopAndBottom), 15.0, (0.0, 10.0));
|
||||
assert!((body_top(&inside) - (HEADER_TOP + 15.0 + BOX_H)).abs() < 0.5, "body at {}", body_top(&inside));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_14_no_header_paragraph_moves_for_an_object_set_down_the_page_from_the_second() {
|
||||
crate::test_fonts();
|
||||
let lines = |mode: u32, object: bool| {
|
||||
let mut d = Document::from_text("Body text.");
|
||||
d.settings.compat_mode = mode;
|
||||
d.last_section.header = HEADER_TOP;
|
||||
d.last_section.margin_top = 20.0;
|
||||
let tight = ParaProps { space_before: Some(0.0), space_after: Some(0.0), ..Default::default() };
|
||||
let mut blocks = Vec::new();
|
||||
for (i, t) in ["First line", "Second line", "Third line"].into_iter().enumerate() {
|
||||
let mut p = Paragraph::with_text(t, Default::default());
|
||||
p.props = tight.clone();
|
||||
if object && i == 1 {
|
||||
let float = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Page, v_rel: Anchor::Page, x: 72.0, y: 60.0, ..Default::default() };
|
||||
p.insert_object(0, rect_shape(451.65, BOX_H, float), &Default::default()).unwrap();
|
||||
}
|
||||
blocks.push(para_block(p));
|
||||
}
|
||||
let id = d.add_part(PartKind::Header, blocks);
|
||||
d.last_section.headers.default = Some(id);
|
||||
let l = lay(&d);
|
||||
let tops: Vec<f32> = l.pages[0].header.iter().filter_map(|i| if let Placed::Lines { y, .. } = i { Some(*y) } else { None }).collect();
|
||||
(tops, body_top(&l))
|
||||
};
|
||||
let ((plain, _), (with, body)) = (lines(14, false), lines(14, true));
|
||||
assert_eq!(plain.len(), with.len());
|
||||
for (a, b) in plain.iter().zip(&with) {
|
||||
assert!((a - b).abs() < 0.5, "header lines at {with:?}, {plain:?} without the object");
|
||||
}
|
||||
// The box is 60 pt down the page, over the third line (the test font's lines are taller than
|
||||
// Word's 11.5 pt, so the box is set lower than the 26 pt measured): the body starts at its bottom.
|
||||
assert!((body - (60.0 + BOX_H)).abs() < 0.5, "body at {body}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_11_header_text_stays_beside_its_own_top_and_bottom_object_like_mode_14() {
|
||||
// Word: modes 11, 12 and 14 keep the line at the header's top; mode 15 moves it below the box.
|
||||
let (m11, m12, m14, m15) = (
|
||||
page(11, Some(Wrap::TopAndBottom), 7.2),
|
||||
page(12, Some(Wrap::TopAndBottom), 7.2),
|
||||
page(14, Some(Wrap::TopAndBottom), 7.2),
|
||||
page(15, Some(Wrap::TopAndBottom), 7.2),
|
||||
);
|
||||
for l in [&m11, &m12] {
|
||||
assert!((header_line_top(l) - header_line_top(&m14)).abs() < 0.5, "line at {}, {} at mode 14", header_line_top(l), header_line_top(&m14));
|
||||
assert!((body_top(l) - body_top(&m14)).abs() < 0.5, "body at {}, {} at mode 14", body_top(l), body_top(&m14));
|
||||
}
|
||||
assert!(header_line_top(&m15) > header_line_top(&m11) + 5.0, "mode 15 line at {}, mode 11 at {}", header_line_top(&m15), header_line_top(&m11));
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
//! Keep with next on the paragraph that closes a section (#6834). When the next section starts
|
||||
//! on a new page, the paragraph after it is not on this page, so Keep with next has nothing to
|
||||
//! keep it with: it stays at the bottom of its page. Moving it over for want of the next
|
||||
//! section's first line left a page holding only that section's paragraph. Only a next-page
|
||||
//! break was measured in Word; odd-page and even-page breaks follow by analogy (not measured).
|
||||
//! Fixed page size and exact line heights, so no font metrics are assumed. Invented text only.
|
||||
|
||||
use crate::*;
|
||||
use wordcraft_doc::props::LineSpacing;
|
||||
use wordcraft_doc::section::{SectionProps, SectionStart};
|
||||
use wordcraft_doc::{ParaProps, Paragraph};
|
||||
|
||||
fn lay(doc: &Document) -> DocLayout {
|
||||
let mut c = LayoutCache::new();
|
||||
layout(doc, &mut c, &LayoutOptions::default())
|
||||
}
|
||||
|
||||
/// A 400 x 300 pt page with 50 pt margins: 200 pt of body, ten 20 pt lines.
|
||||
fn small_page(start: SectionStart) -> SectionProps {
|
||||
SectionProps {
|
||||
start,
|
||||
page_w: 400.0,
|
||||
page_h: 300.0,
|
||||
margin_top: 50.0,
|
||||
margin_bottom: 50.0,
|
||||
margin_left: 50.0,
|
||||
margin_right: 50.0,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn exact(text: &str, height: f32, keep: bool) -> Paragraph {
|
||||
let mut p = Paragraph::with_text(text, Default::default());
|
||||
p.props = ParaProps {
|
||||
line_spacing: Some(LineSpacing::Exactly(height)),
|
||||
space_before: Some(0.0),
|
||||
space_after: Some(0.0),
|
||||
keep_next: keep.then_some(true),
|
||||
..Default::default()
|
||||
};
|
||||
p
|
||||
}
|
||||
|
||||
/// `filler` exact 20 pt paragraphs, then the closing paragraph (15 pt, block index `filler`,
|
||||
/// kept with the next when `keep`), then one 20 pt paragraph. When `closes`, the closing
|
||||
/// paragraph ends section one and the second section starts as `start`; otherwise the second
|
||||
/// paragraph is in the same section.
|
||||
fn build(filler: usize, keep: bool, start: SectionStart, closes: bool, empty: bool) -> Document {
|
||||
let mut d = Document::new();
|
||||
d.body.clear();
|
||||
for i in 0..filler {
|
||||
d.body.push(wordcraft_doc::para_block(exact(&format!("Filler line {i}"), 20.0, false)));
|
||||
}
|
||||
let mut last = exact(if empty { "" } else { "Closing paragraph of the first part" }, 15.0, keep);
|
||||
if closes {
|
||||
last.section = Some(Box::new(small_page(SectionStart::NextPage)));
|
||||
}
|
||||
d.body.push(wordcraft_doc::para_block(last));
|
||||
d.body.push(wordcraft_doc::para_block(exact("First paragraph of the second part", 20.0, false)));
|
||||
d.last_section = small_page(if closes { start } else { SectionStart::NextPage });
|
||||
d
|
||||
}
|
||||
|
||||
/// The page (0-based) that holds the body paragraph `block`.
|
||||
fn page_of(l: &DocLayout, block: u32) -> Option<usize> {
|
||||
l.pages.iter().position(|p| p.items.iter().any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if path.0 == [block])))
|
||||
}
|
||||
|
||||
const NEXT_BREAKS: [SectionStart; 3] = [SectionStart::NextPage, SectionStart::OddPage, SectionStart::EvenPage];
|
||||
|
||||
/// The issue's case: nine 20 pt lines, an empty 15 pt kept closing paragraph that fits at the
|
||||
/// bottom (195 of 200 pt) while the next section's first line (20 pt) would not, then one
|
||||
/// paragraph of the next section. Two pages, none empty.
|
||||
#[test]
|
||||
fn an_empty_kept_closing_paragraph_leaves_no_empty_page() {
|
||||
crate::test_fonts();
|
||||
let l = lay(&build(9, true, SectionStart::NextPage, true, true));
|
||||
assert_eq!(l.pages.len(), 2);
|
||||
assert_eq!(page_of(&l, 9), Some(0), "the closing paragraph moved to the next page");
|
||||
assert_eq!(page_of(&l, 10), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_closing_paragraph_stays_on_its_page_and_adds_no_page() {
|
||||
crate::test_fonts();
|
||||
for start in NEXT_BREAKS {
|
||||
for empty in [true, false] {
|
||||
for n in 0..25 {
|
||||
let kept = lay(&build(n, true, start, true, empty));
|
||||
let plain = lay(&build(n, false, start, true, empty));
|
||||
assert_eq!(kept.pages.len(), plain.pages.len(), "{start:?}, {n} filler paragraphs, empty {empty}: keep with next added a page");
|
||||
assert_eq!(page_of(&kept, n as u32), page_of(&plain, n as u32), "{start:?}, {n} filler paragraphs, empty {empty}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_with_next_still_moves_an_ordinary_paragraph_with_its_next_line() {
|
||||
crate::test_fonts();
|
||||
// No section ends here: the 15 pt paragraph fits (195 of 200 pt) but the 20 pt one after it
|
||||
// does not, so the pair goes to page 2 together.
|
||||
let kept = lay(&build(9, true, SectionStart::NextPage, false, false));
|
||||
let plain = lay(&build(9, false, SectionStart::NextPage, false, false));
|
||||
assert_eq!(page_of(&plain, 9), Some(0));
|
||||
assert_eq!(page_of(&kept, 9), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keep_with_next_before_a_continuous_section_still_keeps_with_its_next_line() {
|
||||
crate::test_fonts();
|
||||
// The next section continues on this page, so its first line is what the paragraph keeps
|
||||
// with (not measured in Word; the earlier behaviour stays).
|
||||
let kept = lay(&build(9, true, SectionStart::Continuous, true, false));
|
||||
let plain = lay(&build(9, false, SectionStart::Continuous, true, false));
|
||||
assert_eq!(page_of(&plain, 9), Some(0));
|
||||
assert_eq!(page_of(&kept, 9), Some(1));
|
||||
}
|
||||
@@ -1,294 +0,0 @@
|
||||
//! A paragraph that starts a cell's part of a page, in a row split across pages, is split where
|
||||
//! its lines fall, as in Word (#6823): moving it on whole would gain nothing, and keeping
|
||||
//! widow/orphan control left the cell with nothing on the page, so the row was placed whole and
|
||||
//! ran off the bottom. A paragraph below other content of its cell keeps the rule, and so does a
|
||||
//! row that starts below other content of the page. A "can't split" row taller than a page
|
||||
//! splits too.
|
||||
//!
|
||||
//! The expectations were measured in Word for Windows 16.0 (compatibility mode 15, widow control
|
||||
//! on, Letter with 1 inch margins) on synthetic documents laid out like these.
|
||||
use crate::*;
|
||||
use wordcraft_doc::para::{Anchor, Float, InlineObject, Wrap};
|
||||
use wordcraft_doc::props::{LineSpacing, ParaProps};
|
||||
use wordcraft_doc::{Table, para_block};
|
||||
|
||||
fn lay(doc: &Document) -> DocLayout {
|
||||
let mut c = LayoutCache::new();
|
||||
layout(doc, &mut c, &LayoutOptions::default())
|
||||
}
|
||||
|
||||
fn exact(height: f32, widow: bool) -> ParaProps {
|
||||
ParaProps {
|
||||
line_spacing: Some(LineSpacing::Exactly(height)),
|
||||
space_before: Some(0.0),
|
||||
space_after: Some(0.0),
|
||||
widow_control: Some(widow),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn lines_para(lines: usize, height: f32, widow: bool, name: &str) -> Arc<Block> {
|
||||
para_block(lines_paragraph(lines, height, widow, name))
|
||||
}
|
||||
|
||||
fn lines_paragraph(lines: usize, height: f32, widow: bool, name: &str) -> Paragraph {
|
||||
let text: Vec<String> = (1..=lines).map(|i| format!("{name}{i}")).collect();
|
||||
let mut p = Paragraph::with_text(&text.join(&wordcraft_doc::para::LINE_BREAK.to_string()), Default::default());
|
||||
p.props = exact(height, widow);
|
||||
p
|
||||
}
|
||||
|
||||
/// What the table is made of: `pre` one-line paragraphs of 16 pt before it, an optional repeated
|
||||
/// header row, a row (can't split or not) whose second cell holds `fill` lines of `fill_height`,
|
||||
/// the paragraphs `before` (lines and line height) and last a paragraph `last` of lines of a
|
||||
/// height. The last two are inside a nested table when `nested` is set.
|
||||
struct Case {
|
||||
pre: usize,
|
||||
header: bool,
|
||||
cant_split: bool,
|
||||
nested: bool,
|
||||
fill: usize,
|
||||
fill_height: f32,
|
||||
before: Vec<(usize, f32)>,
|
||||
last: (usize, f32),
|
||||
widow: bool,
|
||||
/// A picture floating through the text, anchored in the last paragraph and placed above it.
|
||||
float_above: bool,
|
||||
}
|
||||
|
||||
impl Case {
|
||||
fn new(last: (usize, f32)) -> Case {
|
||||
Case {
|
||||
pre: 0,
|
||||
header: false,
|
||||
cant_split: false,
|
||||
nested: false,
|
||||
fill: 45,
|
||||
fill_height: 14.0,
|
||||
before: Vec::new(),
|
||||
last,
|
||||
widow: true,
|
||||
float_above: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines of the last paragraph on each page.
|
||||
fn per_page(&self) -> Vec<usize> {
|
||||
crate::test_fonts();
|
||||
let w = self.widow;
|
||||
let mut d = Document::from_text("After");
|
||||
for i in 0..self.pre {
|
||||
let mut p = Paragraph::with_text(&format!("F{i}"), Default::default());
|
||||
p.props = exact(16.0, w);
|
||||
d.insert_block(StoryRef::Body, &Path::top(i), Block::Para(p)).unwrap();
|
||||
}
|
||||
let mut t = Table::new(1 + usize::from(self.header), 2, 400.0);
|
||||
t.props.cell_margins = Some([0.0, 5.4, 0.0, 5.4]);
|
||||
let row = usize::from(self.header);
|
||||
if self.header {
|
||||
t.rows[0].props.header = true;
|
||||
for c in &mut t.rows[0].cells {
|
||||
c.blocks = vec![lines_para(1, 14.0, w, "H")];
|
||||
}
|
||||
}
|
||||
t.rows[row].props.cant_split = self.cant_split;
|
||||
let mut inner: Vec<Arc<Block>> = self.before.iter().map(|&(n, h)| lines_para(n, h, w, "P")).collect();
|
||||
let mut last = lines_paragraph(self.last.0, self.last.1, w, "B");
|
||||
if self.float_above {
|
||||
let float = Float { wrap: Wrap::Through, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 250.0, y: -6.0, ..Default::default() };
|
||||
let picture = InlineObject::Image {
|
||||
media: "float".into(),
|
||||
w: 20.0,
|
||||
h: 20.0,
|
||||
alt: "float".into(),
|
||||
float,
|
||||
crop: [0.0; 4],
|
||||
fx: Default::default(),
|
||||
ole: None,
|
||||
};
|
||||
last.insert_object(0, picture, &Default::default()).unwrap();
|
||||
}
|
||||
inner.push(para_block(last));
|
||||
// Without a fill paragraph the cell starts with `inner`.
|
||||
let mut blocks = if self.fill > 0 { vec![lines_para(self.fill, self.fill_height, w, "A")] } else { Vec::new() };
|
||||
let mut at = vec![self.pre as u32, row as u32, 1, (blocks.len() + inner.len()) as u32 - 1];
|
||||
if self.nested {
|
||||
let mut nested = Table::new(1, 1, 200.0);
|
||||
nested.rows[0].cells[0].blocks = inner.clone();
|
||||
at = vec![self.pre as u32, row as u32, 1, blocks.len() as u32, 0, 0, inner.len() as u32 - 1];
|
||||
blocks.push(Arc::new(Block::Table(nested)));
|
||||
blocks.push(lines_para(1, 1.0, w, "Z"));
|
||||
} else {
|
||||
blocks.extend(inner);
|
||||
}
|
||||
t.rows[row].cells[1].blocks = blocks;
|
||||
d.insert_block(StoryRef::Body, &Path::top(self.pre), Block::Table(t)).unwrap();
|
||||
lay(&d)
|
||||
.pages
|
||||
.iter()
|
||||
.map(|p| {
|
||||
p.items
|
||||
.iter()
|
||||
.filter_map(|it| match it {
|
||||
Placed::Lines { path, l0, l1, .. } if path.0 == at => Some(l1 - l0),
|
||||
_ => None,
|
||||
})
|
||||
.sum()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A three-line paragraph at the top of a page with room for its first line only keeps that line
|
||||
/// there (the next two go on, one to a page here).
|
||||
#[test]
|
||||
fn a_first_line_alone_at_the_top_of_a_page_stays_in_a_split_row() {
|
||||
assert_eq!(Case::new((3, 400.0)).per_page(), vec![0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
/// Two lines, room for one: one and one.
|
||||
#[test]
|
||||
fn a_two_line_paragraph_at_the_top_of_a_page_splits_one_and_one() {
|
||||
assert_eq!(Case::new((2, 400.0)).per_page(), vec![0, 1, 1]);
|
||||
}
|
||||
|
||||
/// Three lines, room for two: two and one (not the whole paragraph on, which is no better at the
|
||||
/// top of a page, and not one and two).
|
||||
#[test]
|
||||
fn a_three_line_paragraph_at_the_top_of_a_page_with_room_for_two_splits_two_and_one() {
|
||||
assert_eq!(Case::new((3, 300.0)).per_page(), vec![0, 2, 1]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): four lines with room for three still keep two for the widow.
|
||||
#[test]
|
||||
fn four_lines_at_the_top_of_a_page_with_room_for_three_still_keep_two_for_the_widow() {
|
||||
assert_eq!(Case::new((4, 200.0)).per_page(), vec![0, 2, 2]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): a paragraph below another one of its cell on the page keeps
|
||||
/// the orphan rule, so its single line there moves on with the rest.
|
||||
#[test]
|
||||
fn a_paragraph_below_other_content_of_its_cell_still_moves_on_whole_instead_of_an_orphan() {
|
||||
let mut c = Case::new((3, 200.0));
|
||||
c.before = vec![(1, 300.0)];
|
||||
assert_eq!(c.per_page(), vec![0, 0, 3]);
|
||||
}
|
||||
|
||||
/// Where only the later paragraphs of a cell continue, the one that moved to the top of a page
|
||||
/// splits at its lines (two and one), the paragraph before it having stayed.
|
||||
#[test]
|
||||
fn a_later_paragraph_moved_to_the_top_of_a_page_splits_where_its_lines_fall() {
|
||||
let mut c = Case::new((3, 300.0));
|
||||
c.before = vec![(1, 100.0)];
|
||||
assert_eq!(c.per_page(), vec![0, 0, 2, 1]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): four lines below a paragraph, room for three, keep two.
|
||||
#[test]
|
||||
fn four_lines_below_other_content_with_room_for_three_still_keep_two_for_the_widow() {
|
||||
let mut c = Case::new((4, 200.0));
|
||||
c.before = vec![(1, 40.0)];
|
||||
assert_eq!(c.per_page(), vec![0, 2, 2]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): without widow control the paragraph always split where it fell.
|
||||
#[test]
|
||||
fn without_widow_control_the_lines_split_where_they_fall() {
|
||||
let mut c = Case::new((3, 400.0));
|
||||
c.widow = false;
|
||||
assert_eq!(c.per_page(), vec![0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
/// A paragraph of a nested table splits the same way.
|
||||
#[test]
|
||||
fn a_nested_paragraph_at_the_top_of_a_page_splits_where_its_lines_fall() {
|
||||
let mut c = Case::new((3, 300.0));
|
||||
c.nested = true;
|
||||
assert_eq!(c.per_page(), vec![0, 2, 1]);
|
||||
let mut c = Case::new((2, 400.0));
|
||||
c.nested = true;
|
||||
assert_eq!(c.per_page(), vec![0, 1, 1]);
|
||||
}
|
||||
|
||||
/// A nested paragraph below another one of the nested cell moves on whole, then splits at the top
|
||||
/// of the page.
|
||||
#[test]
|
||||
fn a_nested_paragraph_below_other_content_moves_on_then_splits() {
|
||||
let mut c = Case::new((3, 300.0));
|
||||
c.nested = true;
|
||||
c.before = vec![(1, 100.0)];
|
||||
assert_eq!(c.per_page(), vec![0, 0, 2, 1]);
|
||||
}
|
||||
|
||||
/// Under a repeated header row the paragraph that starts the page splits at its lines too. The
|
||||
/// lines per page are Word's; Word leaves the header off some of the pages, which is not covered.
|
||||
#[test]
|
||||
fn under_a_repeated_header_row_the_paragraph_starting_the_page_splits_where_its_lines_fall() {
|
||||
let mut c = Case::new((3, 300.0));
|
||||
c.header = true;
|
||||
c.fill = 44;
|
||||
assert_eq!(c.per_page(), vec![0, 2, 1]);
|
||||
let mut c = Case::new((3, 300.0));
|
||||
c.header = true;
|
||||
c.fill = 44;
|
||||
c.before = vec![(1, 100.0)];
|
||||
assert_eq!(c.per_page(), vec![0, 0, 2, 1]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): under a header row, four lines with room for three keep two.
|
||||
#[test]
|
||||
fn under_a_repeated_header_row_four_lines_still_keep_two_for_the_widow() {
|
||||
let mut c = Case::new((4, 200.0));
|
||||
c.header = true;
|
||||
c.fill = 44;
|
||||
assert_eq!(c.per_page(), vec![0, 2, 2]);
|
||||
}
|
||||
|
||||
/// A can't split row taller than a page splits where the pages end.
|
||||
#[test]
|
||||
fn a_cant_split_row_taller_than_a_page_splits_where_the_page_ends() {
|
||||
let mut c = Case::new((3, 400.0));
|
||||
c.cant_split = true;
|
||||
assert_eq!(c.per_page(), vec![0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
/// A can't split row taller than a page that starts below text goes to the next page first, then
|
||||
/// splits there.
|
||||
#[test]
|
||||
fn a_tall_cant_split_row_below_text_starts_the_next_page_and_splits_there() {
|
||||
let mut c = Case::new((3, 400.0));
|
||||
c.cant_split = true;
|
||||
c.pre = 20;
|
||||
assert_eq!(c.per_page(), vec![0, 0, 1, 1, 1]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): a can't split row that fits the next page moves there whole.
|
||||
#[test]
|
||||
fn a_cant_split_row_that_fits_the_next_page_moves_there_whole() {
|
||||
let mut c = Case::new((3, 16.0));
|
||||
c.cant_split = true;
|
||||
c.pre = 38;
|
||||
c.fill = 5;
|
||||
c.fill_height = 16.0;
|
||||
assert_eq!(c.per_page(), vec![0, 3]);
|
||||
}
|
||||
|
||||
/// A picture floating above the paragraph that starts the cell doesn't make it any less the
|
||||
/// first: only the text in the flow decides. (Floats are placed with the first piece of their
|
||||
/// paragraph, so this is the table's first page.)
|
||||
#[test]
|
||||
fn a_floating_picture_above_the_first_paragraph_doesnt_keep_it_from_splitting() {
|
||||
let mut c = Case::new((3, 400.0));
|
||||
c.fill = 0;
|
||||
c.float_above = true;
|
||||
assert_eq!(c.per_page(), vec![1, 1, 1]);
|
||||
}
|
||||
|
||||
/// Guard (passes without the fix): a can't split row that fits a page with room to spare stays
|
||||
/// whole on it, whatever the border below it needs.
|
||||
#[test]
|
||||
fn a_cant_split_row_that_fits_a_page_is_left_whole() {
|
||||
let mut c = Case::new((1, 10.0));
|
||||
c.cant_split = true;
|
||||
assert_eq!(c.per_page(), vec![1, 0], "the row stays on page 1 (the paragraph after it is on page 2)");
|
||||
}
|
||||
@@ -302,10 +302,8 @@ fn inline_box_that_resizes_to_fit_takes_its_texts_height() {
|
||||
}
|
||||
|
||||
/// Filler paragraphs before the box in [`inline_box_that_resizes_to_fit_takes_its_texts_height`]:
|
||||
/// enough that a 10 cm box no longer leaves room for the page break on the first page, while the
|
||||
/// box fitted to its three lines does (a paragraph of only a page break that doesn't fit goes to
|
||||
/// the next page, as in Word).
|
||||
const FILLER: usize = 20;
|
||||
/// enough that a 10 cm box no longer leaves room for the page break on the first page.
|
||||
const FILLER: usize = 22;
|
||||
|
||||
/// A floating box that resizes to fit its text takes its text's height too, both where it is
|
||||
/// drawn and the room the text beside it wraps around (an OpenDocument frame without a height).
|
||||
|
||||
@@ -16,7 +16,7 @@ craft = { workspace = true, features = [
|
||||
"color", "color-ui", "control", "draw", "font-manager", "gpu", "menu", "pages", "print", "review", "table", "text",
|
||||
"text-find", "web-api", "web-host", "window",
|
||||
] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38" }
|
||||
wordcraft-geom = { workspace = true, features = ["image"] }
|
||||
wordcraft-doc = { workspace = true }
|
||||
wordcraft-fonts = { workspace = true }
|
||||
@@ -65,18 +65,13 @@ wordcraft-engine = { workspace = true, features = ["test-support"] }
|
||||
# kittest's own dev-dependencies do not propagate their font features. Declare the fonts the
|
||||
# interface tests lay out explicitly: default faces plus monochrome emoji fallbacks.
|
||||
egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] }
|
||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] }
|
||||
# The app-window tests run `WordApp` as an `eframe::App` (`test_harness`), so the runtime gets the app's input before
|
||||
# every pass as on the desktop. The desktop app's feature set, so a workspace build shares one eframe.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "clipboard", "wayland", "x11", "links"] }
|
||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
||||
craft-zip = { workspace = true }
|
||||
# The window tests' frame driver for child viewports; it is not part of the `craft` facade.
|
||||
craft-ui-test-kit = { workspace = true }
|
||||
# The interface tests' fixture and access tree (`craft::ui::testing`).
|
||||
craft = { workspace = true, features = ["ui-testing"] }
|
||||
|
||||
[build-dependencies]
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "b436ae992591173ce53fdb1314421ba2d8897e49", features = ["subset"] }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "243d68e12d05e89122db6d154924bf1992e10d38", features = ["subset"] }
|
||||
serde_json = { workspace = true }
|
||||
toml = "1"
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
|
||||
<path d="M3 6 L7 3.5 L13 3.5 L17 6 L17.5 14 L13.5 16.5 L6.5 16.5 L2.5 14 Z M6 10.5 A1.5 1.5 0 1 0 9 10.5 A1.5 1.5 0 1 0 6 10.5 Z M11 10.5 A1.5 1.5 0 1 0 14 10.5 A1.5 1.5 0 1 0 11 10.5 Z" fill="currentColor" fill-rule="evenodd"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 322 B |
@@ -6,7 +6,6 @@ use super::{
|
||||
theme, updates_ui, window_ui, windows, zotero,
|
||||
};
|
||||
use craft::platform::clock::monotonic_ms;
|
||||
use craft::theme::ComponentSet;
|
||||
use craft::ui::runtime::commands::CommandInput;
|
||||
use craft::ui::runtime::env::{AltCodePages, ResolvedRoot, RootEnv, WheelSpeed};
|
||||
use craft::ui::runtime::frame::{FrameInput, FrameOutput};
|
||||
@@ -185,7 +184,7 @@ impl WordApp {
|
||||
}
|
||||
|
||||
/// This frame's root values: the wheel speed, the Alt-code pages, the interface mode,
|
||||
/// motion, scale, direction and the component set (WordCraft takes the productivity set). Built from the saved settings every frame, so a change
|
||||
/// motion, scale and direction. Built from the saved settings every frame, so a change
|
||||
/// applies at once.
|
||||
pub fn root_env(&self) -> RootEnv {
|
||||
let lang = i18n::Lang::from_pref(&self.ui.language);
|
||||
@@ -205,8 +204,7 @@ impl WordApp {
|
||||
.direction(direction)
|
||||
.mode(self.ui.theme.mode())
|
||||
.wheel_speed(WheelSpeed::new(line, point))
|
||||
.alt_code_pages(AltCodePages::new(ansi, oem))
|
||||
.set(ComponentSet::Productivity);
|
||||
.alt_code_pages(AltCodePages::new(ansi, oem));
|
||||
env.motion = self.ui.animations.motion();
|
||||
env.sizes = std::sync::Arc::clone(&APP_SIZES);
|
||||
env
|
||||
|
||||
@@ -52,21 +52,6 @@ const GATED_UI_COMMANDS: &[(&str, &str)] = &[
|
||||
("ui.zotero.removeCodes", "Unlink Citations"),
|
||||
];
|
||||
|
||||
/// Word feature catalog entries whose command is not yet registered in `registry`: each gets a
|
||||
/// catalog entry without a chord (preventing unregistered-command warnings) and a disabled state
|
||||
/// until an engine command takes its id.
|
||||
fn unimplemented_catalog_commands(registry: &wordcraft_engine::Registry) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
|
||||
let mut seen = HashSet::new();
|
||||
wordcraft_engine::catalog::CATALOG.lines().filter_map(move |line| {
|
||||
let mut parts = line.split('|');
|
||||
let _tab = parts.next()?;
|
||||
let _group = parts.next()?;
|
||||
let feature = parts.next()?;
|
||||
let id = parts.next()?;
|
||||
(registry.get(id).is_none() && seen.insert(id)).then_some((id, feature))
|
||||
})
|
||||
}
|
||||
|
||||
/// The default chords of an engine command: its `shortcut`, one binding per `" / "` piece.
|
||||
fn default_bindings(shortcut: &str) -> impl Iterator<Item = Binding> + '_ {
|
||||
shortcut.split(" / ").filter(|piece| !piece.is_empty()).filter_map(|piece| Binding::parse(piece).ok())
|
||||
@@ -138,11 +123,6 @@ impl WordApp {
|
||||
for (id, label) in GATED_UI_COMMANDS {
|
||||
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
|
||||
}
|
||||
for (id, feature) in unimplemented_catalog_commands(®istry) {
|
||||
if seen.insert(id) {
|
||||
defs.push(CommandDef::new(CommandRef::new(id), tl!(feature), Scope::app()));
|
||||
}
|
||||
}
|
||||
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
|
||||
// plain keys type, and every modified chord is offered to the keymap first.
|
||||
match AppCatalog::new(defs, generation) {
|
||||
@@ -194,14 +174,6 @@ impl WordApp {
|
||||
for id in ids {
|
||||
states.set(CommandRef::new(id), CommandState::new().enabled(command_enabled(self, id)));
|
||||
}
|
||||
let unavailable_hint: Option<Arc<str>> = crate::widgets::command_hint("", "", Some("")).map(Arc::from);
|
||||
for (id, _) in unimplemented_catalog_commands(®istry) {
|
||||
let mut state = CommandState::new().enabled(command_enabled(self, id));
|
||||
if let Some(hint) = unavailable_hint.as_ref() {
|
||||
state = state.hint(Arc::clone(hint));
|
||||
}
|
||||
states.set(CommandRef::new(id), state);
|
||||
}
|
||||
let commands = CommandRef::with_params("ui.dialog", json!({"name": "commands"}));
|
||||
states.set(commands, CommandState::new().enabled(command_enabled(self, "ui.dialog")));
|
||||
if *self.command_states != states {
|
||||
@@ -305,20 +277,4 @@ mod tests {
|
||||
crate::undo_marks::apply_edits(&mut app, end, apply);
|
||||
assert_eq!(app.session.undo_depth(), after_undo, "the late Commit of the taken-back gesture adds no step");
|
||||
}
|
||||
|
||||
/// #7310: unimplemented Word feature catalog commands publish a disabled state so ribbon
|
||||
/// buttons and keytips bound to them resolve disabled instead of falling back to enabled.
|
||||
#[test]
|
||||
fn unimplemented_catalog_commands_publish_disabled_state() {
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
let _ = app.command_input();
|
||||
for id in ["tools.dictate", "draw.inkToMath", "review.translate", "review.blockAuthors"] {
|
||||
assert!(app.session.registry.get(id).is_none(), "{id} is still an unimplemented stub");
|
||||
let state = app.command_states.get(&CommandRef::new(id));
|
||||
assert!(
|
||||
state.is_some_and(|s| !s.is_enabled()),
|
||||
"unimplemented catalog command {id} must publish an explicit disabled state, got {state:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -633,7 +633,7 @@ impl WordApp {
|
||||
for item in intake.take() {
|
||||
match item {
|
||||
Intake::Dropped { files, target } => self.open_dropped(&files, target),
|
||||
Intake::Open(paths) | Intake::OpenFor { paths, .. } => {
|
||||
Intake::Open(paths) => {
|
||||
for p in paths {
|
||||
// A path that is not Unicode cannot be passed on as text: skipped.
|
||||
if let Some(path) = p.to_str()
|
||||
@@ -649,14 +649,6 @@ impl WordApp {
|
||||
Intake::Quit => {
|
||||
self.quit();
|
||||
}
|
||||
// An OS open request that arrived as bytes, with no path.
|
||||
Intake::Bytes { name, bytes } => {
|
||||
let data = wordcraft_engine::cmd::insert::base64_encode(bytes.as_ref());
|
||||
if let Err(e) = self.run("file.open", json!({"path": name, "data": data})) {
|
||||
self.report_open_failure(&name, &e);
|
||||
}
|
||||
self.ui.backstage = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, clicked};
|
||||
use craft::ui::shell::{RecentFile, RecentList, RecentSort, RecentView, StartAction, StartLayout, StartScreen, Template};
|
||||
use craft::ui::style::DataColor;
|
||||
use egui::{Color32, Ui};
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
|
||||
use super::{HOME_TEMPLATES, TEMPLATES, TemplateThumbs, error_line, heading, label, open_recent, thumbs};
|
||||
@@ -78,9 +77,7 @@ pub(super) fn home(ui: &mut Ui, app: &mut WordApp) {
|
||||
let recent = recent_files(app);
|
||||
let cards = template_cards(&TEMPLATES[..HOME_TEMPLATES.min(TEMPLATES.len())]);
|
||||
let store = thumbs::store(&ctx);
|
||||
let region = app.session.region();
|
||||
let (wide, high) = thumbs::page_aspect(®ion);
|
||||
let source = TemplateThumbs { region };
|
||||
let source = TemplateThumbs { region: app.session.region() };
|
||||
let (mut view, mut sort) = (RecentView::List, RecentSort::Opened);
|
||||
let out = StartScreen::new(Bind::bound(&mut view), Bind::bound(&mut sort), &recent)
|
||||
.layout(StartLayout::Greeting)
|
||||
@@ -88,9 +85,6 @@ pub(super) fn home(ui: &mut Ui, app: &mut WordApp) {
|
||||
.templates(&cards)
|
||||
.more_templates(label("More templates →"))
|
||||
.max_recent(app.ui.recent_shown())
|
||||
.picture_aspect(wide, high)
|
||||
.card_zoom(1.0)
|
||||
.page_paper(DataColor::new(Color32::WHITE))
|
||||
.thumbnails(&store, &source)
|
||||
.show(ui);
|
||||
run_actions(app, &ctx, out.actions);
|
||||
@@ -118,6 +112,12 @@ pub(super) fn open(ui: &mut Ui, app: &mut WordApp) {
|
||||
error_line(ui, &error);
|
||||
}
|
||||
let recent = recent_files(app);
|
||||
let out = RecentList::new(&recent).max_recent(app.ui.recent_shown()).empty(label("Documents you open will show up here.")).show(ui);
|
||||
let store = thumbs::store(&ctx);
|
||||
let source = TemplateThumbs { region: app.session.region() };
|
||||
let out = RecentList::new(&recent)
|
||||
.max_recent(app.ui.recent_shown())
|
||||
.empty(label("Documents you open will show up here."))
|
||||
.thumbnails(&store, &source)
|
||||
.show(ui);
|
||||
run_actions(app, &ctx, out.actions);
|
||||
}
|
||||
|
||||
@@ -12,13 +12,12 @@ use craft::ui::contract::{
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::notices::Notice;
|
||||
use craft::ui::primitives::{ContentPainterCx, IconSpec};
|
||||
use craft::ui::primitives::IconSpec;
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::shell::{Template, ThumbKey};
|
||||
use craft::ui::style::DataColor;
|
||||
use craft::ui::text::TextField;
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
use egui::{Color32, Rect, Shape, Ui, vec2};
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
|
||||
use super::home::template_cards;
|
||||
@@ -31,13 +30,13 @@ const PAGE_WIDE: u16 = 3;
|
||||
const PAGE_HIGH: u16 = 4;
|
||||
|
||||
/// A grid of template tiles, one per card, that reports the chosen key.
|
||||
fn grid(name: Label, wide: u16, high: u16) -> TileGrid<'static, String> {
|
||||
fn grid(name: Label) -> TileGrid<'static, String> {
|
||||
TileGrid::<String>::new(name)
|
||||
.select(SelectMode::Single)
|
||||
.activate(ActivateOn::Click)
|
||||
.caption(CaptionPlace::Below)
|
||||
.card()
|
||||
.aspect(f32::from(wide) / f32::from(high))
|
||||
.aspect(f32::from(PAGE_WIDE) / f32::from(PAGE_HIGH))
|
||||
.sizing(Sizing::FillWidth)
|
||||
.natural_height(true)
|
||||
}
|
||||
@@ -59,14 +58,6 @@ fn read_listing(app: &WordApp) -> PersonalListing {
|
||||
PersonalListing { key, folder, templates }
|
||||
}
|
||||
|
||||
/// Paints a personal template card thumbnail: a white page surface with a centered 44×44 pt
|
||||
/// `documentTemplate` icon (#7373).
|
||||
pub(super) fn paint_personal_card(cx: &ContentPainterCx, rect: Rect) {
|
||||
cx.data_shapes([Shape::rect_filled(rect, 2.0, Color32::WHITE)]);
|
||||
let icon_rect = Rect::from_center_size(rect.center(), vec2(44.0, 44.0));
|
||||
cx.icon(icon_rect, &IconSpec::svg(IconId::new("documentTemplate")).data_color(DataColor::new(Color32::from_gray(150))));
|
||||
}
|
||||
|
||||
/// New: the whole template gallery with a search box, then the personal templates (#2852); no
|
||||
/// Recent list (that is on Home and Open). The search covers both.
|
||||
///
|
||||
@@ -96,18 +87,16 @@ pub(super) fn show(ui: &mut Ui, app: &mut WordApp) {
|
||||
return;
|
||||
}
|
||||
let store = thumbs::store(&ctx);
|
||||
let region = app.session.region();
|
||||
let (wide, high) = thumbs::page_aspect(®ion);
|
||||
let source = thumbs::TemplateThumbs { region };
|
||||
let source = thumbs::TemplateThumbs { region: app.session.region() };
|
||||
if !found.is_empty() {
|
||||
let (store, source) = (&store, &source);
|
||||
let cards = template_cards(&found);
|
||||
let items = keyed(&cards, |t: &Template| t.id.clone()).with_text(|t| Cow::Borrowed(t.name.as_str()));
|
||||
let out = grid(label("Templates"), wide, high).show_items(ui, &items, &mut |id, _| {
|
||||
let out = grid(label("Templates")).show_items(ui, &items, &mut |id, _| {
|
||||
let Some(card) = cards.iter().find(|c| &c.id == id) else { return Tile::new(Label::Empty) };
|
||||
let thumb = ThumbKey::Template(card.id.clone());
|
||||
Tile::new(Label::from(card.name.clone()))
|
||||
.thumb(ThumbAspect::new(wide, high), move |cx, rect| thumbs::paint(cx, rect, store, source, &thumb))
|
||||
.thumb(ThumbAspect::new(PAGE_WIDE, PAGE_HIGH), move |cx, rect| thumbs::paint(cx, rect, store, source, &thumb))
|
||||
});
|
||||
for id in activated(out.response.events) {
|
||||
let _ = app.run("file.new", json!({"template": id}));
|
||||
@@ -142,9 +131,9 @@ pub(super) fn show(ui: &mut Ui, app: &mut WordApp) {
|
||||
let tiles: Vec<&PersonalTemplate> = personal_found.iter().filter(|p| p.category == category).collect();
|
||||
let items = keyed(&tiles, |p: &&PersonalTemplate| p.path.clone()).with_text(|p| Cow::Borrowed(p.label.as_str()));
|
||||
let name = if category.is_empty() { label("Personal templates") } else { Label::from(category.to_owned()) };
|
||||
let out = grid(name, PAGE_WIDE, PAGE_HIGH).id_salt(("personal-templates", category.to_owned())).show_items(ui, &items, &mut |path, _| {
|
||||
let out = grid(name).id_salt(("personal-templates", category.to_owned())).show_items(ui, &items, &mut |path, _| {
|
||||
let Some(p) = tiles.iter().find(|p| &p.path == path) else { return Tile::new(Label::Empty) };
|
||||
Tile::new(Label::from(p.label.clone())).thumb(ThumbAspect::new(PAGE_WIDE, PAGE_HIGH), paint_personal_card).tooltip(p.path.clone())
|
||||
Tile::new(Label::from(p.label.clone())).icon(IconSpec::svg(IconId::new("documentTemplate"))).tooltip(p.path.clone())
|
||||
});
|
||||
for path in activated(out.response.events) {
|
||||
let failed = open_personal(app, &path, &ctx).err();
|
||||
|
||||
@@ -353,21 +353,6 @@ fn new_lists_personal_templates_and_opens_one() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #7373: Personal template cards in File › New paint a white page surface and document icon.
|
||||
#[test]
|
||||
fn personal_template_cards_render_as_page_cards() {
|
||||
let dir = personal_dir("card-paint");
|
||||
let memo = dir.join("Proposal.dotx");
|
||||
write_template(&memo, "Proposal template text");
|
||||
let h = new_page_harness(Some(dir.clone()));
|
||||
let card = h.query_by_label("Proposal");
|
||||
assert!(card.is_some(), "personal template tile exists");
|
||||
let rect = card.unwrap().rect();
|
||||
assert!(rect.height() > rect.width(), "personal template card is portrait oriented");
|
||||
drop(h);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An empty (or not yet made) templates folder says where templates come from; no folder (the
|
||||
/// web) shows no Personal section. Home keeps only the built-ins.
|
||||
#[test]
|
||||
@@ -855,40 +840,3 @@ fn a_file_pages_title_is_productions_size() {
|
||||
assert!(title.size > section.size + 6.0, "the title stands above a section heading: {title:?} over {section:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The template cards on File › Home and File › New use the portrait aspect of the active region,
|
||||
/// and Home cards use card_zoom(1.0) so they do not stretch across the row (#7372, #7149 items 2-3).
|
||||
#[test]
|
||||
fn backstage_template_cards_aspect_and_zoom() {
|
||||
let mut letter_app = new_app();
|
||||
letter_app.session.system_region = wordcraft_geom::Region::from_tag("en-US");
|
||||
let (wide_us, high_us) = super::thumbs::page_aspect(&letter_app.session.region());
|
||||
assert_eq!((wide_us, high_us), (17, 22), "US region uses 17:22 (Letter) aspect");
|
||||
|
||||
let mut a4_app = new_app();
|
||||
a4_app.session.system_region = wordcraft_geom::Region::from_tag("en-GB");
|
||||
let (wide_gb, high_gb) = super::thumbs::page_aspect(&a4_app.session.region());
|
||||
assert_eq!((wide_gb, high_gb), (70, 99), "GB region uses 70:99 (A4) aspect");
|
||||
|
||||
// Home template cards: portrait and narrow (~150 pt wide, not stretched across the row)
|
||||
let h = file_page(new_app(), "home");
|
||||
let card = h.get_by_label("Blank document").rect();
|
||||
assert!(card.height() > card.width(), "Home template card is portrait: {card:?}");
|
||||
assert!(card.width() < 300.0, "card zoom keeps cards narrow instead of filling row: {card:?}");
|
||||
}
|
||||
|
||||
/// File › Open presents the recent list without thumbnail letterboxing (#7372).
|
||||
#[test]
|
||||
fn file_open_recent_list_has_no_thumbnail_letterboxing() {
|
||||
let app = new_app();
|
||||
let h = file_page(app, "open");
|
||||
assert!(h.query_by_label("Browse…").is_some(), "Browse button exists");
|
||||
assert!(h.query_all_by_label("Recent").next().is_some(), "Recent section exists");
|
||||
assert!(h.query_by_label("Documents you open will show up here.").is_some(), "empty state message exists");
|
||||
|
||||
let mut populated = new_app();
|
||||
populated.ui.recent = vec!["/tmp/sample.docx".into()];
|
||||
let h2 = file_page(populated, "open");
|
||||
let row = recent_row(&h2, "sample.docx").expect("recent row renders");
|
||||
assert!(row.rect().height() > 0.0, "recent row has non-zero height: {:?}", row.rect());
|
||||
}
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
//! The template thumbnails of the File page: the first page of each built-in template, drawn in a
|
||||
//! throwaway session so the user's document is never touched.
|
||||
|
||||
use craft::ui::primitives::{
|
||||
ContentPainterCx, Priority, Revision, ThumbFit, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails,
|
||||
};
|
||||
use craft::ui::primitives::{ContentPainterCx, Priority, Revision, ThumbPaint, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails};
|
||||
use craft::ui::shell::ThumbKey;
|
||||
use craft::ui::style::{Corners, DataColor, SurfaceKind};
|
||||
use craft::ui::style::{Corners, SurfaceKind};
|
||||
use serde_json::json;
|
||||
|
||||
/// The shape of a document page in `region`, wide to high (Letter 17:22 or A4 70:99).
|
||||
pub(crate) fn page_aspect(region: &wordcraft_geom::Region) -> (u16, u16) {
|
||||
if region.uses_letter() { (17, 22) } else { (70, 99) }
|
||||
}
|
||||
|
||||
/// The salt every reader of the File page's thumbnails asks the store with, so New, Home and the
|
||||
/// recent rows share one loader and one set of pictures.
|
||||
const SALT: &str = "wordcraft.templates";
|
||||
@@ -27,8 +20,7 @@ pub(crate) fn store(ctx: &egui::Context) -> Thumbnails<ThumbKey> {
|
||||
pub(crate) fn paint(cx: &ContentPainterCx, rect: egui::Rect, store: &Thumbnails<ThumbKey>, source: &dyn ThumbSource<ThumbKey>, key: &ThumbKey) {
|
||||
let request = ThumbRequest::for_cell(rect.width().max(rect.height()), cx.pixels_per_point());
|
||||
let state = store.state(cx.painter.ctx(), source, key, &request, Priority::VISIBLE);
|
||||
let paint = ThumbPaint::default().fit(ThumbFit::Cover).checker(false).paper(DataColor::new(egui::Color32::WHITE));
|
||||
if !store.paint(cx, rect, &state, &paint) {
|
||||
if !store.paint(cx, rect, &state, &ThumbPaint::default()) {
|
||||
cx.surface(rect, SurfaceKind::Sunken, Corners::None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::sync::Arc;
|
||||
use craft::behavior::kurbo::{Point, Size};
|
||||
use craft::pages::layout::{Fit, LayoutOptions, PageDisplay, SCREEN_POINTS_PER_POINT};
|
||||
use craft::pages::ui::reading::{ReadingMetrics, reading_size};
|
||||
use craft::pages::ui::{GoTo, MarkArea, MarkKind, PageBody, PageView, PageViewState, PlacedPage, ReadingNav, ReadingState, ReadingView, TextMarks};
|
||||
use craft::pages::ui::{MarkArea, MarkKind, PageBody, PageView, PageViewState, PlacedPage, ReadingNav, ReadingState, ReadingView, TextMarks};
|
||||
use craft::ui::canvas::{Autoscroll, ContextSource, MiddleButton, NavigationOptions, ToolHost, ToolHostResponse, ToolPass, WheelScheme};
|
||||
use craft::ui::contract::Show as _;
|
||||
|
||||
@@ -371,7 +371,7 @@ impl CanvasState {
|
||||
|
||||
/// The comment whose balloon is selected, as the document's comment id.
|
||||
pub fn selected_balloon(&self) -> Option<u32> {
|
||||
self.comments.selected.lead.and_then(|id| u32::try_from(id.0).ok())
|
||||
self.comments.selected.and_then(|id| u32::try_from(id.0).ok())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,7 +609,7 @@ fn mark_areas(app: &mut WordApp, layout: &DocLayout, selected: &[(usize, wordcra
|
||||
fn navigation_options() -> NavigationOptions {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.middle_button =
|
||||
if cfg!(any(target_os = "macos", target_os = "ios", target_arch = "wasm32")) { MiddleButton::Pan } else { MiddleButton::AutoScroll };
|
||||
if cfg!(any(target_os = "macos", target_os = "ios", target_arch = "wasm32")) { MiddleButton::Pan } else { MiddleButton::Autoscroll };
|
||||
options.wheel = WheelScheme::Document;
|
||||
options
|
||||
}
|
||||
@@ -754,7 +754,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
if let Some(c) = c
|
||||
&& let Some(page) = layout.pages.get(c.page)
|
||||
{
|
||||
state.go_to = Some(GoTo::Top { page: c.page, fraction: f64::from(c.top / page.h.max(1.0)) });
|
||||
state.go_to = Some((c.page, f64::from(c.top / page.h.max(1.0))));
|
||||
state.current = c.page;
|
||||
}
|
||||
}
|
||||
@@ -864,7 +864,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
} else {
|
||||
screen_rects(&selected, body.pages)
|
||||
};
|
||||
app.canvas.mini_anchor = crate::mini_toolbar::visible_anchor(anchor_rects, body.view.rect, crate::mini_toolbar::starts_rtl(app));
|
||||
app.canvas.mini_anchor = crate::mini_toolbar::visible_anchor(anchor_rects, body.view.rect);
|
||||
// The bar is its own floating layer: shown after the host, it keeps its buttons' presses (S-L410).
|
||||
crate::mini_toolbar::show(app, ui, body);
|
||||
}
|
||||
@@ -908,7 +908,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
if let Some(go) = fix.go_to {
|
||||
state.go_to = Some(GoTo::Top { page: go.0, fraction: go.1 });
|
||||
state.go_to = Some(go);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
// Dragging a selection past the view's edge scrolls on.
|
||||
@@ -920,9 +920,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
let per_unit = v.zoom.max(f64::EPSILON);
|
||||
let size = Size::new(out.layout.size.width / per_unit, out.layout.size.height / per_unit);
|
||||
if Autoscroll::scroll(&mut v, step, size).is_some() {
|
||||
// The view moved in document units; the state keeps screen points.
|
||||
state.offset.0 += (v.center.x - view.center.x) * view.zoom;
|
||||
state.offset.1 += (v.center.y - view.center.y) * view.zoom;
|
||||
out.adopt(&mut state, &v);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! and its drafts are `CanvasState::comments`, the one copy the Comments pane shares.
|
||||
|
||||
use craft::review::ui::{BalloonItem, BalloonPlace, CommentBalloons, CommentEdit};
|
||||
use craft::review::{CommentAnchor, CommentMessage, CommentThread, Revision, RevisionKind, ThreadId};
|
||||
use craft::review::{CommentAnchor, CommentMessage, CommentThread, ReviewStatus, Revision, RevisionKind, ThreadId};
|
||||
|
||||
use super::geometry::{FLOAT_WIDTH, floating_comments, markup_width, shown_comment};
|
||||
use super::{Color32, CommentDisplay, DocLayout, Env, Pos, Pos2, StoryRef, Ui, WordApp, json};
|
||||
@@ -68,8 +68,7 @@ pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::P
|
||||
/// Applies what a card reported through the commands the Comments pane uses.
|
||||
fn apply(app: &mut WordApp, cards: &[Card], edit: CommentEdit) {
|
||||
match edit {
|
||||
CommentEdit::Select(threads) => {
|
||||
let Some(thread) = threads.first().copied() else { return };
|
||||
CommentEdit::Select(thread) => {
|
||||
let Some(id) = app_id(thread) else { return };
|
||||
focus_balloon(app, id);
|
||||
let pos = cards.iter().find_map(|c| match &c.what {
|
||||
@@ -150,7 +149,7 @@ fn thread_of(app: &WordApp, id: u32, page: usize, anchor: Pos2, color: Color32)
|
||||
let c = app.session.doc.comments.get(&cid)?;
|
||||
let created = c.date_utc.as_deref().map(unix_seconds).filter(|t| *t > 0).unwrap_or_else(|| unix_seconds(&c.date));
|
||||
let text = app.session.doc.plain_text(StoryRef::Part(c.part)).trim().to_string();
|
||||
Some(CommentMessage { author: author_name(&c.author), created, modified: None, text, reactions: Vec::new(), read: true, deletable: true })
|
||||
Some(CommentMessage { author: author_name(&c.author), created, modified: None, text, reactions: Vec::new(), read: true })
|
||||
})
|
||||
.collect();
|
||||
Some(CommentThread {
|
||||
@@ -159,8 +158,7 @@ fn thread_of(app: &WordApp, id: u32, page: usize, anchor: Pos2, color: Color32)
|
||||
kind: None,
|
||||
color: Some([color.r(), color.g(), color.b()]),
|
||||
messages,
|
||||
statuses: Vec::new(),
|
||||
reply_statuses: Vec::new(),
|
||||
status: ReviewStatus::None,
|
||||
marked: false,
|
||||
locked: false,
|
||||
resolved: root.resolved,
|
||||
@@ -255,7 +253,7 @@ fn focus_balloon(app: &mut WordApp, id: u32) {
|
||||
let text = app.session.doc.comments.get(&id).filter(|_| editable).map(|c| app.session.doc.plain_text(StoryRef::Part(c.part)));
|
||||
let thread = thread_id(id);
|
||||
let comments = &mut app.canvas.comments;
|
||||
comments.selected = craft::behavior::Selection::single(thread);
|
||||
comments.selected = Some(thread);
|
||||
if comments.editing.as_ref().is_none_or(|(t, ..)| *t != thread) {
|
||||
comments.editing = text.map(|t| (thread, 0, t));
|
||||
}
|
||||
@@ -277,5 +275,5 @@ pub fn deselect_balloon(app: &mut WordApp) {
|
||||
// What was written is cleared by the write; a draft the document refused (read-only protection) stays, with its
|
||||
// reason on the status line, for when the balloon is selected again or the document is saved or closed (#1348).
|
||||
write_back(app, id);
|
||||
app.canvas.comments.selected = craft::behavior::Selection::default();
|
||||
app.canvas.comments.selected = None;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use craft::behavior::{Input, Metrics};
|
||||
use craft::pages::ui::{PageBody, PlacedPage};
|
||||
use craft::ui::canvas::ToolPass;
|
||||
use craft::ui::contract::{Access, Common, Component, Cx, MeasureCx, NoValue, Outcome, PaintUi, Props as _, Role, Show as _};
|
||||
use craft::ui::fonts::FaceBytes;
|
||||
use craft::ui::fonts::{FaceBytes, MAX_INTERFACE_FACE_BYTES};
|
||||
use craft::ui::primitives::{FaceRun, PaintShape, StrokeWidth, TextRun};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
|
||||
@@ -293,10 +293,14 @@ pub(crate) fn face_key(face: wordcraft_fonts::FaceRef) -> String {
|
||||
format!("wordcraft-face:{}", face.id())
|
||||
}
|
||||
|
||||
/// The bytes, index and variation setting of `face`, read the first time it is drawn. The framework's document-face
|
||||
/// registry keeps the faces within its byte budget.
|
||||
/// The bytes, index and variation setting of `face`, read the first time it is drawn. A file larger than the framework
|
||||
/// draws over the interface fonts is not copied: the composition stays in the interface font (a document's CJK
|
||||
/// fallback can be 19 MB).
|
||||
fn face_bytes(face: wordcraft_fonts::FaceRef) -> Option<FaceBytes> {
|
||||
let data = face.data();
|
||||
if data.len() > MAX_INTERFACE_FACE_BYTES {
|
||||
return None;
|
||||
}
|
||||
Some(FaceBytes::new(std::sync::Arc::from(data), face.index()).coords(face.coords.iter().copied()))
|
||||
}
|
||||
|
||||
|
||||
@@ -427,20 +427,20 @@ fn selection_bar_clicks_select_lines() {
|
||||
page_to_screen(h.state_mut(), c.page, 30.0, c.top + c.height * (li + 0.5)).expect("on screen")
|
||||
};
|
||||
let line_start = |h: &mut H, at: Pos2| {
|
||||
let placed = h.state().canvas.shown.pages.iter().find(|p| p.rect.contains(at)).expect("page").clone();
|
||||
let placed = *h.state().canvas.shown.pages.iter().find(|p| p.rect.contains(at)).expect("page");
|
||||
let p = placed.to_page(at);
|
||||
let layout = h.state_mut().session.layout();
|
||||
layout.selection_bar_at(placed.page, p.x as f32, p.y as f32).expect("in the selection bar")
|
||||
};
|
||||
let span = |h: &mut H, pos: &Pos| h.state_mut().session.layout().line_span(pos, 0).expect("line");
|
||||
let button = |at: Pos2, pressed: bool, modifiers: Modifiers| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers };
|
||||
let clicks_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize, mods: Modifiers| {
|
||||
let button = |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let clicks_drag = |h: &mut H, from: Pos2, to: Pos2, clicks: usize| {
|
||||
h.event(Event::PointerMoved(from));
|
||||
for i in 0..clicks {
|
||||
h.event(button(from, true, mods));
|
||||
h.event(button(from, true));
|
||||
h.app_frame();
|
||||
if i + 1 < clicks {
|
||||
h.event(button(from, false, mods));
|
||||
h.event(button(from, false));
|
||||
h.app_frame();
|
||||
}
|
||||
}
|
||||
@@ -448,7 +448,7 @@ fn selection_bar_clicks_select_lines() {
|
||||
h.event(Event::PointerMoved(from + (to - from) * (k as f32 / 4.0)));
|
||||
h.app_frame();
|
||||
}
|
||||
h.event(button(to, false, mods));
|
||||
h.event(button(to, false));
|
||||
for _ in 0..3 {
|
||||
h.app_frame();
|
||||
}
|
||||
@@ -462,22 +462,22 @@ fn selection_bar_clicks_select_lines() {
|
||||
let at = margin(&mut h, Pos::body(0, 0), 1.0);
|
||||
let l2 = line_start(&mut h, at);
|
||||
assert!(l2.off > 0 && l2.path == wordcraft_doc::Path::top(0));
|
||||
clicks_drag(&mut h, at, at, 1, Modifiers::NONE);
|
||||
clicks_drag(&mut h, at, at, 1);
|
||||
let (_, l2_end, _) = span(&mut h, &l2);
|
||||
assert_eq!(h.state().session.sel.ordered(), (l2.clone(), l2_end.clone()), "the line");
|
||||
// Double-click: the paragraph, mark included.
|
||||
pause(&mut h);
|
||||
clicks_drag(&mut h, at, at, 2, Modifiers::NONE);
|
||||
clicks_drag(&mut h, at, at, 2);
|
||||
assert_eq!(h.state().session.sel.ordered(), (Pos::body(0, 0), Pos::body(1, 0)), "the paragraph");
|
||||
// Triple-click: the whole document.
|
||||
pause(&mut h);
|
||||
clicks_drag(&mut h, at, at, 3, Modifiers::NONE);
|
||||
clicks_drag(&mut h, at, at, 3);
|
||||
assert_eq!(h.state().session.sel.ordered(), (Pos::body(0, 0), Pos::body(2, 10)), "everything");
|
||||
// Drag from beside the first line down past the third: three whole lines.
|
||||
pause(&mut h);
|
||||
let (from, to) = (margin(&mut h, Pos::body(0, 0), 0.0), margin(&mut h, Pos::body(0, 0), 2.0));
|
||||
let l3 = line_start(&mut h, to);
|
||||
clicks_drag(&mut h, from, to, 1, Modifiers::NONE);
|
||||
clicks_drag(&mut h, from, to, 1);
|
||||
let (_, l3_end, _) = span(&mut h, &l3);
|
||||
let sel = h.state().session.sel.clone();
|
||||
assert_eq!((sel.anchor, sel.focus), (Pos::body(0, 0), l3_end), "three lines");
|
||||
@@ -486,7 +486,7 @@ fn selection_bar_clicks_select_lines() {
|
||||
let second = margin(&mut h, Pos::body(1, 0), 0.0);
|
||||
h.event(Event::ModifiersChanged(Modifiers::SHIFT));
|
||||
h.app_frame();
|
||||
clicks_drag(&mut h, second, second, 1, Modifiers::SHIFT);
|
||||
clicks_drag(&mut h, second, second, 1);
|
||||
h.event(Event::ModifiersChanged(Modifiers::default()));
|
||||
h.app_frame();
|
||||
let sel = h.state().session.sel.clone();
|
||||
@@ -1227,14 +1227,15 @@ fn a_cjk_composition_uses_the_cjk_ui_font() {
|
||||
assert_eq!(row.glyphs.len(), 3, "one glyph per composed kana");
|
||||
let family = composition_font(&drawn).map(|f| f.family).expect("a font");
|
||||
assert_eq!(family, egui::FontFamily::Name(format!("face+ui:{}", super::caret::face_key(run.requested_face)).into()), "in the text's face");
|
||||
// The framework serves the face with the interface fonts behind it; what the face lacks is drawn from them, so each
|
||||
// kana has a full-width glyph (a missing one would be a narrow box or nothing).
|
||||
let size = composition_font(&drawn).map(|f| f.size).expect("a size");
|
||||
let (chain, interface) = h.ctx.fonts(|f| {
|
||||
let families = &f.definitions().families;
|
||||
(families.get(&family).cloned().unwrap_or_default(), families.get(&egui::FontFamily::Proportional).cloned().unwrap_or_default())
|
||||
});
|
||||
assert!(
|
||||
row.glyphs.iter().all(|g| g.advance_width >= size * 0.8),
|
||||
"the kana come from the interface fonts: {:?}",
|
||||
row.glyphs.iter().map(|g| g.advance_width).collect::<Vec<_>>()
|
||||
!interface.is_empty() && interface.iter().all(|f| chain.contains(f)),
|
||||
"the face's chain goes on with the interface fonts: {chain:?} {interface:?}"
|
||||
);
|
||||
assert_eq!(chain.len(), interface.len() + 1, "and no other document face is borrowed: {chain:?}");
|
||||
}
|
||||
|
||||
/// The composition is drawn in the font and size of the text it goes into, as Word draws it, its
|
||||
|
||||
@@ -259,7 +259,7 @@ fn comment_harness() -> (H, u32) {
|
||||
/// Click comment `id`'s balloon (from no selected balloon): the card is selected and its own
|
||||
/// edit has the keyboard in its field.
|
||||
fn click_balloon(h: &mut H, id: u32) {
|
||||
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
|
||||
h.state_mut().canvas.comments.selected = None;
|
||||
steps(h, 2);
|
||||
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
|
||||
click_at(h, card.left_top() + vec2(30.0, 8.0));
|
||||
|
||||
@@ -5,13 +5,11 @@ use std::cell::RefCell;
|
||||
|
||||
use craft::behavior::IconId;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::theme::ControlSize;
|
||||
use craft::theme::variant::Variant;
|
||||
use craft::ui::bars::{Bar, BarKind};
|
||||
use craft::ui::buttons::{Button, ButtonOutput, IconButton, ToggleButton};
|
||||
use craft::ui::contract::{Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::display::{Divider, Text};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::value_drag::{Slider, SliderScale};
|
||||
use egui::Ui;
|
||||
@@ -211,92 +209,85 @@ fn missing_fonts(app: &mut WordApp, ui: &mut Ui) {
|
||||
fn controls(app: &mut WordApp, ui: &mut Ui, fit: usize) -> Option<egui::Rect> {
|
||||
use craft::ui::contract::Outcome as _;
|
||||
let mut rects = Vec::new();
|
||||
let _ = Row::new().gap(Gap::Section).show(ui, |ui, _| {
|
||||
let focus = if fit >= 2 {
|
||||
IconButton::command(IconId::new("focus"), CommandRef::new("view.focus")).label(tl!("Focus").to_string()).show(ui).response
|
||||
let focus = if fit >= 2 {
|
||||
IconButton::command(IconId::new("focus"), CommandRef::new("view.focus")).label(tl!("Focus").to_string()).show(ui).response
|
||||
} else {
|
||||
Button::command(CommandRef::new("view.focus"))
|
||||
.label(tl!("Focus").to_string())
|
||||
.icon(IconId::new("focus"))
|
||||
.variant(Variant::GHOST)
|
||||
.show(ui)
|
||||
.response
|
||||
};
|
||||
rects.push(focus.rect);
|
||||
// Icons only, Read Mode first and Web Layout last, each named in its tooltip, the current view on (prod
|
||||
// `chrome.rs:925-943`).
|
||||
let (mode, read) = (app.session.view.mode, app.session.view.read_mode);
|
||||
for (id, icon, name, on) in [
|
||||
("view.readMode", "readMode", tl!("Read Mode"), read),
|
||||
("view.printLayout", "printLayout", tl!("Print Layout"), mode == wordcraft_layout::ViewMode::Print && !read),
|
||||
("view.webLayout", "webLayout", tl!("Web Layout"), mode == wordcraft_layout::ViewMode::Web),
|
||||
] {
|
||||
// No command carries a checked state, so the view is given at the button (S-L415).
|
||||
let out = ToggleButton::new(name.to_string(), Bind::given(on))
|
||||
.command(CommandRef::new(id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon_only()
|
||||
.tooltip(TooltipSpec::new(name.to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response().rect);
|
||||
}
|
||||
let reading = app.session.view.read_mode;
|
||||
// Reading zoom changes only reading presentation, never the normal view zoom.
|
||||
let current = if reading { f64::from(app.session.view.read_zoom) } else { app.canvas.zoom() };
|
||||
let percent = (current * 100.0).round();
|
||||
let step = |app: &mut WordApp, plus: bool| {
|
||||
if reading {
|
||||
let value = if plus { (percent + 10.0).min(150.0) } else { (percent - 10.0).max(75.0) };
|
||||
let _ = app.run("view.readTextSize", json!({"value": value}));
|
||||
} else {
|
||||
Button::command(CommandRef::new("view.focus"))
|
||||
.label(tl!("Focus").to_string())
|
||||
.icon(IconId::new("focus"))
|
||||
.variant(Variant::GHOST)
|
||||
.show(ui)
|
||||
.response
|
||||
};
|
||||
rects.push(focus.rect);
|
||||
// Icons only, Read Mode first and Web Layout last, each named in its tooltip, the current view on (prod
|
||||
// `chrome.rs:925-943`).
|
||||
let _ = Row::new().gap(Gap::Item).show(ui, |ui, _| {
|
||||
let (mode, read) = (app.session.view.mode, app.session.view.read_mode);
|
||||
for (id, icon, name, on) in [
|
||||
("view.readMode", "readMode", tl!("Read Mode"), read),
|
||||
("view.printLayout", "printLayout", tl!("Print Layout"), mode == wordcraft_layout::ViewMode::Print && !read),
|
||||
("view.webLayout", "webLayout", tl!("Web Layout"), mode == wordcraft_layout::ViewMode::Web),
|
||||
] {
|
||||
// No command carries a checked state, so the view is given at the button (S-L415).
|
||||
let out = ToggleButton::new(name.to_string(), Bind::given(on))
|
||||
.command(CommandRef::new(id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon_only()
|
||||
.tooltip(TooltipSpec::new(name.to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response().rect);
|
||||
}
|
||||
});
|
||||
let reading = app.session.view.read_mode;
|
||||
// Reading zoom changes only reading presentation, never the normal view zoom.
|
||||
let current = if reading { f64::from(app.session.view.read_zoom) } else { app.canvas.zoom() };
|
||||
let percent = (current * 100.0).round();
|
||||
let step = |app: &mut WordApp, plus: bool| {
|
||||
if reading {
|
||||
let value = if plus { (percent + 10.0).min(150.0) } else { (percent - 10.0).max(75.0) };
|
||||
let _ = app.run("view.readTextSize", json!({"value": value}));
|
||||
} else {
|
||||
let _ = app.run(if plus { "view.zoomIn" } else { "view.zoomOut" }, json!({}));
|
||||
}
|
||||
};
|
||||
let _ = Row::new().show(ui, |ui, _| {
|
||||
let out = IconButton::new(IconId::new("wordcraft.minus"))
|
||||
.label(tl!("Zoom Out").to_string())
|
||||
.tooltip(TooltipSpec::new(tl!("Zoom Out").to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.response.clicked() {
|
||||
step(app, false);
|
||||
}
|
||||
if fit < 1 {
|
||||
let mut value = current;
|
||||
let range = if reading { 0.75..=1.5 } else { 0.1..=5.0 };
|
||||
let name = if reading { tl!("Text Size") } else { tl!("Zoom") };
|
||||
let slider = Slider::new(Bind::bound(&mut value), range)
|
||||
.size(ControlSize::Md)
|
||||
.scale(if reading { SliderScale::Linear } else { SliderScale::Log })
|
||||
// A plain rail, as the old zoom slider's (prod `chrome.rs:911`): no fill up to the thumb.
|
||||
.fill(false)
|
||||
.label(name.to_string())
|
||||
.show(ui);
|
||||
rects.push(slider.response().rect);
|
||||
if let Some(v) = slider.value() {
|
||||
let command = if reading { "view.readTextSize" } else { "view.zoom" };
|
||||
let _ = app.run(command, json!({"value": (*v * 100.0).round()}));
|
||||
}
|
||||
}
|
||||
let out = IconButton::new(IconId::new("wordcraft.plus"))
|
||||
.label(tl!("Zoom In").to_string())
|
||||
.tooltip(TooltipSpec::new(tl!("Zoom In").to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.response.clicked() {
|
||||
step(app, true);
|
||||
}
|
||||
if !reading {
|
||||
// PLAN: assumed Button::room_for (ribbon-w2, S-L418)
|
||||
let out = Button::new(format!("{percent}%")).variant(Variant::GHOST).room_for(format!("{MOST_ZOOM_PERCENT}%")).show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.clicked() {
|
||||
let _ = app.run("ui.dialog", json!({"name": "zoom"}));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
let _ = app.run(if plus { "view.zoomIn" } else { "view.zoomOut" }, json!({}));
|
||||
}
|
||||
};
|
||||
let out = IconButton::new(IconId::new("wordcraft.minus"))
|
||||
.label(tl!("Zoom Out").to_string())
|
||||
.tooltip(TooltipSpec::new(tl!("Zoom Out").to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.response.clicked() {
|
||||
step(app, false);
|
||||
}
|
||||
if fit < 1 {
|
||||
let mut value = current;
|
||||
let range = if reading { 0.75..=1.5 } else { 0.1..=5.0 };
|
||||
let name = if reading { tl!("Text Size") } else { tl!("Zoom") };
|
||||
let slider = Slider::new(Bind::bound(&mut value), range)
|
||||
.scale(if reading { SliderScale::Linear } else { SliderScale::Log })
|
||||
// A plain rail, as the old zoom slider's (prod `chrome.rs:911`): no fill up to the thumb.
|
||||
.fill(false)
|
||||
.label(name.to_string())
|
||||
.show(ui);
|
||||
rects.push(slider.response().rect);
|
||||
if let Some(v) = slider.value() {
|
||||
let command = if reading { "view.readTextSize" } else { "view.zoom" };
|
||||
let _ = app.run(command, json!({"value": (*v * 100.0).round()}));
|
||||
}
|
||||
}
|
||||
let out = IconButton::new(IconId::new("wordcraft.plus"))
|
||||
.label(tl!("Zoom In").to_string())
|
||||
.tooltip(TooltipSpec::new(tl!("Zoom In").to_string()))
|
||||
.show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.response.clicked() {
|
||||
step(app, true);
|
||||
}
|
||||
if !reading {
|
||||
// PLAN: assumed Button::room_for (ribbon-w2, S-L418)
|
||||
let out = Button::new(format!("{percent}%")).variant(Variant::GHOST).room_for(format!("{MOST_ZOOM_PERCENT}%")).show(ui);
|
||||
rects.push(out.response.rect);
|
||||
if out.clicked() {
|
||||
let _ = app.run("ui.dialog", json!({"name": "zoom"}));
|
||||
}
|
||||
}
|
||||
super::union(rects)
|
||||
}
|
||||
|
||||
@@ -436,286 +436,3 @@ fn status_bar_texts_stop_before_the_controls_in_a_narrow_window() {
|
||||
let focus = wide.get_by_role_and_label(egui::accesskit::Role::Button, "Focus").rect();
|
||||
assert!(painted_on_row_of(&wide, focus).iter().any(|(t, _)| t == "Track Changes: On"), "a wide window shows everything");
|
||||
}
|
||||
|
||||
/// #7311: the title bar's Discord community button keeps its solid accent fill and contrasting
|
||||
/// `on_strong` icon/label in both wide (pill with label) and narrow (compact icon-only) windows,
|
||||
/// across Light and Dark themes, and still dispatches `ui.discord` when clicked.
|
||||
#[test]
|
||||
fn title_bar_discord_button_keeps_accent_fill_and_icon_contrast_in_wide_and_narrow_windows() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
fn to_color32(rgba: craft::theme::Rgba) -> egui::Color32 {
|
||||
egui::Color32::from(craft::theme::Srgba::from(rgba))
|
||||
}
|
||||
|
||||
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
|
||||
for clipped in shapes {
|
||||
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(children) => {
|
||||
for child in children {
|
||||
walk(child, out);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
walk(&clipped.shape, out);
|
||||
}
|
||||
}
|
||||
|
||||
for theme in ["light", "dark"] {
|
||||
for (width, expect_compact) in [(1440.0_f32, false), (520.0_f32, true)] {
|
||||
let mut a = new_app();
|
||||
a.ui.show_discord = true;
|
||||
a.run("ui.theme", json!({"value": theme})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(width, 700.0)).build_ui_state(app_frame, a);
|
||||
crate::test_harness::frames(&mut h, 10);
|
||||
|
||||
let node = h.get_by_role_and_label(Role::Button, "Discord");
|
||||
let rect = node.rect();
|
||||
assert!(rect.is_positive(), "{theme} {width}: Discord button must be laid out");
|
||||
if expect_compact {
|
||||
assert!(rect.width() <= rect.height() + 4.0, "{theme} {width}: expected compact icon-only Discord button, got {rect:?}");
|
||||
} else {
|
||||
assert!(rect.width() > rect.height() + 10.0, "{theme} {width}: expected full labelled Discord pill, got {rect:?}");
|
||||
}
|
||||
|
||||
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
|
||||
let accent_strong = to_color32(env.tokens.color.accent.strong);
|
||||
let on_strong = to_color32(env.tokens.color.text.on_strong);
|
||||
|
||||
let mut shapes = Vec::new();
|
||||
collect_shapes(&h.output().shapes, &mut shapes);
|
||||
|
||||
let bg = shapes.iter().find_map(|s| match s {
|
||||
egui::Shape::Rect(r)
|
||||
if (r.rect.min.x - rect.min.x).abs() <= 1.5
|
||||
&& (r.rect.max.x - rect.max.x).abs() <= 1.5
|
||||
&& (r.rect.min.y - rect.min.y).abs() <= 1.5
|
||||
&& (r.rect.max.y - rect.max.y).abs() <= 1.5
|
||||
&& r.fill != egui::Color32::TRANSPARENT =>
|
||||
{
|
||||
Some(r)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let bg = bg.unwrap_or_else(|| panic!("{theme} {width}: expected a filled background rect for Discord button {rect:?}"));
|
||||
assert_eq!(bg.fill, accent_strong, "{theme} {width}: Discord button fill should be accent.strong");
|
||||
if !expect_compact {
|
||||
let min_pill_radius = (rect.height() / 2.0 - 1.5).floor().max(0.0) as u8;
|
||||
assert!(
|
||||
bg.corner_radius.nw >= min_pill_radius,
|
||||
"{theme} {width}: wide Discord button should have pill corners (>= {min_pill_radius}), got {:?}",
|
||||
bg.corner_radius
|
||||
);
|
||||
}
|
||||
|
||||
let icon_tinted_on_strong = shapes.iter().any(|s| match s {
|
||||
egui::Shape::Mesh(mesh) => {
|
||||
let bounds = mesh.calc_bounds();
|
||||
rect.expand(1.5).contains_rect(bounds) && !mesh.vertices.is_empty() && mesh.vertices.iter().all(|v| v.color == on_strong)
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
assert!(
|
||||
icon_tinted_on_strong,
|
||||
"{theme} {width}: Discord icon inside {rect:?} must paint in text.on_strong ({on_strong:?}), not accent ink"
|
||||
);
|
||||
|
||||
if !expect_compact {
|
||||
let has_label = shapes.iter().any(|s| match s {
|
||||
egui::Shape::Text(t) => rect.expand(1.5).contains_rect(s.visual_bounding_rect()) && t.galley.text() == "Discord",
|
||||
_ => false,
|
||||
});
|
||||
assert!(has_label, "{theme} {width}: wide Discord pill must paint its \"Discord\" label");
|
||||
}
|
||||
|
||||
// Clicking the button dispatches `ui.discord` and opens the community URL.
|
||||
h.get_by_role_and_label(Role::Button, "Discord").click();
|
||||
let mut opened = None;
|
||||
for _ in 0..4 {
|
||||
crate::test_harness::step(&mut h);
|
||||
for cmd in &h.output().platform_output.commands {
|
||||
if let egui::OutputCommand::OpenUrl(url) = cmd {
|
||||
opened = Some(url.url.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
opened.as_deref(),
|
||||
Some("https://discord.gg/artcraft"),
|
||||
"{theme} {width}: clicking the Discord button should open the community URL"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #7445: the title bar's Discord community button uses the dedicated single-ink `discordPill` icon
|
||||
/// with `on_strong` contrast over the solid accent pill, while the ribbon's Review › Help › Community
|
||||
/// Discord button retains the branded `discord` icon with `class="accent"` ink.
|
||||
#[test]
|
||||
fn discord_icons_distinguish_title_bar_pill_and_ribbon_accent() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
fn to_color32(rgba: craft::theme::Rgba) -> egui::Color32 {
|
||||
egui::Color32::from(craft::theme::Srgba::from(rgba))
|
||||
}
|
||||
|
||||
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
|
||||
for clipped in shapes {
|
||||
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(children) => {
|
||||
for child in children {
|
||||
walk(child, out);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
walk(&clipped.shape, out);
|
||||
}
|
||||
}
|
||||
|
||||
for theme in ["light", "dark"] {
|
||||
let mut a = new_app();
|
||||
a.ui.show_discord = true;
|
||||
a.ui.language = "en".into();
|
||||
a.run("ui.theme", json!({"value": theme})).unwrap();
|
||||
a.run("ui.tab", json!({"tab": "Help"})).unwrap();
|
||||
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 700.0)).build_ui_state(app_frame, a);
|
||||
crate::test_harness::frames(&mut h, 6);
|
||||
|
||||
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
|
||||
let on_strong = to_color32(env.tokens.color.text.on_strong);
|
||||
let accent_solid = to_color32(env.tokens.color.accent.solid);
|
||||
|
||||
let mut shapes = Vec::new();
|
||||
collect_shapes(&h.output().shapes, &mut shapes);
|
||||
|
||||
// 1. Title-bar button uses discordPill icon (single-ink text.on_strong).
|
||||
let title_bar_node = h.get_by_role_and_label(Role::Button, "Discord");
|
||||
let title_bar_rect = title_bar_node.rect();
|
||||
assert!(title_bar_rect.is_positive(), "{theme}: Title-bar Discord button must be laid out");
|
||||
|
||||
let title_bar_icon_on_strong = shapes.iter().any(|s| match s {
|
||||
egui::Shape::Mesh(mesh) => {
|
||||
let bounds = mesh.calc_bounds();
|
||||
title_bar_rect.expand(1.5).contains_rect(bounds) && !mesh.vertices.is_empty() && mesh.vertices.iter().all(|v| v.color == on_strong)
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
assert!(title_bar_icon_on_strong, "{theme}: Title-bar Discord icon inside {title_bar_rect:?} must paint in text.on_strong ({on_strong:?})");
|
||||
|
||||
// 2. Ribbon Help › Community Discord button uses discord icon with class="accent".
|
||||
let ribbon_node = h
|
||||
.query_all_by_role(Role::Button)
|
||||
.find(|n| n.accesskit_node().label().is_some_and(|l| l.contains("Discord")) && n.rect() != title_bar_rect)
|
||||
.expect("Ribbon Community Discord button");
|
||||
let ribbon_rect = ribbon_node.rect();
|
||||
assert!(ribbon_rect.is_positive(), "{theme}: Ribbon Community Discord button must be laid out");
|
||||
|
||||
let ribbon_icon_accent = shapes.iter().any(|s| match s {
|
||||
egui::Shape::Mesh(mesh) => {
|
||||
let bounds = mesh.calc_bounds();
|
||||
ribbon_rect.expand(1.5).contains_rect(bounds) && !mesh.vertices.is_empty() && mesh.vertices.iter().all(|v| v.color == accent_solid)
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
assert!(ribbon_icon_accent, "{theme}: Ribbon Community Discord icon inside {ribbon_rect:?} must paint in accent.solid ({accent_solid:?})");
|
||||
}
|
||||
}
|
||||
|
||||
/// #7319: view mode toggle buttons (Read Mode, Print Layout, Web Layout) in the status bar are grouped
|
||||
/// with `Gap::Item` intra-group spacing, separated from Focus and Zoom controls via `Gap::Section`.
|
||||
/// The Zoom slider has size `ControlSize::Md`, giving its thumb a 14 pt grab affordance matching sibling `IconButton`s.
|
||||
#[test]
|
||||
fn status_bar_view_mode_toggles_and_zoom_slider_proportions() {
|
||||
use egui::accesskit::Role;
|
||||
let h = harness(new_app());
|
||||
|
||||
let focus = h.get_by_role_and_label(Role::Button, "Focus").rect();
|
||||
let read_mode = h.get_by_role_and_label(Role::Button, "Read Mode").rect();
|
||||
let print_layout = h.get_by_role_and_label(Role::Button, "Print Layout").rect();
|
||||
let web_layout = h.get_by_role_and_label(Role::Button, "Web Layout").rect();
|
||||
let zoom_out = h.get_by_role_and_label(Role::Button, "Zoom Out").rect();
|
||||
let slider = h.get_by_role_and_label(Role::Slider, "Zoom").rect();
|
||||
let zoom_in = h.get_by_role_and_label(Role::Button, "Zoom In").rect();
|
||||
|
||||
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
|
||||
let gap_section = env.tokens.space.gap.section;
|
||||
let gap_item = env.tokens.space.gap.item;
|
||||
let gap_row = env.tokens.space.gap.row;
|
||||
let glyph_md = env.tokens.size.icon.glyph_md;
|
||||
|
||||
// 1. Spacing and grouping:
|
||||
// Focus -> View modes group gap is Gap::Section.
|
||||
let focus_to_views_gap = read_mode.min.x - focus.max.x;
|
||||
assert!(
|
||||
(focus_to_views_gap - gap_section).abs() <= 0.5,
|
||||
"Focus and Read Mode should be separated by Gap::Section ({gap_section} pt), got {focus_to_views_gap}"
|
||||
);
|
||||
|
||||
// Intra-group spacing between view mode toggle buttons is Gap::Item.
|
||||
let read_to_print_gap = print_layout.min.x - read_mode.max.x;
|
||||
let print_to_web_gap = web_layout.min.x - print_layout.max.x;
|
||||
assert!(
|
||||
(read_to_print_gap - gap_item).abs() <= 0.5,
|
||||
"Read Mode and Print Layout intra-group spacing should be Gap::Item ({gap_item} pt), got {read_to_print_gap}"
|
||||
);
|
||||
assert!(
|
||||
(print_to_web_gap - gap_item).abs() <= 0.5,
|
||||
"Print Layout and Web Layout intra-group spacing should be Gap::Item ({gap_item} pt), got {print_to_web_gap}"
|
||||
);
|
||||
|
||||
// View modes group -> Zoom controls group gap is Gap::Section.
|
||||
let views_to_zoom_gap = zoom_out.min.x - web_layout.max.x;
|
||||
assert!(
|
||||
(views_to_zoom_gap - gap_section).abs() <= 0.5,
|
||||
"Web Layout and Zoom Out should be separated by Gap::Section ({gap_section} pt), got {views_to_zoom_gap}"
|
||||
);
|
||||
|
||||
// Zoom controls intra-group spacing is default row gap (Gap::Row).
|
||||
let zoom_out_to_slider_gap = slider.min.x - zoom_out.max.x;
|
||||
let slider_to_zoom_in_gap = zoom_in.min.x - slider.max.x;
|
||||
assert!(
|
||||
(zoom_out_to_slider_gap - gap_row).abs() <= 0.5,
|
||||
"Zoom Out and Zoom Slider intra-group spacing should be Gap::Row ({gap_row} pt), got {zoom_out_to_slider_gap}"
|
||||
);
|
||||
assert!(
|
||||
(slider_to_zoom_in_gap - gap_row).abs() <= 0.5,
|
||||
"Zoom Slider and Zoom In intra-group spacing should be Gap::Row ({gap_row} pt), got {slider_to_zoom_in_gap}"
|
||||
);
|
||||
|
||||
// 2. Zoom slider thumb proportions:
|
||||
// Slider thumb is rendered as a round knob sized at glyph_md (14 pt) for ControlSize::Md.
|
||||
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
|
||||
for clipped in shapes {
|
||||
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(children) => {
|
||||
for child in children {
|
||||
walk(child, out);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
walk(&clipped.shape, out);
|
||||
}
|
||||
}
|
||||
|
||||
let mut shapes = Vec::new();
|
||||
collect_shapes(&h.output().shapes, &mut shapes);
|
||||
|
||||
let has_14pt_knob = shapes.iter().any(|s| match s {
|
||||
egui::Shape::Rect(r) => {
|
||||
let rect = r.rect;
|
||||
slider.expand(2.0).contains_rect(rect) && (rect.width() - glyph_md).abs() <= 0.5 && (rect.height() - glyph_md).abs() <= 0.5
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
assert!(has_14pt_knob, "Zoom slider should paint a {glyph_md} pt thumb (ControlSize::Md) matching 14 pt IconButton icons inside {slider:?}");
|
||||
}
|
||||
|
||||
@@ -6,10 +6,7 @@ use craft::behavior::IconId;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::menu::RibbonMenuRequest;
|
||||
use craft::review::ui::Avatar;
|
||||
use craft::theme::variant::Tone;
|
||||
use craft::theme::{ControlSize, CustomVariant, Emphasis, RadiusStep, Tokens, Variant, VariantLook};
|
||||
use craft::ui::buttons::button::ButtonStyleKey;
|
||||
use craft::ui::buttons::icon_button::IconButtonStyleKey;
|
||||
use craft::theme::ControlSize;
|
||||
use craft::ui::buttons::{Button, IconButton};
|
||||
use craft::ui::choice::Switch;
|
||||
use craft::ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
@@ -235,19 +232,6 @@ fn qat_menu(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
|
||||
out.response.rect
|
||||
}
|
||||
|
||||
/// Solid accent pill look for the full title bar Discord button (#656, #7311).
|
||||
fn discord_pill_look(tokens: &Tokens) -> VariantLook {
|
||||
VariantLook::of(Emphasis::Solid, Tone::Accent, tokens).radius(RadiusStep::Pill)
|
||||
}
|
||||
|
||||
/// Solid accent look for the compact icon-only Discord button when the title bar narrows (#5886, #7311).
|
||||
fn discord_icon_look(tokens: &Tokens) -> VariantLook {
|
||||
VariantLook::of(Emphasis::Solid, Tone::Accent, tokens)
|
||||
}
|
||||
|
||||
const DISCORD_PILL: CustomVariant = CustomVariant::new::<ButtonStyleKey>("wordcraft.discord-pill", discord_pill_look);
|
||||
const DISCORD_ICON: CustomVariant = CustomVariant::new::<IconButtonStyleKey>("wordcraft.discord-icon", discord_icon_look);
|
||||
|
||||
/// Search, the community button and the account, at the end of the bar; returns the rect they took. In a narrow
|
||||
/// window they give way by `step` (#5886, as the old bar's fit): at 1 the Discord button drops its label, at 2 the
|
||||
/// search shows its magnifier alone as well.
|
||||
@@ -256,17 +240,11 @@ fn trailing(app: &mut WordApp, ui: &mut Ui, step: usize) -> Option<egui::Rect> {
|
||||
if app.ui.show_discord {
|
||||
let tip = TooltipSpec::new(tl!("Join the ArtCraft community on Discord").to_string());
|
||||
let clicked = if step >= 1 {
|
||||
let out = IconButton::new(IconId::new("discordPill"))
|
||||
.label(tl!("Discord").to_string())
|
||||
.variant(Variant::Custom(DISCORD_ICON))
|
||||
.glyphs(GlyphRole::Tool)
|
||||
.tooltip(tip)
|
||||
.show(ui);
|
||||
let out = IconButton::new(IconId::new("discord")).label(tl!("Discord").to_string()).tooltip(tip).show(ui);
|
||||
rects.push(out.response.rect);
|
||||
out.response.clicked()
|
||||
} else {
|
||||
let out =
|
||||
Button::new(tl!("Discord").to_string()).icon(IconId::new("discordPill")).variant(Variant::Custom(DISCORD_PILL)).tooltip(tip).show(ui);
|
||||
let out = Button::new(tl!("Discord").to_string()).icon(IconId::new("discord")).tooltip(tip).show(ui);
|
||||
rects.push(out.response.rect);
|
||||
out.clicked()
|
||||
};
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//! control library
|
||||
//! - `ui.clickText {page, x, y}`: click at a page position (points from the page's top-left)
|
||||
//! - `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel`: the open dialogs' fields and answers
|
||||
//! - `ui.screenshot {path?, region?}`: PNG of the window (or of `region` `[x0, y0, x1, y1]` in points); `ui.render {path?, page?, scale?}`: page PNG
|
||||
//! - `ui.screenshot {path?}`: PNG of the window; `ui.render {path?, page?, scale?}`: page PNG
|
||||
//! (without `path`, both reply with the PNG as base64 `png`)
|
||||
//! - `ui.resize`, `ui.focus`, `ui.closeWindow`, `ui.clipboard`, `ui.replayAt`, `ui.accessTree`
|
||||
//! - `ui.parity`: feature catalog parity
|
||||
|
||||
@@ -376,13 +376,10 @@ fn handle_request(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
"ui.inspect" => ok(inspect(app, ctx)),
|
||||
"ui.parity" => ok(wordcraft_engine::catalog::parity(&app.session.registry)),
|
||||
"ui.clickText" => click_text(app, ctx, p),
|
||||
"ui.screenshot" => match craft::automation::screenshot::ScreenshotParams::from_params(p) {
|
||||
Ok(params) => {
|
||||
let token = app.next_capture_token();
|
||||
Reply::screenshot(token, params, app.active_viewport())
|
||||
}
|
||||
Err(e) => err(e),
|
||||
},
|
||||
"ui.screenshot" => {
|
||||
let token = app.next_capture_token();
|
||||
Reply::screenshot(token, s("path").map(str::to_string), app.active_viewport())
|
||||
}
|
||||
"ui.render" => {
|
||||
let page = p.get("page").and_then(Value::as_u64).unwrap_or(1);
|
||||
let scale = p.get("scale").and_then(Value::as_f64).map_or(2.0, |v| v as f32);
|
||||
|
||||
@@ -307,8 +307,7 @@ fn control_keyboard_reaches_the_background_document_once() {
|
||||
assert_eq!(body_text(h.state()), "Seed", "one Undo reverses the one text input");
|
||||
}
|
||||
|
||||
/// Control text and keys target the focused widget of a dialog, not the document. The Find dialog is modeless, so the
|
||||
/// first Escape reverts the field's typing and the second closes the dialog.
|
||||
/// Control text and keys target the focused widget of a dialog, not the document, and Escape closes it.
|
||||
#[test]
|
||||
fn control_keyboard_keeps_the_background_widget_target() {
|
||||
let mut a = app();
|
||||
@@ -326,10 +325,7 @@ fn control_keyboard_keeps_the_background_widget_target() {
|
||||
assert_eq!(body_text(h.state()), "Seed", "the Find field, not the document, owns the input");
|
||||
send(&mut h, "ui.key", json!({"key": "Escape"}));
|
||||
frames(&mut h, 6);
|
||||
assert!(open(&mut h) > 0, "the first Escape reverts the field and leaves the dialog open");
|
||||
send(&mut h, "ui.key", json!({"key": "Escape"}));
|
||||
frames(&mut h, 6);
|
||||
assert_eq!(open(&mut h), 0, "the second Escape closes the dialog");
|
||||
assert_eq!(open(&mut h), 0, "Escape closes the dialog");
|
||||
assert_eq!(body_text(h.state()), "Seed");
|
||||
}
|
||||
|
||||
|
||||
@@ -287,7 +287,7 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, layout: &DocLayout, body: &Pa
|
||||
);
|
||||
}
|
||||
}
|
||||
if out.apply.is_some() || out.discard {
|
||||
if out.apply || out.discard {
|
||||
leave(app);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ use craft::ui::contract::{
|
||||
use craft::ui::dialog::DialogId;
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::list::{ListRow, ThumbAspect, ThumbSize};
|
||||
use craft::ui::list::{ListRow, ThumbAspect};
|
||||
// PLAN: assumed `FormCx::accept` (dialogs-w5, S-L285)
|
||||
use craft::ui::patterns::form_dialogs::FormCx;
|
||||
use craft::ui::primitives::DataWidth;
|
||||
@@ -22,7 +22,7 @@ use craft::ui::runtime::env::Label;
|
||||
use craft::ui::style::DataColor;
|
||||
use craft::ui::table::Table;
|
||||
use craft::ui::text::TextField;
|
||||
use craft::ui::tile_grid::{GridZoom, Tile, TileGrid};
|
||||
use craft::ui::tile_grid::{Tile, TileGrid};
|
||||
use egui::{Color32, Ui, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -272,9 +272,6 @@ fn chart_grid(ui: &mut Ui, colors: [Color32; 3], form: &mut ChartTypeForm) -> bo
|
||||
let current = kinds.iter().position(|k| *k == form.kind).unwrap_or(0);
|
||||
let source = keyed(&positions, |i| *i);
|
||||
let out = TileGrid::<usize>::new(tl!("Chart types").to_string())
|
||||
.thumb_size(ThumbSize::Large)
|
||||
.zoom(GridZoom::Fixed(1.6))
|
||||
.aspect(19.0 / 15.0)
|
||||
.select(SelectMode::Single)
|
||||
.card_columns(3)
|
||||
// Every type shows, as in production, so the dialog's body is the one scroll.
|
||||
|
||||
@@ -26,7 +26,7 @@ pub(crate) mod symbol;
|
||||
pub use columns::DropCapForm;
|
||||
pub use date_time::DateTimeForm;
|
||||
#[cfg(test)]
|
||||
pub(crate) use date_time::date_time_previews_at;
|
||||
pub(crate) use date_time::date_time_preview_matches;
|
||||
pub use field::{DATE_FORMATS, FIELD_CATEGORIES, FIELDS, FieldForm, FieldKind, NUMBER_FORMATS, STYLEREF_SWITCHES, field_kind};
|
||||
pub(crate) use symbol::SymbolDialog;
|
||||
pub use symbol::{RECENT_SYMBOLS, RecentSymbol, SPECIAL, SUBSETS, SymbolForm, remember_symbol, subset_of};
|
||||
|
||||
@@ -35,16 +35,14 @@ const PT_DATE_FORMATS: &[&str] = &[
|
||||
"HH:mm:ss",
|
||||
];
|
||||
|
||||
/// What the Date and Time preview list shows at the instant `unix`: document values, not
|
||||
/// interface strings. The i18n audit recognizes these instead of treating month names, dates and
|
||||
/// times as labels.
|
||||
/// The date preview list consists of document values (not interface strings).
|
||||
/// The i18n audit recognizes these dynamic values instead of treating month names as UI labels.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn date_time_previews_at(unix: u64) -> impl Iterator<Item = String> {
|
||||
let offset = wordcraft_engine::cmd::local_offset_secs(unix);
|
||||
PT_DATE_FORMATS
|
||||
.iter()
|
||||
.chain(DATE_FORMATS.iter())
|
||||
.flat_map(move |picture| ["pt-BR", "en-US"].map(|lang| wordcraft_engine::cmd::insert::format_date_at_in(picture, Some(lang), unix, offset)))
|
||||
pub(crate) fn date_time_preview_matches(value: &str) -> bool {
|
||||
PT_DATE_FORMATS.iter().chain(DATE_FORMATS.iter()).any(|picture| {
|
||||
wordcraft_engine::cmd::insert::format_date_in(picture, Some("pt-BR")) == value
|
||||
|| wordcraft_engine::cmd::insert::format_date_in(picture, Some("en-US")) == value
|
||||
})
|
||||
}
|
||||
|
||||
/// State of the Word-like Insert > Date & Time dialog.
|
||||
|
||||
@@ -8,7 +8,7 @@ use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk,
|
||||
use craft::ui::display::{Kbd, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::{ListRow, ThumbAspect, ThumbSize};
|
||||
use craft::ui::list::{ListRow, ThumbAspect};
|
||||
use craft::ui::patterns::form_dialogs::{FormCx, FormDialog};
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::runtime::env::Label;
|
||||
@@ -639,7 +639,6 @@ fn recent_row(ui: &mut Ui, form: &mut SymbolForm, dark: bool) {
|
||||
let events = {
|
||||
let recent = &form.recent;
|
||||
TileGrid::new(word("Recently used symbols:"))
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.select(SelectMode::Single)
|
||||
.caption(CaptionPlace::None)
|
||||
.card_columns(RECENT_SYMBOLS)
|
||||
@@ -682,12 +681,8 @@ fn glyph_grid(ui: &mut Ui, form: &mut SymbolForm, dark: bool) -> bool {
|
||||
let font = form.shown_font().to_string();
|
||||
let events = {
|
||||
let chars = &form.chars;
|
||||
let mut grid = TileGrid::new(word("Symbols"))
|
||||
.thumb_size(ThumbSize::Medium)
|
||||
.select(SelectMode::Single)
|
||||
.max_rows(8)
|
||||
.caption(CaptionPlace::None)
|
||||
.selection(Bind::bound(&mut selection));
|
||||
let mut grid =
|
||||
TileGrid::new(word("Symbols")).select(SelectMode::Single).max_rows(8).caption(CaptionPlace::None).selection(Bind::bound(&mut selection));
|
||||
if let Some(at) = reveal {
|
||||
grid = grid.reveal(at);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
@@ -119,25 +118,6 @@ fn symbol_dialog_inserts_with_its_font() {
|
||||
assert_eq!(f.params().unwrap(), json!({"char": "\u{2665}"}));
|
||||
}
|
||||
|
||||
/// #7326: Recently used symbols and Symbols map use compact tile sizing so the dialog
|
||||
/// fits comfortably within default window bounds without vertical overflow.
|
||||
#[test]
|
||||
fn symbol_dialog_uses_compact_tile_grids() {
|
||||
let mut a = app();
|
||||
remember_symbol(&mut a, "©", "DejaVu Sans");
|
||||
let mut h = testing::harness(a);
|
||||
let id = crate::dialogs::open(h.state_mut(), "symbol", &json!({})).expect("symbol dialog opens");
|
||||
h.run_steps(3);
|
||||
assert!(h.state().dialog_host.get_dyn(id).is_some(), "the symbol dialog is open");
|
||||
let dialog = h.get_by_role_and_label(egui::accesskit::Role::Dialog, "Symbol").rect();
|
||||
assert!(dialog.height() <= 900.0, "complete dialog should fit within default desktop viewport: {}", dialog.height());
|
||||
assert!(dialog.max.y <= 900.0, "complete dialog should not overflow viewport bottom: {}", dialog.max.y);
|
||||
let symbols = h.get_by_role_and_label(egui::accesskit::Role::ListBox, "Symbols").rect();
|
||||
assert!(symbols.height() < 500.0, "symbols grid should be compact: {}", symbols.height());
|
||||
let recent = h.get_by_role_and_label(egui::accesskit::Role::ListBox, "Recently used symbols:").rect();
|
||||
assert!(recent.height() < 80.0, "recently used symbols row should be compact: {}", recent.height());
|
||||
}
|
||||
|
||||
/// The Field dialog builds the field code from its options.
|
||||
#[test]
|
||||
fn field_dialog_builds_the_instruction() {
|
||||
|
||||
@@ -14,9 +14,9 @@ use craft::ui::patterns::form_dialogs::FormCx;
|
||||
use craft::ui::primitives::{ContentPainterCx, TextRun};
|
||||
use craft::ui::runtime::env::{Label, LengthUnits, UnitKind};
|
||||
use craft::ui::sections::Section;
|
||||
use craft::ui::style::TypeRole;
|
||||
use craft::ui::style::{Corners, SurfaceKind, TypeRole};
|
||||
use craft::ui::text::{NumberField, TextField};
|
||||
use egui::{Color32, Rect, Ui, pos2};
|
||||
use egui::{Rect, Ui, pos2, vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_doc::section::NumFormat;
|
||||
@@ -293,10 +293,7 @@ impl ListForm {
|
||||
/// being edited at full strength and the others faded.
|
||||
fn preview(rows: Vec<PreviewRow>, edited: usize) -> impl Fn(&ContentPainterCx, Rect) {
|
||||
move |cx: &ContentPainterCx, rect: Rect| {
|
||||
cx.data_shapes([
|
||||
egui::Shape::rect_filled(rect, 2.0, Color32::WHITE),
|
||||
egui::Shape::rect_stroke(rect, 2.0, egui::Stroke::new(1.0, Color32::from_gray(160)), egui::StrokeKind::Inside),
|
||||
]);
|
||||
cx.surface(rect, SurfaceKind::Sunken, Corners::All);
|
||||
let row = rect.height() / LEVELS as f32;
|
||||
// Positions are points, scaled so 4.5 inches fit.
|
||||
let scale = (rect.width() - 16.0).max(1.0) / 324.0;
|
||||
@@ -305,20 +302,14 @@ fn preview(rows: Vec<PreviewRow>, edited: usize) -> impl Fn(&ContentPainterCx, R
|
||||
let top = rect.top() + row * i as f32;
|
||||
let paint = |cx: &ContentPainterCx| {
|
||||
let run = TextRun::new(r.sample.clone()).role(TypeRole::Caption);
|
||||
let layout = cx.with_draw(|draw| draw.layout(&run, f32::INFINITY));
|
||||
let width = layout.size().x;
|
||||
let width = cx.with_draw(|draw| draw.layout(&run, f32::INFINITY).size().x);
|
||||
let x = x_of(r.aligned_at);
|
||||
let number_x = match r.align.as_str() {
|
||||
"center" => x - width / 2.0,
|
||||
"right" => x - width,
|
||||
_ => x,
|
||||
};
|
||||
let spare = if layout.galley.rows.len() <= 1 { (row - layout.size().y).max(0.0) } else { 0.0 };
|
||||
cx.data_shapes([egui::Shape::galley_with_override_text_color(
|
||||
pos2(number_x, top + spare / 2.0),
|
||||
layout.galley.clone(),
|
||||
Color32::BLACK,
|
||||
)]);
|
||||
cx.with_draw(|draw| draw.text(Rect::from_min_size(pos2(number_x, top), vec2(width + 1.0, row)), &run));
|
||||
let text_x = match r.follow.as_str() {
|
||||
"space" => number_x + width + 3.0,
|
||||
"nothing" => number_x + width,
|
||||
@@ -326,7 +317,7 @@ fn preview(rows: Vec<PreviewRow>, edited: usize) -> impl Fn(&ContentPainterCx, R
|
||||
};
|
||||
let bar = Rect::from_min_max(pos2(text_x, top + row / 2.0 - 2.0), pos2(rect.right() - 8.0, top + row / 2.0 + 2.0));
|
||||
if bar.width() > 0.0 {
|
||||
let draw_bar = |cx: &ContentPainterCx| cx.data_shapes([egui::Shape::rect_filled(bar, 1.0, Color32::BLACK)]);
|
||||
let draw_bar = |cx: &ContentPainterCx| cx.data_shapes([egui::Shape::rect_filled(bar, 1.0, cx.ink())]);
|
||||
cx.faded(0.45, draw_bar);
|
||||
}
|
||||
};
|
||||
@@ -798,79 +789,4 @@ mod tests {
|
||||
a.run("review.trackingOptions", json!({"moveToMark": v})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// #7325: the Define New Multilevel List dialog preview renders an opaque white paper sheet
|
||||
/// with a crisp stroke outline across both Light and Dark themes, and renders level samples
|
||||
/// and text bars in fixed dark ink.
|
||||
#[test]
|
||||
fn define_new_multilevel_list_preview_opaque_paper_in_both_themes() {
|
||||
use egui::epaint::ClippedShape;
|
||||
|
||||
fn collect_shapes<'a>(shapes: &'a [ClippedShape], out: &mut Vec<&'a egui::Shape>) {
|
||||
for clipped in shapes {
|
||||
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(children) => {
|
||||
for child in children {
|
||||
walk(child, out);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
walk(&clipped.shape, out);
|
||||
}
|
||||
}
|
||||
|
||||
for theme in ["light", "dark"] {
|
||||
let mut a = app();
|
||||
a.run("ui.theme", json!({"value": theme})).unwrap();
|
||||
let mut h = harness(a);
|
||||
assert_eq!(h.state_mut().run("list.define", json!({})).unwrap(), json!({"pending": "defineList"}));
|
||||
h.run_steps(2);
|
||||
|
||||
let mut shapes = Vec::new();
|
||||
collect_shapes(&h.output().shapes, &mut shapes);
|
||||
|
||||
// Verify the preview paper sheet is painted as an opaque white rect
|
||||
let white_rects: Vec<_> = shapes
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
egui::Shape::Rect(r)
|
||||
if r.fill == egui::Color32::WHITE && (r.rect.width() - 80.0).abs() <= 5.0 && (r.rect.height() - 48.0).abs() <= 5.0 =>
|
||||
{
|
||||
Some(r)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(!white_rects.is_empty(), "{theme}: preview sheet must have an opaque white paper background");
|
||||
|
||||
// Verify crisp stroke border (StrokeKind::Inside with gray 160)
|
||||
let stroke_rects: Vec<_> = shapes
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
egui::Shape::Rect(r)
|
||||
if r.stroke.color == egui::Color32::from_gray(160)
|
||||
&& (r.rect.width() - 80.0).abs() <= 5.0
|
||||
&& (r.rect.height() - 48.0).abs() <= 5.0 =>
|
||||
{
|
||||
Some(r)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(!stroke_rects.is_empty(), "{theme}: preview sheet must have a crisp stroke border");
|
||||
|
||||
// Verify sample text has black override text color in both themes
|
||||
let black_text_samples: Vec<_> = shapes
|
||||
.iter()
|
||||
.filter_map(|s| match s {
|
||||
egui::Shape::Text(t) if t.override_text_color == Some(egui::Color32::BLACK) => Some(t),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(!black_text_samples.is_empty(), "{theme}: preview text samples must override text color with black");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ use craft::ui::runtime::focus::{self, FocusTarget};
|
||||
// PLAN: assumed `RuleKind` re-exported from `craft::ui::style`
|
||||
use craft::ui::style::{DataColor, RuleKind};
|
||||
use craft::ui::text::TextField;
|
||||
use craft::ui::tile_grid::{GridZoom, Tile, TileGrid};
|
||||
use craft::ui::tile_grid::{Tile, TileGrid};
|
||||
use egui::{Color32, CornerRadius, Pos2, Rect, Ui, pos2, vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -315,8 +315,6 @@ fn layout_tiles(ui: &mut Ui, theme: &[Rgb], form: &mut SmartArtForm) -> bool {
|
||||
let positions: Vec<usize> = (0..shown.len()).collect();
|
||||
let current = shown.iter().position(|l| *l == form.layout).unwrap_or(0);
|
||||
let out = TileGrid::<usize>::new(tl!("Layouts").to_string())
|
||||
.thumb_size(ThumbSize::Large)
|
||||
.zoom(GridZoom::Fixed(1.4))
|
||||
.select(SelectMode::Single)
|
||||
.card_columns(3)
|
||||
// Production's picker is three tile rows high and scrolls the rest; the cap also makes the grid the one owner
|
||||
|
||||
@@ -272,7 +272,6 @@ fn edges_on(b: &Borders, edges: &str) -> bool {
|
||||
|
||||
/// A square showing which edges a border choice draws: the drawn edges in the icon colour, the
|
||||
/// others as faint dotted guides.
|
||||
#[derive(craft::ui::contract::MemoProps)]
|
||||
struct EdgeGlyph {
|
||||
edges: &'static str,
|
||||
}
|
||||
|
||||
@@ -699,7 +699,14 @@ pub(crate) mod testing {
|
||||
|
||||
/// A harness that runs the app's logic and UI each frame in a 1440×900 window.
|
||||
pub(crate) fn harness(app: WordApp) -> Harness<'static, WordApp> {
|
||||
crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| app)
|
||||
crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
)
|
||||
}
|
||||
|
||||
/// Confirms the dialog `id` as OK does and runs the passes it takes to file the held OK and finish: the held OK
|
||||
|
||||
@@ -1785,33 +1785,3 @@ fn colour_fields_say_their_label_and_colour_in_the_interface_language() {
|
||||
assert!(present, "the translated field is {name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #7446: the SmartArt picker renders compact layout tiles capped at three rows (PICKER_HEIGHT = 304),
|
||||
/// instead of expanding each thumbnail to default card dimensions (~132×132 pt) and overflowing.
|
||||
#[test]
|
||||
fn smartart_layout_cells_keep_productions_size() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut h = app_harness(app_with("Text"));
|
||||
open_named(&mut h, "insertSmartArt", json!({}));
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
let cell = h.get_by_role_and_label(Role::ListItem, "Basic List").rect();
|
||||
assert!(cell.width() <= 80.0 && cell.height() <= 102.0, "a layout cell is 75×93, got {:?}", cell.size());
|
||||
let grid = h.get_by_role_and_label(Role::ListBox, "Layouts").rect();
|
||||
assert!(grid.height() <= 304.0, "the picker is three 96 pt rows, got {:?}", grid.size());
|
||||
}
|
||||
|
||||
/// #7456: the Insert Chart dialog renders compact chart type tiles in its 3-column gallery,
|
||||
/// instead of expanding each thumbnail to default card dimensions (~132×104 pt) and ballooning the grid.
|
||||
#[test]
|
||||
fn insert_chart_tiles_render_within_compact_bounds() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut h = app_harness(app_with("Text"));
|
||||
open_named(&mut h, "insertChart", json!({}));
|
||||
crate::test_harness::frames(&mut h, 4);
|
||||
let cell = h.get_by_role_and_label(Role::ListItem, "Clustered Column").rect();
|
||||
assert!(cell.width() <= 90.0 && cell.height() <= 92.0, "chart tile should be compact (~85×87 pt), got {:?}", cell.size());
|
||||
let grid = h.get_by_role_and_label(Role::ListBox, "Chart types").rect();
|
||||
assert!(grid.width() <= 380.0, "3-column chart types grid should not exceed comfortable dialog proportions (~360 pt), got {:?}", grid.size());
|
||||
}
|
||||
|
||||
@@ -237,15 +237,10 @@ pub fn is_word_template(path: &str) -> bool {
|
||||
/// The name an open document goes by in the window: the engine's title, with an untitled
|
||||
/// document's `Document2` in the interface language.
|
||||
pub fn display_title(d: &DocInfo) -> String {
|
||||
// NUL cannot go into an X11 window title (C string); a title of only NUL reads as untitled (#3634).
|
||||
let title: String = d.title.chars().filter(|&c| c != '\0').collect();
|
||||
if title.is_empty() && !d.title.is_empty() {
|
||||
return tl!("Document1").into();
|
||||
}
|
||||
if d.path.is_none() {
|
||||
return untitled_title(&title).unwrap_or(title);
|
||||
return untitled_title(&d.title).unwrap_or_else(|| d.title.clone());
|
||||
}
|
||||
title
|
||||
d.title.clone()
|
||||
}
|
||||
|
||||
/// `Document2` (the engine's English name for an untitled document) in the interface language,
|
||||
|
||||
@@ -14,14 +14,12 @@ use craft::behavior::IconId;
|
||||
use craft::theme::Variant;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Pad, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft::ui::display::{Badge, Elide, Icon, Shade, Text};
|
||||
use craft::ui::layout::RowAlign;
|
||||
use craft::ui::layout_components::{Row as Line, Stack};
|
||||
use craft::ui::display::{Badge, Icon, Shade, Text};
|
||||
use craft::ui::layout_components::Row as Line;
|
||||
use craft::ui::primitives::IconSpec;
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::style::{SurfaceKind, TypeRole};
|
||||
use craft::ui::sections::{DialogRole, FooterButton, GroupBox};
|
||||
use egui::Ui;
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -274,22 +272,15 @@ impl StackDialog for FontBox {
|
||||
.shade(Shade::Faint)
|
||||
.show(ui);
|
||||
for (at, g) in groups(fonts).into_iter().enumerate() {
|
||||
// One row per download, as before the craft port: the names, what they are shown as and the licence
|
||||
// note stacked at the start edge, the button at the end. The names are the document's own words.
|
||||
Stack::new().surface(SurfaceKind::Frame).pad(Pad::Regular).fill_width().id_salt(("download_group", at)).show(ui, |ui, _| {
|
||||
Line::new().fill_width().align(RowAlign::SpaceBetween).id_salt(("download", at)).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
// One line cut at the end, whole in a tooltip: one unbroken name must not push the button out.
|
||||
Text::new(g.fonts.join(", ")).role(TypeRole::BodyStrong).elide(Elide::End).show(ui);
|
||||
let shown_as = crate::i18n::fmt(
|
||||
tl!("Shown as {fonts} · {publisher}"),
|
||||
&[("fonts", &g.shown_as.join(", ")), ("publisher", g.publisher)],
|
||||
);
|
||||
Text::new(shown_as).shade(Shade::Faint).show(ui);
|
||||
if g.restricted {
|
||||
Text::new(tl!("Its licence limits who may use it: read the terms first.")).shade(Shade::Faint).show(ui);
|
||||
}
|
||||
});
|
||||
// The names are the document's own words, not interface text.
|
||||
GroupBox::new(g.fonts.join(", "), None).id_salt(("download", at)).show(ui, |ui, _| {
|
||||
let shown_as =
|
||||
crate::i18n::fmt(tl!("Shown as {fonts} · {publisher}"), &[("fonts", &g.shown_as.join(", ")), ("publisher", g.publisher)]);
|
||||
Text::new(shown_as).shade(Shade::Faint).show(ui);
|
||||
if g.restricted {
|
||||
Text::new(tl!("Its licence limits who may use it: read the terms first.")).shade(Shade::Faint).show(ui);
|
||||
}
|
||||
Line::new().show(ui, |ui, _| {
|
||||
if clicked(&Button::new(tl!("Download")).variant(Variant::PRIMARY).id_salt(("download_button", at)).show(ui)) {
|
||||
asks.push(Ask::Download(g.url.to_string()));
|
||||
}
|
||||
|
||||
@@ -233,60 +233,3 @@ fn only_so_many_documents_are_remembered() {
|
||||
assert_eq!(a.font_notice_seen.len(), REMEMBERED);
|
||||
assert_eq!(a.font_notice_seen.last(), Some(&(REMEMBERED as u64 + 49)));
|
||||
}
|
||||
|
||||
/// Each missing font's names, substitute and Download button sit in one compact row, not one under another, and a
|
||||
/// narrow window keeps them inside the box.
|
||||
#[test]
|
||||
fn each_download_is_one_row() {
|
||||
let row = |font: &str, shown: &str, url: &str| Row {
|
||||
font: font.into(),
|
||||
shown_as: vec![shown.into()],
|
||||
download: font.into(),
|
||||
publisher: "Microsoft".into(),
|
||||
url: url.into(),
|
||||
restricted: false,
|
||||
};
|
||||
for width in [1440.0, 520.0] {
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
let fonts = vec![row("Aptos", "Carlito", "https://a"), row("Cascadia Code", "Liberation Mono", "https://c")];
|
||||
open_with(&mut a, None, FontBox::new(fonts, false), DialogHooks { prepare: None, settle });
|
||||
let h = harness_sized(a, egui::vec2(width, 900.0));
|
||||
let buttons: Vec<_> = h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Download").collect();
|
||||
assert_eq!(buttons.len(), 2);
|
||||
for (button, shown) in buttons.iter().zip(["Shown as Carlito · Microsoft", "Shown as Liberation Mono · Microsoft"]) {
|
||||
let shown = h.get_by_label(shown).rect();
|
||||
let button = button.rect();
|
||||
// The button is beside the text block, level with it, not under it.
|
||||
assert!(button.min.x >= shown.max.x, "{width}: {button:?} {shown:?}");
|
||||
assert!(button.center().y < shown.max.y, "{width}: button under the text: {button:?} {shown:?}");
|
||||
assert!(button.max.x <= width, "{width}: clipped {button:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One very long unbroken family name is cut inside its card and leaves the Download button inside the card too.
|
||||
#[test]
|
||||
fn a_long_unbroken_name_stays_inside_its_card() {
|
||||
let long = format!("Aptos {}", "W".repeat(200));
|
||||
let row = Row {
|
||||
font: long.clone(),
|
||||
shown_as: vec!["Carlito".into()],
|
||||
download: "Aptos".into(),
|
||||
publisher: "Microsoft".into(),
|
||||
url: "https://a".into(),
|
||||
restricted: false,
|
||||
};
|
||||
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
open_with(&mut a, None, FontBox::new(vec![row], false), DialogHooks { prepare: None, settle });
|
||||
let h = harness_sized(a, egui::vec2(700.0, 900.0));
|
||||
let button = h.query_all_by_role_and_label(egui::accesskit::Role::Button, "Download").next().expect("button").rect();
|
||||
let name = h.get_by_label(&long).rect();
|
||||
let shown = h.get_by_label("Shown as Carlito · Microsoft").rect();
|
||||
// The card has no node of its own; the dialog it fills is the tightest box to hold both to.
|
||||
let dialog = h.query_all(egui_kittest::kittest::By::new().role(egui::accesskit::Role::Dialog)).next().expect("the dialog").rect();
|
||||
assert!(name.max.x <= button.min.x, "name runs under the button: {name:?} {button:?}");
|
||||
assert!(dialog.contains_rect(name) && dialog.contains_rect(button), "outside the dialog: {name:?} {button:?} {dialog:?}");
|
||||
// The card's padding stands between the button and the dialog's edge.
|
||||
assert!(button.max.x < dialog.max.x, "button reaches the dialog's edge: {button:?} {dialog:?}");
|
||||
assert!(name.min.x >= shown.min.x - 1.0 && name.width() > 0.0, "{name:?} {shown:?}");
|
||||
}
|
||||
|
||||
@@ -28,17 +28,7 @@ fn unmarked(text: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// When the audit began: the Date and Time preview drawn at any moment since is clock data, not
|
||||
/// interface text, whatever second the audit compares it in (#7463).
|
||||
static CLOCK_START: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
|
||||
/// Seconds of clock `clock_text` catches up in one check after the clock jumps forward.
|
||||
const CLOCK_CATCH_UP: u64 = 60;
|
||||
|
||||
thread_local! {
|
||||
// Every date/time the preview list could show since `CLOCK_START`, up to the second last
|
||||
// looked at: (next second to add, strings).
|
||||
static CLOCK_TEXTS: std::cell::RefCell<(u64, std::collections::HashSet<String>)> = std::cell::RefCell::new(Default::default());
|
||||
// Input time, advanced every frame so tooltips and animations move on.
|
||||
static TIME: Cell<f64> = const { Cell::new(0.0) };
|
||||
// Process-wide names (font families, the custom dictionary) seen at any point of the run:
|
||||
@@ -46,25 +36,6 @@ thread_local! {
|
||||
static GLOBAL_NAMES: std::cell::RefCell<std::collections::HashSet<String>> = std::cell::RefCell::new(Default::default());
|
||||
}
|
||||
|
||||
/// Whether `text` is something the Date and Time preview list showed at any second since the audit began.
|
||||
fn clock_text(text: &str) -> bool {
|
||||
let start = *CLOCK_START.get_or_init(wordcraft_engine::cmd::now_unix);
|
||||
let now = wordcraft_engine::cmd::now_unix();
|
||||
CLOCK_TEXTS.with_borrow_mut(|(next, set)| {
|
||||
if *next == 0 {
|
||||
*next = start;
|
||||
}
|
||||
// A clock stepped back still adds the current second; one stepped far forward catches up
|
||||
// a minute at most, the longest a preview waits to be checked.
|
||||
let from = (*next).min(now).max(now.saturating_sub(CLOCK_CATCH_UP));
|
||||
for unix in from..=now {
|
||||
set.extend(crate::dialogs_insert::date_time_previews_at(unix));
|
||||
}
|
||||
*next = now + 1;
|
||||
set.contains(text)
|
||||
})
|
||||
}
|
||||
|
||||
/// Remember the process-wide names drawn this frame could have come from.
|
||||
fn note_global_names() {
|
||||
GLOBAL_NAMES.with_borrow_mut(|seen| {
|
||||
@@ -153,16 +124,11 @@ fn pseudo_app(ctx: &egui::Context) -> WordApp {
|
||||
}
|
||||
|
||||
fn fresh_app(ctx: &egui::Context) -> WordApp {
|
||||
CLOCK_START.get_or_init(wordcraft_engine::cmd::now_unix);
|
||||
ctx.all_styles_mut(|s| s.interaction.tooltip_delay = 0.0);
|
||||
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_engine::sample::sample_document()), Default::default());
|
||||
// Read Aloud holds each sentence instead of starting the system's speech engine: no sound on
|
||||
// machines that have one, and no worker thread failing at its own pace on machines that don't.
|
||||
app.session.read_aloud.backend = wordcraft_engine::speech::Backend::Hold;
|
||||
// Help › Check for Updates answers "up to date" instead of asking GitHub, whose rate limit
|
||||
// would otherwise put the updater's error text on screen.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
app.stub_update_check();
|
||||
// Fonts install over the first frames.
|
||||
for _ in 0..2 {
|
||||
frame(ctx, &mut app);
|
||||
@@ -170,11 +136,6 @@ fn fresh_app(ctx: &egui::Context) -> WordApp {
|
||||
app
|
||||
}
|
||||
|
||||
/// A link: one `http(s)://` word.
|
||||
fn is_url(text: &str) -> bool {
|
||||
(text.starts_with("https://") || text.starts_with("http://")) && !text.contains(char::is_whitespace)
|
||||
}
|
||||
|
||||
/// Words (two or more ASCII letters in a row) drawn outside translation marks.
|
||||
fn english_words(text: &str) -> bool {
|
||||
let plain = unmarked(text);
|
||||
@@ -323,8 +284,7 @@ impl<'a> Exempt<'a> {
|
||||
|| matches!(plain, "WordCraft" | "WordCraft User" | "Discord" | "https://" | "auto" | "I. II. III." | "i. ii. iii." | "I, II, III, …" | "i, ii, iii, …")
|
||||
|| plain == "CONFIDENTIAL" // the watermark dialog's text: document content, kept as typed
|
||||
|| plain == "Figure 1" // the caption dialog's sample: the label goes into the document as is
|
||||
|| clock_text(plain) // the Date and Time preview: formatted from the clock
|
||||
|| is_url(plain) // a link is data, not wording
|
||||
|| crate::dialogs_insert::date_time_preview_matches(plain)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,41 +300,6 @@ fn math_placeholders_are_exact_math_input_only() {
|
||||
assert!(!set.contains("Translate"), "ordinary interface wording is not exempt");
|
||||
}
|
||||
|
||||
/// Runtime data is exempt (links, the clock's dates and times), wording is not (#7463), and
|
||||
/// Check for Updates never reaches the network.
|
||||
#[test]
|
||||
fn runtime_data_is_exempt_and_wording_is_not() {
|
||||
let ctx = crate::test_harness::context();
|
||||
let mut app = fresh_app(&ctx);
|
||||
let none = std::collections::HashSet::new();
|
||||
let exempt = Exempt::new(&app, &none);
|
||||
let now = wordcraft_engine::cmd::now_unix();
|
||||
let offset = wordcraft_engine::cmd::local_offset_secs(now);
|
||||
for picture in ["M/d/yyyy h:mm:ss am/pm", "h:mm:ss am/pm", "dddd, MMMM d, yyyy"] {
|
||||
let drawn = wordcraft_engine::cmd::insert::format_date_at_in(picture, None, now, offset);
|
||||
assert!(exempt.allows(&app, &drawn), "{drawn:?} is the clock");
|
||||
}
|
||||
assert!(exempt.allows(&app, "https://github.com/storytold/wordcraft/releases"));
|
||||
assert!(!exempt.allows(&app, "Download the newest release"), "an unwrapped sentence is reported");
|
||||
assert!(!exempt.allows(&app, "See https://example.com now"), "a sentence with a link is not a link");
|
||||
assert!(!exempt.allows(&app, "11/22/1999 5:28:50 PM"), "a time before the audit began is not the preview");
|
||||
// A stubbed check finds no update and puts no updater error on screen.
|
||||
app.run("help.checkForUpdates", json!({})).expect("Check for Updates runs");
|
||||
let calls = app.updates_rt.stub_calls.clone();
|
||||
// The check runs on a worker thread: draw at least 30 frames, then until it has run (a loaded
|
||||
// runner can be slow to start the thread, so the cap is wall-clock time, not a frame count).
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
for n in 0.. {
|
||||
let drawn = frame(&ctx, &mut app);
|
||||
assert!(drawn.iter().all(|t| !t.contains("request limit")), "{drawn:?}");
|
||||
if n >= 30 && (calls.load(std::sync::atomic::Ordering::SeqCst) > 0 || std::time::Instant::now() > deadline) {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
}
|
||||
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1, "the check went through the stub, not GitHub");
|
||||
}
|
||||
|
||||
/// Fails on interface text drawn without going through the catalog, listed per UI state, and
|
||||
/// prints the missing-translation report (`report_catalog_gaps`). `cargo xtask i18n-report` runs it
|
||||
/// with `--nocapture`; `cargo xtask test` and `ci` run it that way instead of in the main test run.
|
||||
|
||||
@@ -88,7 +88,6 @@ static WORDCRAFT_ICONS_TABLE: &[(&str, &[u8])] = &[
|
||||
("designMode", include_bytes!("../icons/designMode.svg")),
|
||||
("dictate", include_bytes!("../icons/dictate.svg")),
|
||||
("discord", include_bytes!("../icons/discord.svg")),
|
||||
("discordPill", include_bytes!("../icons/discordPill.svg")),
|
||||
("distributeCols", include_bytes!("../icons/distributeCols.svg")),
|
||||
("distributeRows", include_bytes!("../icons/distributeRows.svg")),
|
||||
("docPrefs", include_bytes!("../icons/docPrefs.svg")),
|
||||
@@ -428,18 +427,16 @@ pub fn for_command(id: &str) -> IconSpec<'static> {
|
||||
|
||||
/// An Insert › Icons library icon as a value glyph, drawn from the same path data the inserted
|
||||
/// picture is rendered from (`wordcraft_render::icon_lib`).
|
||||
#[derive(craft::ui::contract::MemoProps)]
|
||||
pub struct LibraryGlyph {
|
||||
#[memo_props(address = "library icons are items of the static `ICONS`")]
|
||||
icon: &'static wordcraft_render::icon_lib::Icon,
|
||||
pub struct LibraryGlyph<'a> {
|
||||
icon: &'a wordcraft_render::icon_lib::Icon,
|
||||
}
|
||||
|
||||
/// The glyph of a library icon; bind it to a local so `IconSpec::glyph(&glyph)` can borrow it.
|
||||
pub fn library_glyph(icon: &'static wordcraft_render::icon_lib::Icon) -> impl Glyph {
|
||||
pub fn library_glyph(icon: &wordcraft_render::icon_lib::Icon) -> impl Glyph + '_ {
|
||||
LibraryGlyph { icon }
|
||||
}
|
||||
|
||||
impl Glyph for LibraryGlyph {
|
||||
impl Glyph for LibraryGlyph<'_> {
|
||||
fn paint(&self, p: &Painter, _tokens: &UiTokens, r: Rect, c: Color32, _mirrored: bool) {
|
||||
use wordcraft_render::icon_lib::{GRID, STROKE};
|
||||
let s = r.width().min(r.height()) / GRID;
|
||||
|
||||
@@ -875,9 +875,7 @@ impl StackDialog for AddLanguage {
|
||||
let endonym = shown(&pack.name, MAX_BAR_NAME);
|
||||
let detail = if endonym == *name { pack.locale.clone() } else { format!("{endonym} · {}", pack.locale) };
|
||||
let wants = &wants;
|
||||
// The licence is the row's wrapped secondary text: `below` components share one line, and the error
|
||||
// notice (or the progress bar while installing) needs the row's width there.
|
||||
let mut row = ListRow::new(format!("{name} · {detail}")).lines(licence_hover(pack));
|
||||
let mut row = ListRow::new(format!("{name} · {detail}"));
|
||||
match progress(&pack.locale) {
|
||||
Some((done, total)) => {
|
||||
let locale = pack.locale.clone();
|
||||
@@ -899,6 +897,7 @@ impl StackDialog for AddLanguage {
|
||||
});
|
||||
}
|
||||
}
|
||||
row = row.below(Text::new(licence_hover(pack)).shade(Shade::Faint), |_| {});
|
||||
if let Some(e) = error_in(errors, &pack.locale) {
|
||||
row = row.below(Notice::new(Tone::Bad, e).id_salt(("row_error", at)), |_| {});
|
||||
}
|
||||
@@ -1633,19 +1632,6 @@ mod tests {
|
||||
assert!(a.packs_rt.errors.values().any(|e| e.contains("Only you")), "{:?}", a.packs_rt.errors);
|
||||
let tree = settled(&mut a, &ctx);
|
||||
assert!(labels(&tree).iter().any(|l| l.contains("Only you")), "the row says why: {:?}", labels(&tree));
|
||||
// The reason has room to be read: it is at least as wide as Install and within the list's width (the row may sit
|
||||
// partly below the list's visible edge).
|
||||
let rect = |pick: &dyn Fn(&egui::accesskit::Node) -> bool| {
|
||||
tree.nodes.iter().filter(|(_, n)| pick(n)).filter_map(|(_, n)| n.bounds()).collect::<Vec<_>>()
|
||||
};
|
||||
let list = rect(&|n| n.role() == egui::accesskit::Role::List && n.label() == Some("Languages"));
|
||||
let button = rect(&|n| n.label().is_some_and(|l| l.starts_with("Install (")));
|
||||
let why = rect(&|n| n.label().is_some_and(|l| l.contains("Only you")));
|
||||
let (list, button) = (list.first().expect("the list"), button.first().expect("an Install button"));
|
||||
assert!(
|
||||
why.iter().any(|w| w.width() >= button.width() && w.x0 >= list.x0 && w.x1 <= list.x1 && w.y0 < list.y1),
|
||||
"the reason is as wide as Install and within the list's width: {why:?}, Install {button:?}, list {list:?}"
|
||||
);
|
||||
// The person's own click on the same row turns it on.
|
||||
let install = spot(&tree, "Install").expect("the row still offers Install");
|
||||
user_click(&mut a, &ctx, install);
|
||||
|
||||
@@ -5,35 +5,30 @@
|
||||
use craft::behavior::{EditEvent, Preview};
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::pages::ui::PageBody;
|
||||
use craft::ui::buttons::{Button, ControlPlace, GroupLevel, ToggleButton};
|
||||
use craft::ui::buttons::{IconButton, ToggleButton};
|
||||
use craft::ui::canvas_controls::TaskBar;
|
||||
use craft::ui::contract::{Bind, Entry, Gap, Hover, Props, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, Entry, Hover, Props, Show as _};
|
||||
use craft::ui::display::Divider;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::pickers::ComboBox;
|
||||
use craft::ui::runtime::env::{Label, with_env};
|
||||
use egui::{Rect, Ui, pos2};
|
||||
use craft::ui::runtime::env::Label;
|
||||
use egui::{Rect, Ui};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::WordApp;
|
||||
use crate::colors::{Remember, Target};
|
||||
|
||||
/// Distance from the selection's start (its left edge, or right in a right-to-left paragraph) at which the bar is centred.
|
||||
const ANCHOR_INSET: f32 = 4.0;
|
||||
/// Least height of a selection rectangle (screen points) that counts as visible for anchoring.
|
||||
const MIN_VISIBLE_H: f32 = 1.0;
|
||||
|
||||
/// The part of the selection the bar anchors to: the topmost visible line of the selection inside
|
||||
/// `clip` (the scroll viewport), cut down to its visible portion. `None` when no usable part of the
|
||||
/// selection is on screen. Rectangles that only touch the clip's edge, or are not finite, are ignored.
|
||||
/// For `rtl` the result spans every run on that line (see below); otherwise it is the first such
|
||||
/// rectangle. Pure geometry, unit tested without a window.
|
||||
pub fn visible_anchor(selection_rects: impl IntoIterator<Item = Rect>, clip: Rect, rtl: bool) -> Option<Rect> {
|
||||
/// The part of the selection the bar anchors to: the topmost selection rectangle that is actually
|
||||
/// visible inside `clip` (the scroll viewport), cut down to its visible portion. `None` when no
|
||||
/// usable part of the selection is on screen. Rectangles that only touch the clip's edge, or are
|
||||
/// not finite, are ignored. Pure geometry, unit tested without a window.
|
||||
pub fn visible_anchor(selection_rects: impl IntoIterator<Item = Rect>, clip: Rect) -> Option<Rect> {
|
||||
if !clip.is_finite() || !clip.is_positive() {
|
||||
return None;
|
||||
}
|
||||
let mut first: Option<Rect> = None;
|
||||
let mut visible_rects = Vec::new();
|
||||
for sr in selection_rects {
|
||||
if !sr.is_finite() || !sr.intersects(clip) {
|
||||
continue;
|
||||
@@ -46,26 +41,8 @@ pub fn visible_anchor(selection_rects: impl IntoIterator<Item = Rect>, clip: Rec
|
||||
if first.is_none_or(|f| visible.min.y < f.min.y) {
|
||||
first = Some(visible);
|
||||
}
|
||||
visible_rects.push(visible);
|
||||
}
|
||||
let top = first?;
|
||||
if !rtl {
|
||||
return Some(top);
|
||||
}
|
||||
// A bidirectional line is emitted as several visual runs, left to right: span the whole line, so
|
||||
// its right edge (the start of a right-to-left paragraph) is not that of the first run.
|
||||
Some(visible_rects.into_iter().filter(|r| (top.min.y..=top.max.y).contains(&r.center().y)).fold(top, |u, r| u.union(r)))
|
||||
}
|
||||
|
||||
/// The x the bar centres at over `anchor`: its start edge, less the inset, mirrored for right-to-left.
|
||||
fn start_x(anchor: Rect, rtl: bool) -> f32 {
|
||||
if rtl { anchor.max.x - ANCHOR_INSET } else { anchor.min.x + ANCHOR_INSET }
|
||||
}
|
||||
|
||||
/// Whether the paragraph where the selection starts is right-to-left.
|
||||
pub(crate) fn starts_rtl(app: &WordApp) -> bool {
|
||||
let start = app.session.sel.ordered().0;
|
||||
app.session.doc.para_at(&start).is_some_and(|p| app.session.doc.styles.resolve_para(&p.props).bidi)
|
||||
first
|
||||
}
|
||||
|
||||
/// Whether the bar may be shown for the current app state.
|
||||
@@ -121,11 +98,7 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, body: &PageBody<'_>) {
|
||||
return;
|
||||
}
|
||||
let Some(anchor) = app.canvas.mini_anchor else { return };
|
||||
// The bar centres over the selection's start rather than drifting to the centre of long selections (#7447);
|
||||
// a right-to-left paragraph at the start puts it at the right edge (#7464).
|
||||
let start_x = start_x(anchor, starts_rtl(app));
|
||||
let anchor_box = Rect::from_min_max(pos2(start_x, anchor.min.y), pos2(start_x, anchor.max.y));
|
||||
let points: Vec<_> = [anchor_box.left_top(), anchor_box.right_top(), anchor_box.right_bottom(), anchor_box.left_bottom()]
|
||||
let points: Vec<_> = [anchor.left_top(), anchor.right_top(), anchor.right_bottom(), anchor.left_bottom()]
|
||||
.into_iter()
|
||||
.map(|corner| body.view.to_doc(corner))
|
||||
.collect();
|
||||
@@ -176,102 +149,79 @@ pub(crate) fn members(app: &mut WordApp, ui: &mut Ui, preview: bool) {
|
||||
if preview && let Some(held) = app.canvas.list_preview.clone() {
|
||||
app.canvas.command_preview = Some(held);
|
||||
}
|
||||
with_env(
|
||||
ui,
|
||||
|overrides| {
|
||||
overrides.values.set(GroupLevel::Compact);
|
||||
overrides.values.set(ControlPlace::Ribbon);
|
||||
},
|
||||
|ui| {
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
let mut family = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let picked = crate::widgets::font_box::font_box(ui, app, tl!("Font").to_string(), &mut family);
|
||||
follow_list(app, preview, &picked.preview, |f| Some(("format.font".to_string(), json!({"name": f}))));
|
||||
if let Some(f) = &picked.picked {
|
||||
let _ = app.run("format.font", json!({"name": f}));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let mut family = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let picked = crate::widgets::font_box::font_box(ui, app, tl!("Font").to_string(), &mut family);
|
||||
follow_list(app, preview, &picked.preview, |f| Some(("format.font".to_string(), json!({"name": f}))));
|
||||
if let Some(f) = &picked.picked {
|
||||
let _ = app.run("format.font", json!({"name": f}));
|
||||
}
|
||||
|
||||
let size = st.get("size").and_then(Value::as_f64).map(number_text).unwrap_or_default();
|
||||
let sizes: Vec<Entry<String>> = wordcraft_engine::cmd::format::SIZES
|
||||
.iter()
|
||||
.map(|s| Entry::new(number_text(f64::from(*s)), number_text(f64::from(*s))))
|
||||
.collect();
|
||||
let mut text = size.clone();
|
||||
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text), &sizes).show(ui);
|
||||
follow_list(app, preview, &combo.preview, |v| {
|
||||
v.trim().parse::<f64>().ok().map(|x| ("format.size".to_string(), json!({"size": x})))
|
||||
});
|
||||
// Only a pick or Enter applies the size: typing alone is an edit of the box's draft.
|
||||
let committed =
|
||||
combo.edit.submitted || combo.edit.events.iter().any(|e| matches!(e, EditEvent::Set { .. } | EditEvent::Commit { .. }));
|
||||
if committed
|
||||
&& text != size
|
||||
&& let Ok(x) = text.trim().parse::<f64>()
|
||||
{
|
||||
let _ = app.run("format.size", json!({"size": x}));
|
||||
}
|
||||
let size = st.get("size").and_then(Value::as_f64).map(number_text).unwrap_or_default();
|
||||
let sizes: Vec<Entry<String>> =
|
||||
wordcraft_engine::cmd::format::SIZES.iter().map(|s| Entry::new(number_text(f64::from(*s)), number_text(f64::from(*s)))).collect();
|
||||
let mut text = size.clone();
|
||||
let combo = ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut text), &sizes).show(ui);
|
||||
follow_list(app, preview, &combo.preview, |v| v.trim().parse::<f64>().ok().map(|x| ("format.size".to_string(), json!({"size": x}))));
|
||||
// Only a pick or Enter applies the size: typing alone is an edit of the box's draft.
|
||||
let committed = combo.edit.submitted || combo.edit.events.iter().any(|e| matches!(e, EditEvent::Set { .. } | EditEvent::Commit { .. }));
|
||||
if committed
|
||||
&& text != size
|
||||
&& let Ok(x) = text.trim().parse::<f64>()
|
||||
{
|
||||
let _ = app.run("format.size", json!({"size": x}));
|
||||
}
|
||||
|
||||
for (id, icon, tip) in
|
||||
[("format.growFont", "grow", tl!("Increase Font Size")), ("format.shrinkFont", "shrink", tl!("Decrease Font Size"))]
|
||||
{
|
||||
let b = Button::command(CommandRef::new(id)).icon(crate::icons::id(icon)).tooltip(tip.to_string()).show(ui);
|
||||
preview_on_hover(app, b.hover, b.response.enabled(), id, json!({}), preview);
|
||||
}
|
||||
});
|
||||
for (id, icon) in [("format.growFont", "grow"), ("format.shrinkFont", "shrink")] {
|
||||
let b = IconButton::command(crate::icons::id(icon), CommandRef::new(id)).show(ui);
|
||||
preview_on_hover(app, b.hover, b.response.enabled(), id, json!({}), preview);
|
||||
}
|
||||
});
|
||||
|
||||
Row::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
for (id, key, icon) in [
|
||||
("format.bold", "bold", "bold"),
|
||||
("format.italic", "italic", "italic"),
|
||||
("format.underline", "underline", "underline"),
|
||||
("format.strikethrough", "strike", "strike"),
|
||||
] {
|
||||
toggle(ui, app, id, icon, flag(key), preview);
|
||||
}
|
||||
let _ = Divider::vertical().show(ui);
|
||||
ui.horizontal(|ui| {
|
||||
for (id, key, icon) in [
|
||||
("format.bold", "bold", "bold"),
|
||||
("format.italic", "italic", "italic"),
|
||||
("format.underline", "underline", "underline"),
|
||||
("format.strikethrough", "strike", "strike"),
|
||||
] {
|
||||
toggle(ui, app, id, icon, flag(key), preview);
|
||||
}
|
||||
let _ = Divider::vertical().show(ui);
|
||||
|
||||
let hl = crate::colors::highlight_split(ui, app, tl!("Text Highlight Color").to_string());
|
||||
follow_list(app, preview, &hl.preview, |c| {
|
||||
wordcraft_doc::props::Highlight::ALL
|
||||
.iter()
|
||||
.find(|h| h.rgb().as_ref() == Some(c))
|
||||
.map(|h| ("format.highlight".to_string(), json!({"color": h.ooxml()})))
|
||||
});
|
||||
// PLAN: assumed ColorPick::hover (ribbon-w11, S-L413)
|
||||
let color = app.canvas.last_highlight.clone();
|
||||
preview_on_hover(app, hl.hover, hl.response.enabled(), "format.highlight", json!({"color": color}), preview);
|
||||
if hl.picked.is_some() {
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
let fc = crate::colors::font_color_split(
|
||||
ui,
|
||||
app,
|
||||
tl!("Font Color").to_string(),
|
||||
Target::cmd("format.color").remember(Remember::FontColor),
|
||||
);
|
||||
follow_list(app, preview, &fc.preview, |c| Some(("format.color".to_string(), json!({"color": c.hex()}))));
|
||||
// PLAN: assumed ColorPick::hover (ribbon-w11, S-L413)
|
||||
let color = app.canvas.last_font_color.clone();
|
||||
preview_on_hover(app, fc.hover, fc.response.enabled(), "format.color", json!({"color": color}), preview);
|
||||
if fc.picked.is_some() {
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
let _ = Divider::vertical().show(ui);
|
||||
let hl = crate::colors::highlight_split(ui, app, tl!("Text Highlight Color").to_string());
|
||||
follow_list(app, preview, &hl.preview, |c| {
|
||||
wordcraft_doc::props::Highlight::ALL
|
||||
.iter()
|
||||
.find(|h| h.rgb().as_ref() == Some(c))
|
||||
.map(|h| ("format.highlight".to_string(), json!({"color": h.ooxml()})))
|
||||
});
|
||||
// PLAN: assumed ColorPick::hover (ribbon-w11, S-L413)
|
||||
let color = app.canvas.last_highlight.clone();
|
||||
preview_on_hover(app, hl.hover, hl.response.enabled(), "format.highlight", json!({"color": color}), preview);
|
||||
if hl.picked.is_some() {
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
let fc = crate::colors::font_color_split(ui, app, tl!("Font Color").to_string(), Target::cmd("format.color").remember(Remember::FontColor));
|
||||
follow_list(app, preview, &fc.preview, |c| Some(("format.color".to_string(), json!({"color": c.hex()}))));
|
||||
// PLAN: assumed ColorPick::hover (ribbon-w11, S-L413)
|
||||
let color = app.canvas.last_font_color.clone();
|
||||
preview_on_hover(app, fc.hover, fc.response.enabled(), "format.color", json!({"color": color}), preview);
|
||||
if fc.picked.is_some() {
|
||||
app.canvas.focus_page(ui.ctx());
|
||||
}
|
||||
let _ = Divider::vertical().show(ui);
|
||||
|
||||
use wordcraft_doc::Align as A;
|
||||
for (id, icon, a) in [
|
||||
("para.alignLeft", "alignLeft", A::Left),
|
||||
("para.alignCenter", "alignCenter", A::Center),
|
||||
("para.alignRight", "alignRight", A::Right),
|
||||
("para.justify", "justify", A::Justify),
|
||||
] {
|
||||
toggle(ui, app, id, icon, align == a, preview);
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
use wordcraft_doc::Align as A;
|
||||
for (id, icon, a) in [
|
||||
("para.alignLeft", "alignLeft", A::Left),
|
||||
("para.alignCenter", "alignCenter", A::Center),
|
||||
("para.alignRight", "alignRight", A::Right),
|
||||
("para.justify", "justify", A::Justify),
|
||||
] {
|
||||
toggle(ui, app, id, icon, align == a, preview);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Keeps a bar list's preview: the framework reports `Shows` once, when the pointer reaches an
|
||||
|
||||
@@ -32,22 +32,22 @@ fn anchor_skips_rects_scrolled_offscreen_and_clips_partial_ones() {
|
||||
// Page 1's line is above the viewport, page 2's line is inside it.
|
||||
let above = Rect::from_min_size(pos2(100.0, clip.top() - 300.0), Vec2::new(200.0, 20.0));
|
||||
let inside = Rect::from_min_size(pos2(120.0, clip.top() + 50.0), Vec2::new(200.0, 20.0));
|
||||
assert_eq!(visible_anchor([above, inside], clip, false), Some(inside));
|
||||
assert_eq!(visible_anchor([above, inside], clip), Some(inside));
|
||||
// Partly scrolled off the top: anchored to the visible part, never above the viewport.
|
||||
let partial = Rect::from_min_size(pos2(100.0, clip.top() - 10.0), Vec2::new(200.0, 20.0));
|
||||
let a = visible_anchor([partial], clip, false).unwrap();
|
||||
let a = visible_anchor([partial], clip).unwrap();
|
||||
assert!((a.min.y - clip.top()).abs() < 1e-3 && (a.height() - 10.0).abs() < 1e-3);
|
||||
// Entirely off either end, or only touching the edge: nothing to anchor to.
|
||||
let below = Rect::from_min_size(pos2(100.0, clip.bottom() + 5.0), Vec2::new(200.0, 20.0));
|
||||
let touching = Rect::from_min_size(pos2(100.0, clip.top() - 20.0), Vec2::new(200.0, 20.0));
|
||||
assert_eq!(visible_anchor([above, below, touching], clip, false), None);
|
||||
assert_eq!(visible_anchor([], clip, false), None);
|
||||
assert_eq!(visible_anchor([above, below, touching], clip), None);
|
||||
assert_eq!(visible_anchor([], clip), None);
|
||||
// Input order does not matter: the topmost visible rectangle wins.
|
||||
let lower = Rect::from_min_size(pos2(100.0, clip.top() + 200.0), Vec2::new(200.0, 20.0));
|
||||
assert_eq!(visible_anchor([lower, inside], clip, false), Some(inside));
|
||||
assert_eq!(visible_anchor([lower, inside], clip), Some(inside));
|
||||
// Degenerate input is rejected, not propagated.
|
||||
let nan = Rect::from_min_size(pos2(f32::NAN, 0.0), Vec2::new(10.0, 10.0));
|
||||
assert_eq!(visible_anchor([nan], clip, false), None);
|
||||
assert_eq!(visible_anchor([nan], clip), None);
|
||||
}
|
||||
|
||||
/// The whole window over a document with `pick` selected, run until the bar is up.
|
||||
@@ -55,11 +55,6 @@ fn bar_over(pick: &str) -> H {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "The quick brown fox jumps over the lazy dog"})).unwrap();
|
||||
a.run("select.text", json!({"text": pick})).unwrap();
|
||||
bar_over_app(a)
|
||||
}
|
||||
|
||||
/// `bar_over` for an app whose document and selection are already set up.
|
||||
fn bar_over_app(a: WordApp) -> H {
|
||||
let mut h = crate::test_harness::builder().with_size(Vec2::new(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
@@ -196,20 +191,7 @@ fn every_control_fits_inside_the_bar() {
|
||||
let h = bar_over("brown fox");
|
||||
let c = canvas(&h);
|
||||
let mut rects: Vec<(String, Rect)> = Vec::new();
|
||||
for label in [
|
||||
"Bold",
|
||||
"Italic",
|
||||
"Underline",
|
||||
"Strikethrough",
|
||||
"Align Left",
|
||||
"Center",
|
||||
"Align Right",
|
||||
"Justify",
|
||||
"Text Highlight Color",
|
||||
"Font Color",
|
||||
"Increase Font Size",
|
||||
"Decrease Font Size",
|
||||
] {
|
||||
for label in ["Bold", "Italic", "Underline", "Align Left", "Center", "Align Right", "Justify", "Text Highlight Color", "Font Color"] {
|
||||
let r = member(&h, label).unwrap_or_else(|| panic!("the bar has {label}"));
|
||||
rects.push((label.to_string(), r));
|
||||
}
|
||||
@@ -222,7 +204,6 @@ fn every_control_fits_inside_the_bar() {
|
||||
.map(|n| n.rect())
|
||||
.find(|r| c.contains_rect(*r))
|
||||
.expect("the selection bar lies inside the document area");
|
||||
assert!(bar.width() < 350.0, "bar width {} must not be bloated by text labels", bar.width());
|
||||
for (name, r) in &rects {
|
||||
assert!(bar.contains_rect(*r), "{name} {r:?} must stay inside the bar {bar:?}");
|
||||
}
|
||||
@@ -233,94 +214,6 @@ fn every_control_fits_inside_the_bar() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #7482: Text Highlight Color appearance follows the picked highlight choice.
|
||||
#[test]
|
||||
fn highlight_button_appearance_follows_the_picked_colour() {
|
||||
assert_eq!(crate::colors::highlight_button_appearance("cyan"), ("highlight", Some(egui::Color32::from_rgb(0, 255, 255)), "cyan"));
|
||||
assert_eq!(crate::colors::highlight_button_appearance("none"), ("highlightNoColor", None, "none"));
|
||||
assert_eq!(crate::colors::highlight_button_appearance("unknown"), ("highlightNoColor", None, "none"));
|
||||
}
|
||||
|
||||
/// #7447: the mini toolbar anchors to the start of the selection rather than its center,
|
||||
/// so its position does not shift with the length of the selection.
|
||||
#[test]
|
||||
fn the_bar_anchors_to_the_selection_start_rather_than_its_center() {
|
||||
let h_short = bar_over("brown");
|
||||
let h_long = bar_over("brown fox jumps over the lazy dog");
|
||||
|
||||
let bar_from = |h: &H| {
|
||||
let c = canvas(h);
|
||||
h.query_all_by_role(Role::Group)
|
||||
.filter(|n| n.accesskit_node().label().as_deref() == Some("Formatting"))
|
||||
.map(|n| n.rect())
|
||||
.find(|r| c.contains_rect(*r))
|
||||
.expect("the selection bar is shown inside the canvas")
|
||||
};
|
||||
|
||||
let bar_short = bar_from(&h_short);
|
||||
let bar_long = bar_from(&h_long);
|
||||
|
||||
assert!(
|
||||
(bar_short.min.x - bar_long.min.x).abs() < 1e-3,
|
||||
"the toolbar's horizontal position must anchor to the selection start and not shift with selection length: short x={}, long x={}",
|
||||
bar_short.min.x,
|
||||
bar_long.min.x,
|
||||
);
|
||||
|
||||
// A selection starting at a later word on the same line tracks that word's start.
|
||||
let h_later = bar_over("jumps");
|
||||
let bar_later = bar_from(&h_later);
|
||||
assert!(
|
||||
bar_later.min.x > bar_short.min.x + 20.0,
|
||||
"a selection starting later on the line must place the toolbar further to the right: brown x={}, jumps x={}",
|
||||
bar_short.min.x,
|
||||
bar_later.min.x,
|
||||
);
|
||||
}
|
||||
|
||||
/// #7375: the bar's formatting controls are stacked into two rows: Row 2 controls (Bold,
|
||||
/// Align Left) sit strictly below Row 1 controls (Font, Font Size) rather than side-by-side.
|
||||
#[test]
|
||||
fn formatting_controls_stack_into_two_rows() {
|
||||
let h = bar_over("brown fox");
|
||||
let font = font_box(&h);
|
||||
let size = size_box(&h);
|
||||
let bold = member(&h, "Bold").expect("the bar has Bold");
|
||||
let align_left = member(&h, "Align Left").expect("the bar has Align Left");
|
||||
let grow = member(&h, "Increase Font Size").expect("the bar has Increase Font Size");
|
||||
let shrink = member(&h, "Decrease Font Size").expect("the bar has Decrease Font Size");
|
||||
|
||||
// Row 1 controls sit on the top row together and align in height.
|
||||
assert!((font.min.y - size.min.y).abs() < 1.0, "Font and Font Size must share Row 1: font {font:?}, size {size:?}");
|
||||
assert!((grow.min.y - size.min.y).abs() < 1.0, "Grow Font and Font Size must share Row 1: grow {grow:?}, size {size:?}");
|
||||
assert!((shrink.min.y - size.min.y).abs() < 1.0, "Shrink Font and Font Size must share Row 1: shrink {shrink:?}, size {size:?}");
|
||||
assert!((grow.height() - size.height()).abs() < 2.0, "grow height ({}) aligns with row 1 height ({})", grow.height(), size.height());
|
||||
assert!((shrink.height() - size.height()).abs() < 2.0, "shrink height ({}) aligns with row 1 height ({})", shrink.height(), size.height());
|
||||
|
||||
// Row 2 controls sit on the second row together.
|
||||
assert!((bold.min.y - align_left.min.y).abs() < 1.0, "Bold and Align Left must share Row 2: bold {bold:?}, align_left {align_left:?}");
|
||||
|
||||
// Row 2 controls sit strictly below Row 1 controls.
|
||||
assert!(bold.min.y >= font.max.y, "Bold ({bold:?}) must sit strictly below Font ({font:?})");
|
||||
assert!(bold.min.y >= size.max.y, "Bold ({bold:?}) must sit strictly below Font Size ({size:?})");
|
||||
assert!(align_left.min.y >= font.max.y, "Align Left ({align_left:?}) must sit strictly below Font ({font:?})");
|
||||
assert!(align_left.min.y >= size.max.y, "Align Left ({align_left:?}) must sit strictly below Font Size ({size:?})");
|
||||
}
|
||||
|
||||
/// #7482: Hovering the split buttons for highlight and font colour previews their command.
|
||||
#[test]
|
||||
fn hovering_the_colour_buttons_previews_their_colour() {
|
||||
let mut h = bar_over("brown fox");
|
||||
let viewport = canvas(&h);
|
||||
for (label, id) in [("Text Highlight Color", "format.highlight"), ("Font Color", "format.color")] {
|
||||
let r = member(&h, label).expect("the bar has the button");
|
||||
assert!(viewport.contains_rect(r), "{label} is inside viewport");
|
||||
hover_at(&mut h, r.center());
|
||||
let previewed = h.state().canvas.command_previewed.clone();
|
||||
assert!(previewed.is_some_and(|(p, _)| p == id), "{label} previews {id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Hovering any member of the bar previews its command on the selection; the pick is not made.
|
||||
#[test]
|
||||
fn hovering_a_bar_member_previews_its_command() {
|
||||
@@ -515,45 +408,6 @@ fn context_menu_toolbar_respects_read_mode_and_the_toolbar_preference() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #7482: The companion toolbar fits within window bounds even in a narrow window (~380 pt).
|
||||
#[test]
|
||||
fn context_menu_toolbar_fits_near_the_bottom_right_of_a_narrow_window() {
|
||||
let mut h = bar_over("brown fox");
|
||||
h.set_size(Vec2::new(380.0, 650.0));
|
||||
steps(&mut h);
|
||||
h.state_mut().run("ui.contextMenu", json!({})).unwrap();
|
||||
steps(&mut h);
|
||||
h.state_mut().canvas.context_menu_at = Some(pos2(370.0, 640.0));
|
||||
steps(&mut h);
|
||||
let screen = h.ctx.content_rect();
|
||||
let bold = h.query_all_by_label("Bold").map(|n| n.rect()).find(|r| r.min.y > 200.0).expect("the context toolbar is shown");
|
||||
assert!(screen.contains_rect(bold), "the toolbar stays inside the window: {bold:?} in {screen:?}");
|
||||
let copy = h.query_all_by_label_contains("Copy").map(|n| n.rect()).find(|r| r.min.y > 200.0).expect("the menu has Copy");
|
||||
assert!(screen.contains_rect(copy), "the menu stays inside the window: {copy:?} in {screen:?}");
|
||||
let align = h.query_all_by_label("Justify").map(|n| n.rect()).find(|r| r.min.y > 200.0).expect("the last toolbar control is shown");
|
||||
assert!(screen.contains_rect(align), "all controls fit: {align:?} in {screen:?}");
|
||||
}
|
||||
|
||||
/// #7482: The command panel under the context toolbar keeps its own width, not stretched by the toolbar.
|
||||
#[test]
|
||||
fn context_menu_panel_keeps_its_own_width_under_the_toolbar() {
|
||||
let copy_width = |toolbar: bool| {
|
||||
let mut h = bar_over("brown fox");
|
||||
h.state_mut().ui.mini_toolbar = toolbar;
|
||||
h.state_mut().run("ui.contextMenu", json!({})).unwrap();
|
||||
steps(&mut h);
|
||||
let top = canvas(&h).top();
|
||||
let copy = h.query_all_by_label_contains("Copy").map(|n| n.rect()).find(|r| r.min.y > top).expect("the menu has Copy");
|
||||
let bar = h.query_all_by_label("Justify").map(|n| n.rect()).find(|r| r.min.y > top);
|
||||
(copy, bar)
|
||||
};
|
||||
let (plain, _) = copy_width(false);
|
||||
let (copy, justify) = copy_width(true);
|
||||
let justify = justify.expect("the context toolbar is shown");
|
||||
assert!((copy.width() - plain.width()).abs() < 0.5, "panel {} vs plain menu {}", copy.width(), plain.width());
|
||||
assert!(copy.max.x + 20.0 < justify.max.x, "the panel ({copy:?}) is narrower than the toolbar ({justify:?})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_in_a_ribbon_list_does_not_open_the_context_menu() {
|
||||
let mut h = bar_over("brown fox");
|
||||
@@ -768,67 +622,3 @@ fn a_clicked_member_holds_its_preview_until_the_pointer_leaves() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bar's centre, and the selection's first visible line (the anchor) it hangs from.
|
||||
fn bar_centre_and_anchor(h: &H) -> (f32, Rect) {
|
||||
let c = canvas(h);
|
||||
let bar = h
|
||||
.query_all_by_role(Role::Group)
|
||||
.filter(|n| n.accesskit_node().label().as_deref() == Some("Formatting"))
|
||||
.map(|n| n.rect())
|
||||
.find(|r| c.contains_rect(*r))
|
||||
.expect("the selection bar is shown inside the canvas");
|
||||
(bar.center().x, h.state().canvas.mini_anchor.expect("the selection has an anchor"))
|
||||
}
|
||||
|
||||
/// A paragraph long enough to wrap onto several lines, with a selection from `from_char` to its end.
|
||||
fn wrapped_selection(text: &str, rtl: bool, from_char: usize) -> H {
|
||||
let text = text.repeat(40);
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text(&text)), Default::default());
|
||||
if rtl {
|
||||
a.run("select.all", json!({})).unwrap();
|
||||
a.run("para.rtl", json!({})).unwrap();
|
||||
}
|
||||
let off = text.char_indices().nth(from_char).map_or(0, |(i, _)| i);
|
||||
let end = text.len();
|
||||
a.session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, off), focus: wordcraft_doc::Pos::body(0, end) };
|
||||
bar_over_app(a)
|
||||
}
|
||||
|
||||
/// #7464: in a right-to-left paragraph the selection starts at the right, so the bar sits there,
|
||||
/// not at the left margin where the selection's first line ends.
|
||||
#[test]
|
||||
fn the_bar_anchors_at_the_right_in_a_right_to_left_paragraph() {
|
||||
let h = wrapped_selection("سلام دنیا ", true, 12);
|
||||
let (x, anchor) = bar_centre_and_anchor(&h);
|
||||
assert!(anchor.width() > 100.0, "the first selected line is a wide rect: {anchor:?}");
|
||||
assert!((x - anchor.max.x).abs() < (x - anchor.min.x).abs(), "the bar x={x} is nearer the start (right) edge of {anchor:?}");
|
||||
}
|
||||
|
||||
/// #7464: a left-to-right selection from mid-line 1 to a later line keeps the bar at its start.
|
||||
#[test]
|
||||
fn the_bar_anchors_at_the_start_of_a_multi_line_left_to_right_selection() {
|
||||
let h = wrapped_selection("The quick brown fox ", false, 12);
|
||||
let (x, anchor) = bar_centre_and_anchor(&h);
|
||||
assert!(anchor.width() > 100.0, "the first selected line is a wide rect: {anchor:?}");
|
||||
assert!((x - anchor.min.x).abs() < (x - anchor.max.x).abs(), "the bar x={x} is nearer the start (left) edge of {anchor:?}");
|
||||
}
|
||||
|
||||
/// #7464: a right-to-left line mixing Arabic with Latin words or digits is several visual runs
|
||||
/// (emitted left to right): the bar hangs from the whole line's right edge, not the first run's.
|
||||
#[test]
|
||||
fn the_anchor_spans_every_run_on_the_topmost_line() {
|
||||
let clip = vp();
|
||||
let run = |x: f32, y: f32| Rect::from_min_size(pos2(x, y), Vec2::new(50.0, 20.0));
|
||||
let line1 = [run(200.0, 100.0), run(300.0, 100.0), run(250.0, 100.0)];
|
||||
let later = run(900.0, 130.0);
|
||||
let rects = [line1[0], line1[1], line1[2], later];
|
||||
let a = visible_anchor(rects, clip, true).unwrap();
|
||||
assert!(line1.iter().all(|r| a.max.x >= r.max.x && a.min.x <= r.min.x), "spans every run of line 1: {a:?}");
|
||||
assert!(a.max.x < later.min.x && a.max.y <= later.min.y, "the later line is excluded: {a:?}");
|
||||
let x = start_x(a, true);
|
||||
assert!((x - a.max.x).abs() < (x - a.min.x).abs(), "RTL bar x={x} is nearer the line's right edge {}, not the left {}", a.max.x, a.min.x);
|
||||
// Left to right keeps the first rectangle (vertical text stacks whole lines at one y-range).
|
||||
let l = visible_anchor(rects, clip, false).unwrap();
|
||||
assert!(l.min.x == line1[0].min.x && l.max.x < a.max.x, "LTR anchor is the top run only: {l:?}");
|
||||
}
|
||||
|
||||
@@ -705,38 +705,40 @@ impl PreferencesModel for OptionsModel<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
fn custom_row(&mut self, ui: &mut Ui, key: &str) -> bool {
|
||||
fn custom_row(&mut self, ui: &mut Ui, key: &str) {
|
||||
match key {
|
||||
"general.defaultApp" => default_app_row(self.app, ui),
|
||||
"proofing.autoCorrect" => self.command_button(ui, tl!("AutoCorrect Options"), "tools.autocorrect"),
|
||||
"proofing.autoCorrect" => {
|
||||
if Button::new(tl!("AutoCorrect Options")).show(ui).clicked() {
|
||||
self.run("tools.autocorrect", json!({}));
|
||||
}
|
||||
}
|
||||
"proofing.customDictionaryFile" => self.custom_dictionary_file(ui),
|
||||
"proofing.customDictionary" => self.custom_dictionary(ui),
|
||||
"language.proofingLanguage" => {
|
||||
Text::new(self.strings.proofing_language.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
|
||||
false
|
||||
}
|
||||
// PLAN: assumed `your_languages(app: &mut WordApp, ui: &mut Ui)` (chrome-w12)
|
||||
"language.yourLanguages" => {
|
||||
crate::language_packs::your_languages(self.app, ui);
|
||||
false
|
||||
"language.yourLanguages" => crate::language_packs::your_languages(self.app, ui),
|
||||
"language.dictionaryFiles" => dictionary_files(ui),
|
||||
"advanced.customizeKeyboard" => {
|
||||
if Button::new(tl!("Customize…")).show(ui).clicked() {
|
||||
self.run("tools.customizeKeyboard", json!({}));
|
||||
}
|
||||
}
|
||||
"language.dictionaryFiles" => {
|
||||
dictionary_files(ui);
|
||||
false
|
||||
"advanced.customizeRibbon" if Button::new(tl!("Customize…")).show(ui).clicked() => {
|
||||
self.run("tools.customizeRibbon", json!({}));
|
||||
}
|
||||
"advanced.customizeKeyboard" => self.command_button(ui, tl!("Customize…"), "tools.customizeKeyboard"),
|
||||
"advanced.customizeRibbon" => self.command_button(ui, tl!("Customize…"), "tools.customizeRibbon"),
|
||||
_ => false,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn custom_page(&mut self, ui: &mut Ui, page: &str) -> bool {
|
||||
fn custom_page(&mut self, ui: &mut Ui, page: &str) {
|
||||
if page == "agents" {
|
||||
Text::new(tl!("Agents")).role(TypeRole::Heading).show(ui);
|
||||
Text::new(tl!("Every command is available to scripts and AI agents: run `wordcraft-cli mcp` for an MCP server, or start the app with `--control <port>` for the JSON control channel."))
|
||||
.show(ui);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn reset_page(&mut self, page: &str) {
|
||||
@@ -760,32 +762,21 @@ impl OptionsModel<'_> {
|
||||
/// Enter or focus loss. The field is given the saved path and never writes it: the framework
|
||||
/// holds the draft while an edit is open and drops it when the saved path changes (an agent's
|
||||
/// `file.options`) or the page is left, so no edit open always shows the saved path.
|
||||
/// A button that runs `command` when clicked; whether it did.
|
||||
fn command_button(&mut self, ui: &mut Ui, label: impl Into<craft::ui::runtime::env::Label>, command: &str) -> bool {
|
||||
let clicked = Button::new(label).show(ui).clicked();
|
||||
if clicked {
|
||||
self.run(command, json!({}));
|
||||
}
|
||||
clicked
|
||||
}
|
||||
|
||||
fn custom_dictionary_file(&mut self, ui: &mut Ui) -> bool {
|
||||
fn custom_dictionary_file(&mut self, ui: &mut Ui) {
|
||||
let saved = self.app.session.prefs.custom_dictionary.clone().unwrap_or_default();
|
||||
let out = TextField::new(tl!("Dictionary file:"), Bind::given(saved)).limit(None).show(ui);
|
||||
let committed = out.events.into_iter().find_map(|event| match event {
|
||||
EditEvent::Commit { after, .. } => Some(after),
|
||||
_ => None,
|
||||
});
|
||||
let changed = committed.is_some();
|
||||
if let Some(path) = committed {
|
||||
self.set("proofing.customDictionaryFile", PrefValue::Text(path));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The custom dictionary: the words Add to Dictionary kept, each with a Remove button, and a
|
||||
/// field to add one.
|
||||
fn custom_dictionary(&mut self, ui: &mut Ui) -> bool {
|
||||
fn custom_dictionary(&mut self, ui: &mut Ui) {
|
||||
let words = wordcraft_engine::proof::user_dictionary();
|
||||
if words.is_empty() {
|
||||
Text::new(tl!("No words yet. Add to Dictionary on a misspelled word puts it here.")).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
|
||||
@@ -802,10 +793,8 @@ impl OptionsModel<'_> {
|
||||
}
|
||||
})
|
||||
});
|
||||
let mut changed = false;
|
||||
if let Some(w) = removed.take() {
|
||||
self.options(json!({"removeWords": [w]}));
|
||||
changed = true;
|
||||
}
|
||||
// Enter or Add files the draft and clears it.
|
||||
Row::new().show(ui, |ui, cx| {
|
||||
@@ -817,10 +806,8 @@ impl OptionsModel<'_> {
|
||||
if ok && (add || out.submitted) {
|
||||
self.options(json!({"addWords": [word]}));
|
||||
draft.clear();
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
@@ -874,7 +861,7 @@ fn language_name(lang: wordcraft_engine::proof::ProofLang) -> &'static str {
|
||||
/// the host can (`Services::make_default_app`: Windows opens Default apps, Linux and BSD use
|
||||
/// `xdg-mime`); macOS shows how to do it in Finder, the web shows nothing.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn default_app_row(app: &mut WordApp, ui: &mut Ui) -> bool {
|
||||
fn default_app_row(app: &mut WordApp, ui: &mut Ui) {
|
||||
if app.services.make_default_app.is_some() {
|
||||
let hint = if cfg!(target_os = "windows") {
|
||||
tl!("Opens Settings › Default apps, where you choose WordCraft for .docx and the other document types.")
|
||||
@@ -885,7 +872,6 @@ fn default_app_row(app: &mut WordApp, ui: &mut Ui) -> bool {
|
||||
// Only a person's click changes system defaults: an automation client's pass does not.
|
||||
if clicked && !WindowHost::of(ui.ctx()).injected_pass() {
|
||||
let _ = app.make_default_app();
|
||||
return true;
|
||||
}
|
||||
} else if cfg!(target_os = "macos") {
|
||||
Text::new(tl!("To open Word documents with WordCraft by default: select one in Finder, choose File › Get Info, pick WordCraft under Open with, then click Change All."))
|
||||
@@ -893,14 +879,11 @@ fn default_app_row(app: &mut WordApp, ui: &mut Ui) -> bool {
|
||||
.shade(Shade::Faint)
|
||||
.show(ui);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The web has no system default apps to change: nothing to show.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn default_app_row(_app: &mut WordApp, _ui: &mut Ui) -> bool {
|
||||
false
|
||||
}
|
||||
fn default_app_row(_app: &mut WordApp, _ui: &mut Ui) {}
|
||||
|
||||
/// The Options page.
|
||||
pub fn page(app: &mut WordApp, ui: &mut Ui) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use craft::behavior::{EditEvent, IconId, Selection};
|
||||
use craft::behavior::{EditEvent, IconId};
|
||||
use craft::review::ThreadId;
|
||||
use craft::review::ui::CommentsPanelState;
|
||||
use craft::ui::buttons::Button;
|
||||
@@ -192,7 +192,7 @@ fn reply_id(document: u64, id: u32) -> egui::Id {
|
||||
/// keeps the field open with its text.
|
||||
fn reply_field(app: &mut WordApp, ui: &mut Ui, document: u64, id: u32) -> bool {
|
||||
let thread = thread_of(app, id);
|
||||
let selected = app.canvas.comments.selected.lead.as_ref().is_some_and(|t| t.0 == thread.0);
|
||||
let selected = app.canvas.comments.selected.as_ref().is_some_and(|t| t.0 == thread.0);
|
||||
let shown = if selected { app.canvas.comments.reply.clone() } else { String::new() };
|
||||
let editable = crate::app::command_board::command_enabled(app, "review.reply");
|
||||
let field = reply_id(document, id);
|
||||
@@ -208,12 +208,12 @@ fn reply_field(app: &mut WordApp, ui: &mut Ui, document: u64, id: u32) -> bool {
|
||||
match event {
|
||||
EditEvent::Update { value, .. } => {
|
||||
let d = drafts(app);
|
||||
d.selected = Selection::single(thread);
|
||||
d.selected = Some(thread);
|
||||
d.reply = value.clone();
|
||||
}
|
||||
EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } => {
|
||||
let d = drafts(app);
|
||||
d.selected = Selection::single(thread);
|
||||
d.selected = Some(thread);
|
||||
d.reply = after.clone();
|
||||
done = commit_reply(app, id).is_ok();
|
||||
}
|
||||
@@ -235,7 +235,7 @@ fn reply_field(app: &mut WordApp, ui: &mut Ui, document: u64, id: u32) -> bool {
|
||||
pub(crate) fn commit_reply(app: &mut WordApp, id: u32) -> Result<(), String> {
|
||||
let thread = thread_of(app, id);
|
||||
let d = drafts(app);
|
||||
if !d.selected.lead.as_ref().is_some_and(|t| t.0 == thread.0) {
|
||||
if !d.selected.as_ref().is_some_and(|t| t.0 == thread.0) {
|
||||
return Ok(());
|
||||
}
|
||||
let text = d.reply.clone();
|
||||
@@ -266,7 +266,7 @@ pub(crate) fn flush_comment_drafts(app: &mut WordApp) -> Result<(), String> {
|
||||
first = r;
|
||||
}
|
||||
}
|
||||
let selected = drafts(app).selected.lead.as_ref().and_then(|t| u32::try_from(t.0).ok());
|
||||
let selected = drafts(app).selected.as_ref().and_then(|t| u32::try_from(t.0).ok());
|
||||
if let Some(id) = selected {
|
||||
let r = commit_reply(app, id);
|
||||
if first.is_ok() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Localized print-page wording around the shared, backend-independent controls.
|
||||
pub use craft::print::ui::{Destination, Discover, Duplex, Feedback, Printer, Settings, State};
|
||||
pub use craft::print::ui::{Discover, Duplex, Feedback, Printer, Settings, State};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::print_page::{NO_SCALING, ORIENTATIONS, PAGES_PER_SHEET, PARITIES, PrintPage, RANGES};
|
||||
@@ -43,7 +43,7 @@ pub fn settings(state: &mut State, params: &Value, discover: Option<&Discover>)
|
||||
if !state.printers.iter().any(|available| available.name == printer) {
|
||||
return Err("printer must be a name from the discovered list".into());
|
||||
}
|
||||
next.destination = Destination::Printer(printer.to_owned());
|
||||
next.printer = printer.to_owned();
|
||||
}
|
||||
if let Some(value) = object.get("copies") {
|
||||
let copies = value.as_u64().filter(|copies| (1..=999).contains(copies)).ok_or("copies must be an integer from 1 to 999")?;
|
||||
@@ -82,7 +82,7 @@ pub fn settings(state: &mut State, params: &Value, discover: Option<&Discover>)
|
||||
Some(_) => ("idle", ""),
|
||||
};
|
||||
Ok(json!({
|
||||
"printer": printer_name(&state.settings), "copies": state.settings.copies,
|
||||
"printer": state.settings.printer, "copies": state.settings.copies,
|
||||
"duplex": match state.settings.duplex { None => "printerDefault", Some(Duplex::LongEdge) => "longEdge", Some(Duplex::ShortEdge) => "shortEdge", Some(_) => "off" },
|
||||
"grayscale": state.settings.grayscale,
|
||||
"printers": state.printers.iter().map(|printer| json!({"name": printer.name, "default": printer.default})).collect::<Vec<Value>>(),
|
||||
@@ -228,19 +228,11 @@ pub fn pwg_media(paper: &str) -> Option<&'static str> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The chosen printer's name; empty when none is chosen or the destination is not a printer.
|
||||
pub(crate) fn printer_name(settings: &Settings) -> &str {
|
||||
match &settings.destination {
|
||||
Destination::Printer(name) => name,
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// The spooler's job for `settings`: the app's choices, shrink-to-fit paper and the options list.
|
||||
// PLAN: assumed `craft::print` is reachable from ui-egui (the Job is built here, as apps/wordcraft/src/print.rs did).
|
||||
fn job_of(settings: &Settings, collate: bool, options: Vec<(String, String)>) -> craft::print::Job {
|
||||
craft::print::Job {
|
||||
printer: Some(printer_name(settings)).filter(|name| !name.is_empty()).map(str::to_owned),
|
||||
printer: (!settings.printer.is_empty()).then(|| settings.printer.clone()),
|
||||
copies: settings.copies.clamp(1, 999),
|
||||
collate,
|
||||
duplex: settings.duplex.map(|value| match value {
|
||||
@@ -262,11 +254,6 @@ pub fn submit(app: &mut crate::WordApp, params: &Value) -> Result<Value, String>
|
||||
let Some(spool) = app.services.print.clone() else {
|
||||
return Err("printing to the system print dialog isn't available here; export a PDF instead".into());
|
||||
};
|
||||
// Save as PDF is WordCraft's own route, not the spooler's.
|
||||
if app.printing.settings.destination == Destination::File {
|
||||
app.print_pdf_dialog();
|
||||
return Ok(json!({"saveAsPdf": true}));
|
||||
}
|
||||
let chooses = spool.chooses_printer();
|
||||
if chooses && !app.printing.ready() {
|
||||
return Err("Select an available printer in File > Print before submitting.".into());
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::ops::RangeInclusive;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::menu::ribbon::{RibbonGroup, RibbonRow};
|
||||
use craft::ui::buttons::{Arrangement, Button};
|
||||
use craft::ui::contract::{Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, TooltipSpec, Trigger};
|
||||
use craft::ui::contract::{Bind, BodyCx, Gap, Props as _, Show as _, ShowContainer as _, Trigger};
|
||||
use craft::ui::controls::disclosure::DisclosureGlyph;
|
||||
use craft::ui::display::Divider;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
@@ -18,6 +18,11 @@ use super::{Ui, WordApp, json};
|
||||
use crate::icons;
|
||||
use crate::undo_marks::apply_edits;
|
||||
|
||||
/// Whether the command a menu is about can run now; a menu about no command is always open.
|
||||
pub(super) fn about_enabled(ctx: &egui::Context, about: &str) -> bool {
|
||||
about.is_empty() || craft::ui::runtime::commands::resolve(ctx, CommandRef::new(about)).enabled
|
||||
}
|
||||
|
||||
/// The arrow after the label of a ribbon menu button: the small filled triangle of the old ribbon.
|
||||
pub(crate) static MENU_ARROW: DisclosureGlyph = DisclosureGlyph::new(1.0);
|
||||
|
||||
@@ -25,16 +30,12 @@ pub(crate) static MENU_ARROW: DisclosureGlyph = DisclosureGlyph::new(1.0);
|
||||
/// `face` is the caller's button; `about` is that command's id, `None` for a menu about no command.
|
||||
pub(crate) fn menu_button(
|
||||
ui: &mut Ui,
|
||||
mut face: Button<'_>,
|
||||
face: Button<'_>,
|
||||
name: impl Into<Label>,
|
||||
about: Option<&str>,
|
||||
body: impl FnMut(&mut Ui, &mut BodyCx<'_>),
|
||||
) -> MenuOutput {
|
||||
let resolved = about.filter(|id| !id.is_empty()).map(|id| craft::ui::runtime::commands::resolve(ui.ctx(), CommandRef::new(id)));
|
||||
let enabled = resolved.as_ref().is_none_or(|cmd| cmd.enabled);
|
||||
if !enabled && let Some(hint) = resolved.as_ref().and_then(|cmd| cmd.hint.clone()) {
|
||||
face = face.tooltip(TooltipSpec::new(hint.clone()).disabled_text(hint));
|
||||
}
|
||||
let enabled = about_enabled(ui.ctx(), about.unwrap_or(""));
|
||||
let opener = face.trailing_icon(IconSpec::glyph(&MENU_ARROW)).enabled(enabled).show(ui);
|
||||
Menu::new(name).opened_by(&opener.response, Trigger::Click).show(ui, body).output
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use craft::ui::primitives::IconSpec;
|
||||
use craft::ui::primitives::textures::Revision;
|
||||
use craft::ui::runtime::commands::resolve;
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::tile_grid::{CaptionPlace, GridZoom, Tile, TileGrid};
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
use egui::{Color32, ColorImage, Pos2, Ui};
|
||||
use serde_json::json;
|
||||
use wordcraft_doc::props::CharProps;
|
||||
@@ -90,9 +90,32 @@ pub(crate) fn style_tile_image(doc: &Document, id: &str, ppp: f32, dark_page: bo
|
||||
if dark && !dark_page {
|
||||
dim(&mut img);
|
||||
}
|
||||
// The old ribbon drew the sample letters on the ribbon itself, with no page behind them.
|
||||
if !dark_page {
|
||||
clear_white_paper(&mut img);
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
/// Takes the white paper out of `img`: each pixel becomes the colour that, laid over white, gives
|
||||
/// it, so the letters keep their edges over any background and the paper is transparent.
|
||||
fn clear_white_paper(img: &mut ColorImage) {
|
||||
for px in &mut img.pixels {
|
||||
let [r, g, b, _] = px.to_array();
|
||||
let alpha = 255 - r.min(g).min(b);
|
||||
if alpha == 0 {
|
||||
*px = egui::Color32::TRANSPARENT;
|
||||
continue;
|
||||
}
|
||||
// c = a * x + (1 - a) * 255, solved for x.
|
||||
let unlay = |c: u8| -> u8 {
|
||||
let lifted = i32::from(c) - (255 - i32::from(alpha));
|
||||
(lifted.max(0) * 255 / i32::from(alpha)).clamp(0, 255) as u8
|
||||
};
|
||||
*px = egui::Color32::from_rgba_unmultiplied(unlay(r), unlay(g), unlay(b), alpha);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Style Sets tile: a title, a heading and a paragraph in the set `name`.
|
||||
fn style_set_image(name: &str, ppp: f32, dark: bool) -> ColorImage {
|
||||
let mut s = wordcraft_engine::Session::new(Document::new());
|
||||
@@ -230,10 +253,7 @@ pub(crate) fn table_styles(ui: &mut Ui, app: &mut WordApp) {
|
||||
let doc = &app.session.doc;
|
||||
let makers: Vec<Maker<'_>> = entries.iter().map(|(id, _)| Box::new(move || table_style_image(doc, id, ppp, dark)) as Maker<'_>).collect();
|
||||
let items = image_items("table", &entries, &makers, ppp, revision);
|
||||
// Each tile shows a 5×4 table sample at the large thumbnail size in the 3:2 landscape
|
||||
// ratio `table_style_image` renders (112×74 pt including margins), matching the sibling
|
||||
// `Styles` and `Style Sets` galleries and v0.18.1's ribbon previews.
|
||||
Gallery::new(tl!("Table Styles"), &items, None).tiles(7, 4).thumb(ThumbSize::Large).aspect(ThumbAspect::new(3, 2)).show(ui)
|
||||
Gallery::new(tl!("Table Styles"), &items, None).tiles(7, 4).show(ui)
|
||||
};
|
||||
if let Some(style) = out.picked {
|
||||
let _ = app.run("table.style", json!({"style": style}));
|
||||
@@ -301,8 +321,7 @@ pub(crate) fn wordart(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp, comma
|
||||
.select(SelectMode::None)
|
||||
.activate(ActivateOn::Click)
|
||||
.card_columns(WORDART_COLUMNS)
|
||||
.thumb_size(ThumbSize::Small)
|
||||
.zoom(GridZoom::Fixed(2.0))
|
||||
.content_cells()
|
||||
// Every style shows, as in production; the menu's body is the one scroll.
|
||||
.natural_height(true)
|
||||
.caption(CaptionPlace::None)
|
||||
@@ -322,82 +341,19 @@ pub(crate) fn wordart(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp, comma
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// White paper turns transparent and black letters stay black and opaque.
|
||||
#[test]
|
||||
fn white_paper_clears_and_ink_stays() {
|
||||
let mut img = egui::ColorImage::new([3, 1], vec![egui::Color32::WHITE, egui::Color32::BLACK, egui::Color32::from_rgb(128, 128, 128)]);
|
||||
super::clear_white_paper(&mut img);
|
||||
assert_eq!(img.pixels[0], egui::Color32::TRANSPARENT);
|
||||
assert_eq!(img.pixels[1], egui::Color32::BLACK);
|
||||
assert_eq!(img.pixels[2].a(), 127);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Relative luminance (WCAG) of an opaque sRGB colour, in `0.0..=1.0`.
|
||||
fn rel_luma(c: Color32) -> f64 {
|
||||
let [r, g, b, _] = c.to_srgba_unmultiplied();
|
||||
let lin = |u: u8| {
|
||||
let s = f64::from(u) / 255.0;
|
||||
if s <= 0.04045 { s / 12.92 } else { ((s + 0.055) / 1.055).powf(2.4) }
|
||||
};
|
||||
0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
|
||||
}
|
||||
|
||||
/// WCAG contrast ratio between two opaque colours.
|
||||
fn contrast_ratio(a: Color32, b: Color32) -> f64 {
|
||||
let (la, lb) = (rel_luma(a), rel_luma(b));
|
||||
let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
|
||||
(hi + 0.05) / (lo + 0.05)
|
||||
}
|
||||
|
||||
/// The background paper pixel: the most frequent colour in the tile.
|
||||
fn paper_color(img: &ColorImage) -> Color32 {
|
||||
let mut counts = std::collections::HashMap::<Color32, usize>::new();
|
||||
for &px in &img.pixels {
|
||||
*counts.entry(px).or_insert(0) += 1;
|
||||
}
|
||||
counts.into_iter().max_by_key(|&(_, n)| n).expect("non-empty tile").0
|
||||
}
|
||||
|
||||
/// #7309: Styles gallery tiles keep opaque paper in light and dark modes (dimmed in dark mode,
|
||||
/// matching #663 and sibling galleries) so dark style ink remains legible, and leave Switch
|
||||
/// Modes' dark page untouched by interface dimming.
|
||||
#[test]
|
||||
fn style_tile_keeps_opaque_paper_and_legible_contrast_in_dark_mode() {
|
||||
let doc = Document::new();
|
||||
let light = style_tile_image(&doc, "Normal", 1.0, false, false);
|
||||
let dark = style_tile_image(&doc, "Normal", 1.0, false, true);
|
||||
let dark_page_light_ui = style_tile_image(&doc, "Normal", 1.0, true, false);
|
||||
let dark_page_dark_ui = style_tile_image(&doc, "Normal", 1.0, true, true);
|
||||
|
||||
assert!(light.pixels.iter().all(|p| p.a() == 255), "light-mode style tile keeps opaque paper");
|
||||
assert!(dark.pixels.iter().all(|p| p.a() == 255), "dark-mode style tile keeps opaque paper (not a translucent veil)");
|
||||
assert!(dark_page_dark_ui.pixels.iter().all(|p| p.a() == 255), "dark-page style tile stays opaque");
|
||||
|
||||
let lightest = |img: &ColorImage| img.pixels.iter().copied().max_by(|a, b| rel_luma(*a).total_cmp(&rel_luma(*b))).expect("non-empty tile");
|
||||
let darkest = |img: &ColorImage| img.pixels.iter().copied().min_by(|a, b| rel_luma(*a).total_cmp(&rel_luma(*b))).expect("non-empty tile");
|
||||
|
||||
let light_paper = paper_color(&light);
|
||||
let light_ink = darkest(&light);
|
||||
let dark_paper = paper_color(&dark);
|
||||
let dark_ink = darkest(&dark);
|
||||
let dark_page_paper = paper_color(&dark_page_dark_ui);
|
||||
let dark_page_ink = lightest(&dark_page_dark_ui);
|
||||
|
||||
assert!(rel_luma(light_paper) > rel_luma(dark_paper), "dark mode dims white paper below light mode");
|
||||
assert!(rel_luma(dark_paper) > rel_luma(dark_ink), "dark-mode tile ink stays darker than its dimmed paper");
|
||||
assert!(
|
||||
contrast_ratio(light_paper, light_ink) >= 4.5,
|
||||
"light-mode Normal tile needs >= 4.5:1 contrast (got {:.2}:1)",
|
||||
contrast_ratio(light_paper, light_ink)
|
||||
);
|
||||
assert!(
|
||||
contrast_ratio(dark_paper, dark_ink) >= 4.5,
|
||||
"dark-mode Normal tile needs >= 4.5:1 contrast (got {:.2}:1)",
|
||||
contrast_ratio(dark_paper, dark_ink)
|
||||
);
|
||||
assert_eq!(dark_page_light_ui.pixels, dark_page_dark_ui.pixels, "Switch Modes' dark page is not dimmed again by dark mode");
|
||||
assert!(rel_luma(dark_page_paper) < rel_luma(dark_paper), "Switch Modes renders onto a dark page rather than dimmed white paper");
|
||||
assert!(rel_luma(dark_page_ink) > rel_luma(dark_page_paper), "Switch Modes renders light ink onto the dark page");
|
||||
assert!(
|
||||
contrast_ratio(dark_page_paper, dark_page_ink) >= 4.5,
|
||||
"dark-page Normal tile needs >= 4.5:1 contrast (got {:.2}:1)",
|
||||
contrast_ratio(dark_page_paper, dark_page_ink)
|
||||
);
|
||||
}
|
||||
|
||||
/// #2: a style whose hanging indent is larger than its left indent previewed with its first line
|
||||
/// starting off the tile's left edge; the first line now starts at the edge.
|
||||
// PLAN: the sheet puts this test in previews/tests.rs; `ribbon::galleries` is private to `ribbon`, so
|
||||
|
||||
+219
-230
@@ -8,13 +8,13 @@ use craft::ui::contract::{
|
||||
};
|
||||
use craft::ui::display::Divider;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
use craft::ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::primitives::{HAlign, TextRun};
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
use wordcraft_doc::props::Align;
|
||||
|
||||
use super::common::{icon_only, menu_button};
|
||||
use super::common::menu_button;
|
||||
use super::underline::underline_menu;
|
||||
use egui::vec2;
|
||||
use serde_json::Value;
|
||||
@@ -85,7 +85,7 @@ fn bullets_menu(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
.select(SelectMode::None)
|
||||
.activate(ActivateOn::Click)
|
||||
.card_columns(BULLETS.len())
|
||||
.thumb_size(ThumbSize::Small)
|
||||
.content_cells()
|
||||
// One row, all shown; the menu's body is the one scroll.
|
||||
.natural_height(true)
|
||||
.show_items(ui, &source, &mut |c, _| {
|
||||
@@ -174,96 +174,89 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
});
|
||||
});
|
||||
row.group(ribbon_group("font", "Font", "font", Some("format.fontDialog")), |ui| {
|
||||
// The Font and Paragraph groups' small buttons sit side by side with no gap, as the old ribbon's (1 pt apart),
|
||||
// and show their icons alone so they never expand with text labels (#7308).
|
||||
icon_only(ui, |ui| {
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
let mut family = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let out = crate::widgets::font_box(ui, app, tl!("Font").to_string(), &mut family);
|
||||
if let Some(f) = out.picked {
|
||||
let _ = app.run("format.font", json!({"name": f}));
|
||||
}
|
||||
let fmt = |s: f64| if s.fract() == 0.0 { format!("{s:.0}") } else { format!("{s}") };
|
||||
let mut size = st.get("size").and_then(Value::as_f64).map(fmt).unwrap_or_default();
|
||||
let sizes: Vec<Entry<String>> =
|
||||
wordcraft_engine::cmd::format::SIZES.iter().map(|s| Entry::new(fmt(f64::from(*s)), fmt(f64::from(*s)))).collect();
|
||||
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), &sizes).show(ui);
|
||||
if let Some(v) = out.edit.events.committed()
|
||||
&& let Ok(x) = v.trim().parse::<f64>()
|
||||
{
|
||||
let _ = app.run("format.size", json!({"size": x}));
|
||||
}
|
||||
for (icon, tip, id) in [("grow", "Increase Font Size", "format.growFont"), ("shrink", "Decrease Font Size", "format.shrinkFont")]
|
||||
{
|
||||
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
|
||||
.label(tl!(tip).to_string())
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
let face = Button::new(tl!("Change Case").to_string()).icon(IconId::new("case")).tooltip(tl!("Change Case").to_string());
|
||||
menu_button(ui, face, tl!("Change Case").to_string(), Some("format.changeCase"), |ui, _| {
|
||||
for (label, mode) in [
|
||||
("Sentence case.", "sentence"),
|
||||
("lowercase", "lower"),
|
||||
("UPPERCASE", "upper"),
|
||||
("Capitalize Each Word", "title"),
|
||||
("tOGGLE cASE", "toggle"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::with_params("format.changeCase", json!({"mode": mode})))
|
||||
.label(tl!(label).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
});
|
||||
for (icon, tip, id) in [("clear", "Clear All Formatting", "format.clear"), ("phonetic", "Phonetic Guide", "format.phonetic")] {
|
||||
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
|
||||
.label(tl!(tip).to_string())
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
});
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
for (icon, tip, id, on) in [("bold", "Bold", "format.bold", flag("bold")), ("italic", "Italic", "format.italic", flag("italic"))]
|
||||
{
|
||||
ToggleButton::command(CommandRef::new(id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon_only()
|
||||
.selected(on)
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
SplitButton::<String>::command(
|
||||
CommandRef::with_params("format.underline", json!({})),
|
||||
SplitMenu::Body(Box::new(|ui, _| underline_menu(ui, app))),
|
||||
)
|
||||
.icon(IconId::new("underline"))
|
||||
.selected(flag("underline"))
|
||||
.tooltip(tl!("Underline").to_string())
|
||||
.show(ui);
|
||||
for (icon, tip, id, on) in [
|
||||
("strike", "Strikethrough", "format.strikethrough", flag("strike")),
|
||||
("subscript", "Subscript", "format.subscript", flag("subscript")),
|
||||
("superscript", "Superscript", "format.superscript", flag("superscript")),
|
||||
("charborder", "Character Border", "format.border", flag("border")),
|
||||
] {
|
||||
ToggleButton::command(CommandRef::new(id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon_only()
|
||||
.selected(on)
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
IconButton::command(IconId::new("enclose"), CommandRef::new("format.enclose"))
|
||||
.label(tl!("Enclose Characters").to_string())
|
||||
.tooltip(tl!("Enclose Characters").to_string())
|
||||
// The Font and Paragraph groups' small buttons sit side by side with no gap, as the old ribbon's (1 pt apart).
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
let mut family = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let out = crate::widgets::font_box(ui, app, tl!("Font").to_string(), &mut family);
|
||||
if let Some(f) = out.picked {
|
||||
let _ = app.run("format.font", json!({"name": f}));
|
||||
}
|
||||
let fmt = |s: f64| if s.fract() == 0.0 { format!("{s:.0}") } else { format!("{s}") };
|
||||
let mut size = st.get("size").and_then(Value::as_f64).map(fmt).unwrap_or_default();
|
||||
let sizes: Vec<Entry<String>> =
|
||||
wordcraft_engine::cmd::format::SIZES.iter().map(|s| Entry::new(fmt(f64::from(*s)), fmt(f64::from(*s)))).collect();
|
||||
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), &sizes).show(ui);
|
||||
if let Some(v) = out.edit.events.committed()
|
||||
&& let Ok(x) = v.trim().parse::<f64>()
|
||||
{
|
||||
let _ = app.run("format.size", json!({"size": x}));
|
||||
}
|
||||
for (icon, tip, id) in [("grow", "Increase Font Size", "format.growFont"), ("shrink", "Decrease Font Size", "format.shrinkFont")] {
|
||||
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
|
||||
.label(tl!(tip).to_string())
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
let face = Button::new(tl!("Text Effects and Typography").to_string())
|
||||
.icon(IconId::new("effects"))
|
||||
.tooltip(tl!("Text Effects and Typography").to_string());
|
||||
menu_button(ui, face, tl!("Text Effects and Typography").to_string(), None, |ui, cx| text_effects_menu(ui, cx, app));
|
||||
crate::colors::highlight_split(ui, app, tl!("Text Highlight Color"));
|
||||
crate::colors::font_color_split(ui, app, tl!("Font Color"), Target::cmd("format.color").remember(Remember::FontColor));
|
||||
}
|
||||
let face = Button::new(tl!("Change Case").to_string()).icon(IconId::new("case")).tooltip(tl!("Change Case").to_string());
|
||||
menu_button(ui, face, tl!("Change Case").to_string(), Some("format.changeCase"), |ui, _| {
|
||||
for (label, mode) in [
|
||||
("Sentence case.", "sentence"),
|
||||
("lowercase", "lower"),
|
||||
("UPPERCASE", "upper"),
|
||||
("Capitalize Each Word", "title"),
|
||||
("tOGGLE cASE", "toggle"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::with_params("format.changeCase", json!({"mode": mode}))).label(tl!(label).to_string()).show(ui);
|
||||
}
|
||||
});
|
||||
for (icon, tip, id) in [("clear", "Clear All Formatting", "format.clear"), ("phonetic", "Phonetic Guide", "format.phonetic")] {
|
||||
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
|
||||
.label(tl!(tip).to_string())
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
});
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
for (icon, tip, id, on) in [("bold", "Bold", "format.bold", flag("bold")), ("italic", "Italic", "format.italic", flag("italic"))] {
|
||||
ToggleButton::command(CommandRef::new(id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon_only()
|
||||
.selected(on)
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
SplitButton::<String>::command(
|
||||
CommandRef::with_params("format.underline", json!({})),
|
||||
SplitMenu::Body(Box::new(|ui, _| underline_menu(ui, app))),
|
||||
)
|
||||
.icon(IconId::new("underline"))
|
||||
.selected(flag("underline"))
|
||||
.tooltip(tl!("Underline").to_string())
|
||||
.show(ui);
|
||||
for (icon, tip, id, on) in [
|
||||
("strike", "Strikethrough", "format.strikethrough", flag("strike")),
|
||||
("subscript", "Subscript", "format.subscript", flag("subscript")),
|
||||
("superscript", "Superscript", "format.superscript", flag("superscript")),
|
||||
("charborder", "Character Border", "format.border", flag("border")),
|
||||
] {
|
||||
ToggleButton::command(CommandRef::new(id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon_only()
|
||||
.selected(on)
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
IconButton::command(IconId::new("enclose"), CommandRef::new("format.enclose"))
|
||||
.label(tl!("Enclose Characters").to_string())
|
||||
.tooltip(tl!("Enclose Characters").to_string())
|
||||
.show(ui);
|
||||
let face = Button::new(tl!("Text Effects and Typography").to_string())
|
||||
.icon(IconId::new("effects"))
|
||||
.tooltip(tl!("Text Effects and Typography").to_string());
|
||||
menu_button(ui, face, tl!("Text Effects and Typography").to_string(), None, |ui, cx| text_effects_menu(ui, cx, app));
|
||||
crate::colors::highlight_split(ui, app, tl!("Text Highlight Color"));
|
||||
crate::colors::font_color_split(ui, app, tl!("Font Color"), Target::cmd("format.color").remember(Remember::FontColor));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -273,150 +266,146 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
// Alignment is shown as it reads on the page, so Left and Right swap in a right-to-left paragraph.
|
||||
let (align, rtl) = rp.as_ref().map_or((Align::Left, false), |r| (r.align.visual(r.bidi), r.bidi));
|
||||
let marks = app.session.view.marks;
|
||||
icon_only(ui, |ui| {
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
SplitButton::<String>::command(
|
||||
CommandRef::with_params("para.bullets", json!({})),
|
||||
SplitMenu::Body(Box::new(|ui, cx| bullets_menu(ui, cx, app))),
|
||||
)
|
||||
.icon(IconId::new("bullets"))
|
||||
.selected(lists.bullets)
|
||||
.tooltip(tl!("Bullets").to_string())
|
||||
.show(ui);
|
||||
SplitButton::<String>::command(
|
||||
CommandRef::with_params("para.numbering", json!({})),
|
||||
SplitMenu::Body(Box::new(|ui, _| {
|
||||
for (l, k) in [
|
||||
("1. 2. 3.", "numbered"),
|
||||
("1) 2) 3)", "numberedParen"),
|
||||
("I. II. III.", "outline"),
|
||||
("A. B. C.", "upperLetter"),
|
||||
("a) b) c)", "lowerLetter"),
|
||||
("i. ii. iii.", "lowerRoman"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::with_params("para.numbering", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
MenuItem::command(CommandRef::new("para.restartNumbering")).label(tl!("Restart at 1").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::with_params("para.numbering", json!({"off": true})))
|
||||
.label(tl!("None").to_string())
|
||||
.show(ui);
|
||||
})),
|
||||
)
|
||||
.icon(IconId::new("numbering"))
|
||||
.selected(lists.numbering)
|
||||
.tooltip(tl!("Numbering").to_string())
|
||||
.show(ui);
|
||||
SplitButton::<String>::command(
|
||||
CommandRef::with_params("para.multilevel", json!({})),
|
||||
SplitMenu::Body(Box::new(|ui, _| {
|
||||
for (l, k) in [("1. 1.1. 1.1.1.", "legal"), ("I. A. 1. a.", "outline")] {
|
||||
MenuItem::command(CommandRef::with_params("para.multilevel", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
// Lists linked to the heading styles: the headings carry the numbers. Each item
|
||||
// reads as its first three levels, number then (translated) style name.
|
||||
for (numbers, k) in [
|
||||
(["1", "1.1", "1.1.1"], "headings"),
|
||||
(["Article I.", "Section 1.01", "(a)"], "article"),
|
||||
(["I.", "A.", "1."], "outlineHeadings"),
|
||||
(["Chapter 1", "", ""], "chapter"),
|
||||
] {
|
||||
let text = numbers
|
||||
.iter()
|
||||
.zip(["Heading 1", "Heading 2", "Heading 3"])
|
||||
.map(|(n, h)| if n.is_empty() { tl!(h).to_string() } else { format!("{} {}", tl!(n), tl!(h)) })
|
||||
.collect::<Vec<_>>()
|
||||
.join(" / ");
|
||||
MenuItem::command(CommandRef::with_params("list.multilevelPreset", json!({"preset": k}))).label(text).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
MenuItem::command(CommandRef::new("list.define")).label(tl!("Define New Multilevel List…").to_string()).show(ui);
|
||||
Divider::horizontal().show(ui);
|
||||
for lv in 0..5u64 {
|
||||
MenuItem::command(CommandRef::with_params("para.listLevel", json!({"level": lv})))
|
||||
.label(format!("Change to Level {}", lv + 1))
|
||||
.show(ui);
|
||||
}
|
||||
})),
|
||||
)
|
||||
.icon(IconId::new("multilevel"))
|
||||
.selected(lists.multilevel)
|
||||
.tooltip(tl!("Multilevel List").to_string())
|
||||
.show(ui);
|
||||
for (icon, tip, id) in
|
||||
[("outdent", "Decrease Indent", "para.outdent"), ("indent", "Increase Indent", "para.indent"), ("sort", "Sort", "para.sort")]
|
||||
{
|
||||
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
|
||||
.label(tl!(tip).to_string())
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
ToggleButton::command(CommandRef::new("view.marks"))
|
||||
.icon(IconId::new("wordcraft.pilcrow"))
|
||||
.icon_only()
|
||||
.selected(marks)
|
||||
.tooltip(tl!("Show/Hide ¶").to_string())
|
||||
.show(ui);
|
||||
});
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
for (icon, tip, id, on) in [
|
||||
("alignLeft", "Align Left", "para.alignLeft", align == Align::Left),
|
||||
("alignCenter", "Center", "para.alignCenter", align == Align::Center),
|
||||
("alignRight", "Align Right", "para.alignRight", align == Align::Right),
|
||||
("justify", "Justify", "para.justify", align == Align::Justify),
|
||||
("textLtr", "Left-to-Right Text Direction", "para.ltr", !rtl),
|
||||
("textRtl", "Right-to-Left Text Direction", "para.rtl", rtl),
|
||||
] {
|
||||
ToggleButton::command(CommandRef::new(id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon_only()
|
||||
.selected(on)
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
let face = Button::new(tl!("Line and Paragraph Spacing").to_string())
|
||||
.icon(IconId::new("lineSpacing"))
|
||||
.tooltip(tl!("Line and Paragraph Spacing").to_string());
|
||||
menu_button(ui, face, tl!("Line and Paragraph Spacing").to_string(), Some("para.lineSpacing"), |ui, _| {
|
||||
for v in [1.0, 1.15, 1.5, 2.0, 2.5, 3.0] {
|
||||
MenuItem::command(CommandRef::with_params("para.lineSpacing", json!({"value": v}))).label(format!("{v}")).show(ui);
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
SplitButton::<String>::command(
|
||||
CommandRef::with_params("para.bullets", json!({})),
|
||||
SplitMenu::Body(Box::new(|ui, cx| bullets_menu(ui, cx, app))),
|
||||
)
|
||||
.icon(IconId::new("bullets"))
|
||||
.selected(lists.bullets)
|
||||
.tooltip(tl!("Bullets").to_string())
|
||||
.show(ui);
|
||||
SplitButton::<String>::command(
|
||||
CommandRef::with_params("para.numbering", json!({})),
|
||||
SplitMenu::Body(Box::new(|ui, _| {
|
||||
for (l, k) in [
|
||||
("1. 2. 3.", "numbered"),
|
||||
("1) 2) 3)", "numberedParen"),
|
||||
("I. II. III.", "outline"),
|
||||
("A. B. C.", "upperLetter"),
|
||||
("a) b) c)", "lowerLetter"),
|
||||
("i. ii. iii.", "lowerRoman"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::with_params("para.numbering", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
for (label, id) in [
|
||||
("Add Space Before Paragraph", "para.addSpaceBefore"),
|
||||
("Remove Space After Paragraph", "para.removeSpaceAfter"),
|
||||
("Line Spacing Options…", "para.dialog"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::new(id)).label(tl!(label).to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::new("para.restartNumbering")).label(tl!("Restart at 1").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::with_params("para.numbering", json!({"off": true}))).label(tl!("None").to_string()).show(ui);
|
||||
})),
|
||||
)
|
||||
.icon(IconId::new("numbering"))
|
||||
.selected(lists.numbering)
|
||||
.tooltip(tl!("Numbering").to_string())
|
||||
.show(ui);
|
||||
SplitButton::<String>::command(
|
||||
CommandRef::with_params("para.multilevel", json!({})),
|
||||
SplitMenu::Body(Box::new(|ui, _| {
|
||||
for (l, k) in [("1. 1.1. 1.1.1.", "legal"), ("I. A. 1. a.", "outline")] {
|
||||
MenuItem::command(CommandRef::with_params("para.multilevel", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
|
||||
}
|
||||
});
|
||||
crate::colors::shading_split(ui, app, tl!("Shading"), Target::cmd("para.shading").remember(Remember::Shading));
|
||||
SplitButton::<String>::command(
|
||||
CommandRef::with_params("para.borders", json!({"kind": "bottom"})),
|
||||
SplitMenu::Body(Box::new(|ui, _| {
|
||||
for (l, k) in [
|
||||
("Bottom Border", "bottom"),
|
||||
("Top Border", "top"),
|
||||
("Left Border", "left"),
|
||||
("Right Border", "right"),
|
||||
("No Border", "none"),
|
||||
("All Borders", "all"),
|
||||
("Outside Borders", "outside"),
|
||||
("Inside Borders", "inside"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::with_params("para.borders", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
MenuItem::command(CommandRef::new("insert.horizontalLine")).label(tl!("Horizontal Line").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::new("para.borders")).label(tl!("Borders and Shading…").to_string()).show(ui);
|
||||
})),
|
||||
)
|
||||
.icon(IconId::new("borders"))
|
||||
.tooltip(tl!("Borders").to_string())
|
||||
Divider::horizontal().show(ui);
|
||||
// Lists linked to the heading styles: the headings carry the numbers. Each item
|
||||
// reads as its first three levels, number then (translated) style name.
|
||||
for (numbers, k) in [
|
||||
(["1", "1.1", "1.1.1"], "headings"),
|
||||
(["Article I.", "Section 1.01", "(a)"], "article"),
|
||||
(["I.", "A.", "1."], "outlineHeadings"),
|
||||
(["Chapter 1", "", ""], "chapter"),
|
||||
] {
|
||||
let text = numbers
|
||||
.iter()
|
||||
.zip(["Heading 1", "Heading 2", "Heading 3"])
|
||||
.map(|(n, h)| if n.is_empty() { tl!(h).to_string() } else { format!("{} {}", tl!(n), tl!(h)) })
|
||||
.collect::<Vec<_>>()
|
||||
.join(" / ");
|
||||
MenuItem::command(CommandRef::with_params("list.multilevelPreset", json!({"preset": k}))).label(text).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
MenuItem::command(CommandRef::new("list.define")).label(tl!("Define New Multilevel List…").to_string()).show(ui);
|
||||
Divider::horizontal().show(ui);
|
||||
for lv in 0..5u64 {
|
||||
MenuItem::command(CommandRef::with_params("para.listLevel", json!({"level": lv})))
|
||||
.label(format!("Change to Level {}", lv + 1))
|
||||
.show(ui);
|
||||
}
|
||||
})),
|
||||
)
|
||||
.icon(IconId::new("multilevel"))
|
||||
.selected(lists.multilevel)
|
||||
.tooltip(tl!("Multilevel List").to_string())
|
||||
.show(ui);
|
||||
for (icon, tip, id) in
|
||||
[("outdent", "Decrease Indent", "para.outdent"), ("indent", "Increase Indent", "para.indent"), ("sort", "Sort", "para.sort")]
|
||||
{
|
||||
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
|
||||
.label(tl!(tip).to_string())
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
ToggleButton::command(CommandRef::new("view.marks"))
|
||||
.icon(IconId::new("wordcraft.pilcrow"))
|
||||
.icon_only()
|
||||
.selected(marks)
|
||||
.tooltip(tl!("Show/Hide ¶").to_string())
|
||||
.show(ui);
|
||||
});
|
||||
Row::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
for (icon, tip, id, on) in [
|
||||
("alignLeft", "Align Left", "para.alignLeft", align == Align::Left),
|
||||
("alignCenter", "Center", "para.alignCenter", align == Align::Center),
|
||||
("alignRight", "Align Right", "para.alignRight", align == Align::Right),
|
||||
("justify", "Justify", "para.justify", align == Align::Justify),
|
||||
("textLtr", "Left-to-Right Text Direction", "para.ltr", !rtl),
|
||||
("textRtl", "Right-to-Left Text Direction", "para.rtl", rtl),
|
||||
] {
|
||||
ToggleButton::command(CommandRef::new(id))
|
||||
.icon(crate::icons::id(icon))
|
||||
.icon_only()
|
||||
.selected(on)
|
||||
.tooltip(tl!(tip).to_string())
|
||||
.show(ui);
|
||||
}
|
||||
let face = Button::new(tl!("Line and Paragraph Spacing").to_string())
|
||||
.icon(IconId::new("lineSpacing"))
|
||||
.tooltip(tl!("Line and Paragraph Spacing").to_string());
|
||||
menu_button(ui, face, tl!("Line and Paragraph Spacing").to_string(), Some("para.lineSpacing"), |ui, _| {
|
||||
for v in [1.0, 1.15, 1.5, 2.0, 2.5, 3.0] {
|
||||
MenuItem::command(CommandRef::with_params("para.lineSpacing", json!({"value": v}))).label(format!("{v}")).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
for (label, id) in [
|
||||
("Add Space Before Paragraph", "para.addSpaceBefore"),
|
||||
("Remove Space After Paragraph", "para.removeSpaceAfter"),
|
||||
("Line Spacing Options…", "para.dialog"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::new(id)).label(tl!(label).to_string()).show(ui);
|
||||
}
|
||||
});
|
||||
crate::colors::shading_split(ui, app, tl!("Shading"), Target::cmd("para.shading").remember(Remember::Shading));
|
||||
SplitButton::<String>::command(
|
||||
CommandRef::with_params("para.borders", json!({"kind": "bottom"})),
|
||||
SplitMenu::Body(Box::new(|ui, _| {
|
||||
for (l, k) in [
|
||||
("Bottom Border", "bottom"),
|
||||
("Top Border", "top"),
|
||||
("Left Border", "left"),
|
||||
("Right Border", "right"),
|
||||
("No Border", "none"),
|
||||
("All Borders", "all"),
|
||||
("Outside Borders", "outside"),
|
||||
("Inside Borders", "inside"),
|
||||
] {
|
||||
MenuItem::command(CommandRef::with_params("para.borders", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
MenuItem::command(CommandRef::new("insert.horizontalLine")).label(tl!("Horizontal Line").to_string()).show(ui);
|
||||
MenuItem::command(CommandRef::new("para.borders")).label(tl!("Borders and Shading…").to_string()).show(ui);
|
||||
})),
|
||||
)
|
||||
.icon(IconId::new("borders"))
|
||||
.tooltip(tl!("Borders").to_string())
|
||||
.show(ui);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -57,31 +57,25 @@ pub(super) fn table_design(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
row.group(RibbonGroup::new("tableStyles", tl!("Table Styles").to_string(), IconId::new("tableStyles").into()), |ui| {
|
||||
super::galleries::table_styles(ui, app);
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
let _ = menu_button(
|
||||
ui,
|
||||
Button::new(tl!("Styles").to_string()).icon(IconId::new("styles")),
|
||||
tl!("Styles").to_string(),
|
||||
Some("table.style"),
|
||||
|ui, _| {
|
||||
MenuItem::command(CommandRef::with_params("ui.dialog", json!({"name": "newTableStyle"})))
|
||||
.label(tl!("New Table Style…").to_string())
|
||||
.show(ui);
|
||||
MenuItem::command(CommandRef::with_params("ui.dialog", json!({"name": "modifyTableStyle"})))
|
||||
.label(tl!("Modify Table Style…").to_string())
|
||||
.enabled(can_modify)
|
||||
.show(ui);
|
||||
MenuItem::command(CommandRef::with_params("table.deleteStyle", json!({})))
|
||||
.label(tl!("Delete Table Style").to_string())
|
||||
.enabled(can_delete)
|
||||
.show(ui);
|
||||
},
|
||||
);
|
||||
let _ = menu_button(ui, Button::new(tl!("Styles").to_string()).icon(IconId::new("styles")), tl!("Styles").to_string(), None, |ui, _| {
|
||||
MenuItem::command(CommandRef::with_params("ui.dialog", json!({"name": "newTableStyle"})))
|
||||
.label(tl!("New Table Style…").to_string())
|
||||
.show(ui);
|
||||
MenuItem::command(CommandRef::with_params("ui.dialog", json!({"name": "modifyTableStyle"})))
|
||||
.label(tl!("Modify Table Style…").to_string())
|
||||
.enabled(can_modify)
|
||||
.show(ui);
|
||||
MenuItem::command(CommandRef::with_params("table.deleteStyle", json!({})))
|
||||
.label(tl!("Delete Table Style").to_string())
|
||||
.enabled(can_delete)
|
||||
.show(ui);
|
||||
});
|
||||
let _ = crate::colors::shading_split(ui, app, tl!("Shading").to_string(), Target::cmd("table.shading").remember(Remember::Shading));
|
||||
});
|
||||
});
|
||||
row.group(RibbonGroup::new("borders", tl!("Borders").to_string(), IconId::new("borders").into()), |ui| {
|
||||
let face = Button::new(tl!("Borders").to_string()).icon(IconId::new("borders")).arrangement(Arrangement::Stacked);
|
||||
let _ = menu_button(ui, face, tl!("Borders").to_string(), Some("table.borders"), |ui, _| {
|
||||
let _ = menu_button(ui, face, tl!("Borders").to_string(), None, |ui, _| {
|
||||
for (label, kind) in [
|
||||
("All Borders", "all"),
|
||||
("Outside Borders", "outside"),
|
||||
@@ -152,12 +146,8 @@ fn cell_size_boxes(ui: &mut Ui, app: &mut WordApp) {
|
||||
pub(super) fn table_layout(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
row.group(RibbonGroup::new("table", tl!("Table").to_string(), IconId::new("table").into()), |ui| {
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
let _ = menu_button(
|
||||
ui,
|
||||
Button::new(tl!("Select").to_string()).icon(IconId::new("selectTable")),
|
||||
tl!("Select").to_string(),
|
||||
Some("table.selectTable"),
|
||||
|ui, _| {
|
||||
let _ =
|
||||
menu_button(ui, Button::new(tl!("Select").to_string()).icon(IconId::new("selectTable")), tl!("Select").to_string(), None, |ui, _| {
|
||||
for (label, id) in [
|
||||
("Select Cell", "table.selectCell"),
|
||||
("Select Column", "table.selectColumn"),
|
||||
@@ -166,8 +156,7 @@ pub(super) fn table_layout(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
] {
|
||||
MenuItem::command(CommandRef::new(id)).label(tl!(label).to_string()).show(ui);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
ToggleButton::command(CommandRef::new("table.viewGridlines"))
|
||||
.label(tl!("View Gridlines").to_string())
|
||||
.icon(IconId::new("gridlines"))
|
||||
@@ -192,7 +181,7 @@ pub(super) fn table_layout(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
});
|
||||
row.group(RibbonGroup::new("rowsColumns", tl!("Rows & Columns").to_string(), IconId::new("insertAbove").into()), |ui| {
|
||||
let face = Button::new(tl!("Delete").to_string()).icon(IconId::new("deleteTable")).arrangement(Arrangement::Stacked);
|
||||
let _ = menu_button(ui, face, tl!("Delete").to_string(), Some("table.deleteTable"), |ui, _| {
|
||||
let _ = menu_button(ui, face, tl!("Delete").to_string(), None, |ui, _| {
|
||||
for (label, id) in [
|
||||
("Delete Cells", "table.deleteCells"),
|
||||
("Delete Columns", "table.deleteColumn"),
|
||||
@@ -225,7 +214,7 @@ pub(super) fn table_layout(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
});
|
||||
row.group(RibbonGroup::new("cellSize", tl!("Cell Size").to_string(), IconId::new("autofit").into()), |ui| {
|
||||
let face = Button::new(tl!("AutoFit").to_string()).icon(IconId::new("autofit")).arrangement(Arrangement::Stacked);
|
||||
let _ = menu_button(ui, face, tl!("AutoFit").to_string(), Some("table.autofit"), |ui, _| {
|
||||
let _ = menu_button(ui, face, tl!("AutoFit").to_string(), None, |ui, _| {
|
||||
for (label, mode) in [("AutoFit Contents", "contents"), ("AutoFit Window", "window"), ("Fixed Column Width", "fixed")] {
|
||||
MenuItem::command(CommandRef::with_params("table.autofit", json!({"mode": mode}))).label(tl!(label).to_string()).show(ui);
|
||||
}
|
||||
|
||||
@@ -728,269 +728,3 @@ fn table_shading_split_keeps_palette_and_apply_separate() {
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(first_cell_shading(h.state()), Some(red), "No Color is undone in one step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_styles_gallery_uses_large_landscape_thumbnails() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::{By, Queryable};
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let mut h = tab_harness(app, "Design");
|
||||
let style_set_height = h
|
||||
.query_all(By::new().role(Role::RadioButton).label_contains("Style set:"))
|
||||
.next()
|
||||
.expect("Design › Style Sets renders its large gallery tiles")
|
||||
.rect()
|
||||
.height();
|
||||
|
||||
h.state_mut().run("ui.tab", json!({"tab": "Table Design"})).unwrap();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
|
||||
let mut styles: Vec<(bool, String)> = h
|
||||
.state()
|
||||
.session
|
||||
.doc
|
||||
.styles
|
||||
.styles
|
||||
.iter()
|
||||
.filter(|s| s.kind == wordcraft_doc::StyleKind::Table && !s.hidden)
|
||||
.map(|s| (s.builtin, crate::i18n::style_name(s)))
|
||||
.collect();
|
||||
styles.sort_by_key(|(builtin, _)| *builtin);
|
||||
let expected: Vec<String> = styles.into_iter().take(7).map(|(_, name)| name).collect();
|
||||
assert_eq!(expected.len(), 7, "built-in document has at least seven table styles");
|
||||
|
||||
let tiles: Vec<(String, egui::Rect)> = expected
|
||||
.iter()
|
||||
.filter_map(|name| h.query_all(By::new().role(Role::RadioButton).label(name)).next().map(|node| (name.clone(), node.rect())))
|
||||
.collect();
|
||||
assert_eq!(tiles.len(), expected.len(), "all seven Table Styles tiles render at full ribbon width: {tiles:?}");
|
||||
|
||||
for (name, rect) in &tiles {
|
||||
assert!(
|
||||
rect.height() >= style_set_height - 1.0,
|
||||
"Table Styles tile `{name}` height should be at least Design › Style Sets' Large thumbnail height ({style_set_height}), got {rect:?}"
|
||||
);
|
||||
let ratio = rect.width() / rect.height();
|
||||
assert!(
|
||||
(1.25..=1.75).contains(&ratio),
|
||||
"Table Styles tile `{name}` should use a landscape aspect ratio matching its 3:2 table preview, got {ratio:.2} ({rect:?})"
|
||||
);
|
||||
}
|
||||
assert!(tiles.windows(2).all(|w| w[0].1.max.x <= w[1].1.min.x + 0.01), "Table Styles tiles sit side by side without overlapping: {tiles:?}");
|
||||
}
|
||||
|
||||
/// #7308: the compact menu and split buttons of Home › Font and Home › Paragraph show their icons
|
||||
/// alone (keeping their names for access and tooltips) even in a wide window, leaving room for all
|
||||
/// six tiles of the Styles gallery at 1920 pt.
|
||||
#[test]
|
||||
fn home_font_and_paragraph_buttons_stay_icon_only_and_styles_shows_six_tiles() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let button_width = |h: &Harness, name: &str| {
|
||||
h.query_all(By::new().role(Role::Button).label(name)).next().unwrap_or_else(|| panic!("a button named {name}")).rect().width()
|
||||
};
|
||||
|
||||
// Wide enough that the ribbon keeps every group at GroupLevel::Full: without `icon_only`, both
|
||||
// Font and Paragraph render their full text labels, making longer names much wider than shorter
|
||||
// ones and wider than text-labelled buttons like Replace.
|
||||
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Text")), crate::Services::default());
|
||||
let wide = tab_harness(app, "Home");
|
||||
let replace_w = button_width(&wide, "Replace");
|
||||
|
||||
let menu_buttons = ["Change Case", "Text Effects and Typography", "Line and Paragraph Spacing"];
|
||||
let menu_widths: Vec<(&str, f32)> = menu_buttons.iter().map(|&n| (n, button_width(&wide, n))).collect();
|
||||
let base_menu_w = menu_widths[0].1;
|
||||
for &(name, w) in &menu_widths {
|
||||
assert!((w - base_menu_w).abs() < 1.0, "{name} ({w:.1} pt) differs from icon-only menu width ({base_menu_w:.1} pt): {menu_widths:?}");
|
||||
assert!(w < replace_w, "{name} ({w:.1} pt) should be narrower than a labelled button like Replace ({replace_w:.1} pt)");
|
||||
}
|
||||
|
||||
let split_buttons = ["Underline", "Text Highlight Color", "Font Color", "Bullets", "Numbering", "Multilevel List", "Shading", "Borders"];
|
||||
let split_widths: Vec<(&str, f32)> = split_buttons.iter().map(|&n| (n, button_width(&wide, n))).collect();
|
||||
let base_split_w = split_widths[0].1;
|
||||
for &(name, w) in &split_widths {
|
||||
assert!((w - base_split_w).abs() < 1.0, "{name} ({w:.1} pt) differs from icon-only split width ({base_split_w:.1} pt): {split_widths:?}");
|
||||
assert!(w < replace_w, "{name} ({w:.1} pt) should be narrower than a labelled button like Replace ({replace_w:.1} pt)");
|
||||
}
|
||||
|
||||
// At 1920 pt, Font no longer starves the Styles gallery: all six default quick styles show.
|
||||
let app = WordApp::new(Session::new(wordcraft_engine::sample::sample_document()), crate::Services::default());
|
||||
let full_hd = app_harness(app, vec2(1920.0, 900.0));
|
||||
let shown = |name: &str| full_hd.query_all(By::new().label(name)).next().is_some();
|
||||
for style in ["Normal", "No Spacing", "Heading 1", "Title", "Heading 2", "Subtitle"] {
|
||||
assert!(shown(style), "Home › Styles should show {style} at 1920 pt");
|
||||
}
|
||||
}
|
||||
|
||||
/// #7323: the Home › Bullets dropdown renders the Bullet Library grid as compact
|
||||
/// square preview tiles (~22×22 pt), rather than expanding to full card dimensions (~132 pt).
|
||||
#[test]
|
||||
fn bullets_dropdown_renders_compact_bullet_tiles() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample")), crate::Services::default());
|
||||
let mut h = tab_harness(app, "Home");
|
||||
h.ctx.set_missing_glyph_policy(egui::MissingGlyphPolicy::Tofu);
|
||||
|
||||
// The SplitButton has two button nodes: the command part and the arrow part.
|
||||
let arrow = h.query_all(By::new().role(Role::Button).label("Bullets")).nth(1).expect("Bullets split-button menu arrow");
|
||||
arrow.click();
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
|
||||
let bullet_tile = h.query_all(By::new().role(Role::ListItem).label("•")).next().expect("bullet tile •");
|
||||
let rect = bullet_tile.rect();
|
||||
assert!(
|
||||
rect.width() >= 16.0 && rect.width() <= 32.0,
|
||||
"bullet tile width ({:.1} pt) should be compact (expected ~22 pt, bound [16, 32])",
|
||||
rect.width()
|
||||
);
|
||||
assert!(
|
||||
rect.height() >= 16.0 && rect.height() <= 32.0,
|
||||
"bullet tile height ({:.1} pt) should be compact (expected ~22 pt, bound [16, 32])",
|
||||
rect.height()
|
||||
);
|
||||
assert!((rect.width() - rect.height()).abs() <= 2.0, "bullet tile should be square: {}x{}", rect.width(), rect.height());
|
||||
}
|
||||
|
||||
/// #7310: unimplemented stub ribbon buttons (Dictate, Ink to Math, Translate, Block Authors)
|
||||
/// resolve disabled in the ribbon UI and are known to the command catalog without warnings.
|
||||
#[test]
|
||||
fn unimplemented_stub_ribbon_buttons_are_disabled() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let cases = [
|
||||
("Home", "Dictate", "tools.dictate"),
|
||||
("Draw", "Ink to Math", "draw.inkToMath"),
|
||||
("Review", "Translate", "review.translate"),
|
||||
("Review", "Block Authors", "review.blockAuthors"),
|
||||
];
|
||||
|
||||
for (tab, expected_label, id) in cases {
|
||||
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Text")), crate::Services::default());
|
||||
let h = tab_harness(app, tab);
|
||||
|
||||
let keymap = craft::ui::runtime::commands::keymap(&h.ctx).expect("command board has a keymap");
|
||||
assert!(keymap.catalog().iter().any(|def| def.command.id == id), "{tab}: stub command {id} should be registered in the app catalog");
|
||||
|
||||
let button = h
|
||||
.query_all(By::new().role(Role::Button))
|
||||
.find(|n| n.accesskit_node().label().is_some_and(|l| l.split_whitespace().collect::<Vec<_>>().join(" ") == expected_label))
|
||||
.unwrap_or_else(|| panic!("{tab}: ribbon button '{expected_label}' should exist"));
|
||||
assert!(button.accesskit_node().is_disabled(), "{tab}: stub button {:?} ({id}) must be disabled", button.accesskit_node().label());
|
||||
}
|
||||
}
|
||||
|
||||
/// #7324, #7457: Table ribbon menu buttons (Styles, Borders, Select, Delete, AutoFit) bind their command IDs
|
||||
/// so they disable when editing is protected or when no table is active.
|
||||
#[test]
|
||||
fn table_ribbon_menu_buttons_disable_when_unselected_or_protected() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let is_disabled = |h: &Harness, name: &str| {
|
||||
h.query_all(By::new().role(Role::Button).label(name))
|
||||
.next()
|
||||
.unwrap_or_else(|| panic!("button {name} not found"))
|
||||
.accesskit_node()
|
||||
.is_disabled()
|
||||
};
|
||||
|
||||
let description = |h: &Harness, name: &str| {
|
||||
h.query_all(By::new().role(Role::Button).label(name))
|
||||
.next()
|
||||
.unwrap_or_else(|| panic!("button {name} not found"))
|
||||
.accesskit_node()
|
||||
.description()
|
||||
.map(|s| s.to_string())
|
||||
};
|
||||
|
||||
// Configure Table Design & Table Layout as explicit ribbon tabs so they can be
|
||||
// displayed even when the cursor is outside a table.
|
||||
let make_table_tabs_app = |mut app: WordApp| {
|
||||
app.session.ribbon.tabs = vec![
|
||||
wordcraft_engine::ribbon::TabEntry { name: "Table Design".to_string(), custom: false, hidden: false, groups: Vec::new() },
|
||||
wordcraft_engine::ribbon::TabEntry { name: "Table Layout".to_string(), custom: false, hidden: false, groups: Vec::new() },
|
||||
];
|
||||
app
|
||||
};
|
||||
|
||||
// 1. Without a table active:
|
||||
let app_no_table = make_table_tabs_app(WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default()));
|
||||
let h_design_empty = tab_harness(app_no_table, "Table Design");
|
||||
assert!(is_disabled(&h_design_empty, "Styles"), "Styles button should be disabled when not in table");
|
||||
assert!(is_disabled(&h_design_empty, "Borders"), "Borders button should be disabled when not in table");
|
||||
|
||||
let app_no_table2 = make_table_tabs_app(WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default()));
|
||||
let h_layout_empty = tab_harness(app_no_table2, "Table Layout");
|
||||
assert!(is_disabled(&h_layout_empty, "Select"), "Select button should be disabled when not in table");
|
||||
assert!(is_disabled(&h_layout_empty, "Delete"), "Delete button should be disabled when not in table");
|
||||
assert!(is_disabled(&h_layout_empty, "AutoFit"), "AutoFit button should be disabled when not in table");
|
||||
assert!(
|
||||
description(&h_layout_empty, "Select").as_deref().unwrap_or("").to_ascii_lowercase().contains("the cursor isn't in a table"),
|
||||
"Select should indicate outside table in disabled hint"
|
||||
);
|
||||
|
||||
// 2. With an active table and no protection: buttons are enabled:
|
||||
let mut app_table = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_table.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let h_design = tab_harness(app_table, "Table Design");
|
||||
assert!(!is_disabled(&h_design, "Styles"), "Styles button should be enabled in table");
|
||||
assert!(!is_disabled(&h_design, "Borders"), "Borders button should be enabled in table");
|
||||
|
||||
let mut app_table2 = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_table2.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
let h_layout = tab_harness(app_table2, "Table Layout");
|
||||
assert!(!is_disabled(&h_layout, "Select"), "Select button should be enabled in table");
|
||||
assert!(!is_disabled(&h_layout, "Delete"), "Delete button should be enabled in table");
|
||||
assert!(!is_disabled(&h_layout, "AutoFit"), "AutoFit button should be enabled in table");
|
||||
|
||||
// 3. With an active table under document protection (read-only): mutating buttons are disabled:
|
||||
let mut app_protected_design = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_protected_design.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
app_protected_design.session.doc.settings.protection = Some("readOnly".into());
|
||||
let h_prot_design = tab_harness(app_protected_design, "Table Design");
|
||||
assert!(is_disabled(&h_prot_design, "Styles"), "Styles button should be disabled under protection");
|
||||
assert!(is_disabled(&h_prot_design, "Borders"), "Borders button should be disabled under protection");
|
||||
assert!(
|
||||
description(&h_prot_design, "Styles").as_deref().unwrap_or("").contains("protected"),
|
||||
"Styles should indicate protection in disabled hint"
|
||||
);
|
||||
|
||||
let mut app_protected_layout = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
|
||||
app_protected_layout.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
|
||||
app_protected_layout.session.doc.settings.protection = Some("readOnly".into());
|
||||
let h_prot_layout = tab_harness(app_protected_layout, "Table Layout");
|
||||
assert!(!is_disabled(&h_prot_layout, "Select"), "Select button should remain enabled under protection");
|
||||
assert!(is_disabled(&h_prot_layout, "Delete"), "Delete button should be disabled under protection");
|
||||
assert!(is_disabled(&h_prot_layout, "AutoFit"), "AutoFit button should be disabled under protection");
|
||||
assert!(
|
||||
description(&h_prot_layout, "Delete").as_deref().unwrap_or("").contains("protected"),
|
||||
"Delete should indicate protection in disabled hint"
|
||||
);
|
||||
}
|
||||
|
||||
/// #7374: the Decorative Text / WordArt Styles dropdown menu renders compact tiles (~40×36 pt)
|
||||
/// rather than expanding to default card thumbnail size (~132×119 pt).
|
||||
#[test]
|
||||
fn decorative_text_dropdown_renders_compact_wordart_tiles() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample")), crate::Services::default());
|
||||
let mut h = tab_harness(app, "Insert");
|
||||
click_button(&mut h, "Decorative Text");
|
||||
|
||||
let tile = h.query_all(By::new().role(Role::ListItem).label("Solid Accent")).next().expect("Solid Accent WordArt tile");
|
||||
let rect = tile.rect();
|
||||
assert!(
|
||||
rect.width() >= 32.0 && rect.width() <= 50.0,
|
||||
"WordArt tile width ({:.1} pt) should be compact (expected ~40 pt, bound [32, 50]), got {:.1}",
|
||||
rect.width(),
|
||||
rect.width()
|
||||
);
|
||||
assert!(
|
||||
rect.height() >= 28.0 && rect.height() <= 46.0,
|
||||
"WordArt tile height ({:.1} pt) should be compact (expected ~36 pt, bound [28, 46]), got {:.1}",
|
||||
rect.height(),
|
||||
rect.height()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -229,7 +229,7 @@ impl<'a> TableMouse<'a> {
|
||||
/// A press went down at `start.origin` on part `index` of `page` with `mods` held: a selection area selects, an
|
||||
/// insert button inserts, a handle waits.
|
||||
fn press(&mut self, cx: &mut Cx<'_, Self>, start: PressStart, mods: Mods, page: usize, index: u64) {
|
||||
let Some(placed) = self.pages.iter().find(|placed| placed.page == page).cloned() else { return };
|
||||
let Some(placed) = self.pages.iter().find(|placed| placed.page == page).copied() else { return };
|
||||
let (x, y) = page_point(&placed, start.origin);
|
||||
let reach = reach_on(self.pages, page);
|
||||
let story = self.app.session.sel.focus.story;
|
||||
|
||||
@@ -231,7 +231,7 @@ impl<'a> TableBorders<'a> {
|
||||
|
||||
/// A press went down at `origin` on `target`, the border of part `index` on `page`: the drag starts there.
|
||||
fn press(&mut self, cx: &mut Cx<'_, Self>, origin: Pos2, page: usize, index: u64, mut target: ResizeTarget) {
|
||||
let Some(placed) = self.pages.iter().find(|placed| placed.page == page).cloned() else { return };
|
||||
let Some(placed) = self.pages.iter().find(|placed| placed.page == page).copied() else { return };
|
||||
let from = page_point(&placed, origin);
|
||||
target.limit_to_selection(&self.app.session, from.1);
|
||||
self.app.canvas.table_resize = Some(ResizeDrag { page, from, to: from, target, ruler: false });
|
||||
|
||||
@@ -46,10 +46,8 @@ pub(crate) fn screen(h: &mut H, x: f32, y: f32) -> Pos2 {
|
||||
crate::canvas::page_to_screen(h.state_mut(), 0, x, y).unwrap()
|
||||
}
|
||||
|
||||
/// A primary button event carrying the modifiers held, as platforms send it.
|
||||
pub(crate) fn button(h: &H, at: Pos2, pressed: bool) {
|
||||
let modifiers = h.ctx.input(|i| i.modifiers);
|
||||
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers });
|
||||
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
|
||||
}
|
||||
|
||||
pub(crate) fn steps(h: &mut H, n: usize) {
|
||||
|
||||
@@ -10,10 +10,6 @@
|
||||
//! Use [`builder`] instead of `egui_kittest::Harness::builder()` (the framework lint `test/kit`
|
||||
//! flags direct use); chain `with_size`, `with_step_dt` and the rest on the result as before.
|
||||
//! [`builder_with`] takes a custom install spec, e.g. a memory clipboard or a fake system.
|
||||
//!
|
||||
//! A test of the whole app window builds with `build_eframe(|_| app)`: the harness then runs the app
|
||||
//! as the desktop driver does (the `eframe::App` impl below), handing the runtime the app's input
|
||||
//! before every pass, the build pass included.
|
||||
|
||||
use craft::ui::InstallSpec;
|
||||
use egui_kittest::HarnessBuilder;
|
||||
@@ -37,12 +33,37 @@ pub(crate) fn builder<S>() -> HarnessBuilder<S> {
|
||||
/// Like [`builder`], with the install spec `spec` makes (called when the context is set up).
|
||||
pub(crate) fn builder_with<S>(spec: impl FnOnce() -> InstallSpec + 'static) -> HarnessBuilder<S> {
|
||||
egui_kittest::Harness::builder().with_context_setup(move |ctx| {
|
||||
// Before the runtime's plugin: egui runs input hooks in registration order, and the runtime's key stage reads
|
||||
// the input this hands it.
|
||||
ctx.add_plugin(HandOver);
|
||||
// A frame may draw a file name or language name in CJK on its first pass; a CI runner has no CJK font.
|
||||
cjk_stand_in(ctx);
|
||||
craft::ui::shell::embed::install(ctx, spec(), &crate::ui_fonts(Lang::EN)).expect("the craft runtime installs on a fresh test context");
|
||||
})
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The input the app made in the last pass ([`driver_logic`]), waiting for the next pass to start.
|
||||
static PENDING: std::cell::RefCell<Option<craft::ui::runtime::frame::FrameInput>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Hands the runtime the input [`driver_logic`] left, before the next pass begins (egui's input hook runs
|
||||
/// before `begin_pass`). The runtime refuses input during a pass, and a kittest harness has no eframe
|
||||
/// `raw_input_hook` to give it at the right time.
|
||||
struct HandOver;
|
||||
|
||||
impl egui::Plugin for HandOver {
|
||||
fn debug_name(&self) -> &'static str {
|
||||
"wordcraft::test_harness::HandOver"
|
||||
}
|
||||
|
||||
fn input_hook(&mut self, ctx: &egui::Context, _input: &mut egui::RawInput) {
|
||||
if let Some(input) = PENDING.with(|p| p.borrow_mut().take()) {
|
||||
craft::ui::runtime::frame::set_input(ctx, input);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A bare egui context with the craft runtime installed (the framework's test spec), for a test that
|
||||
/// runs frames by hand (`ctx.run_ui`) instead of through a kittest harness. A frame on a context
|
||||
/// without the runtime has no command registry, so the canvas's publish of its view commands
|
||||
@@ -62,12 +83,11 @@ pub(crate) fn context_with(spec: impl FnOnce() -> InstallSpec) -> egui::Context
|
||||
ctx
|
||||
}
|
||||
|
||||
/// One frame of `h`, a harness built with a ui closure, as the app's driver runs it: the runtime is first handed the
|
||||
/// input the app makes (`WordApp::frame_input`: the command catalog, each command's state, the fired commands), as
|
||||
/// eframe's raw-input hook does (`embed::before_input`). On such a harness `Harness::step` and `run_steps` skip the
|
||||
/// hook, so a command-bound control is named by its command id and a clicked control's command never runs. A test
|
||||
/// that finds such a control by its label, or needs its command to run, steps here. A `build_eframe` harness hands
|
||||
/// the input itself on every step.
|
||||
/// One frame of `h` as the app's driver runs it: the runtime is first handed the input the app makes
|
||||
/// (`WordApp::frame_input`: the command catalog, each command's state, the fired commands), as
|
||||
/// eframe's raw-input hook does (`embed::before_input`). `Harness::step` and `run_steps` skip the
|
||||
/// hook, so a command-bound control is named by its command id and a clicked control's command never
|
||||
/// runs. A test that finds such a control by its label, or needs its command to run, steps here.
|
||||
pub(crate) fn frame(h: &mut egui_kittest::Harness<'_, crate::WordApp>) {
|
||||
let ctx = h.ctx.clone();
|
||||
craft::ui::shell::embed::before_input(&ctx, |out| h.state_mut().frame_input(out));
|
||||
@@ -133,21 +153,14 @@ pub(crate) fn logic(ctx: &egui::Context, app: &mut crate::WordApp) {
|
||||
craft::ui::shell::embed::logic(ctx, || app.close_decision());
|
||||
}
|
||||
|
||||
/// The app as the desktop driver runs it (apps/wordcraft's `eframe::App`), for a `build_eframe` harness: kittest
|
||||
/// calls the raw-input hook before every pass, so each pass has the app's input (the root env with the host, the
|
||||
/// command states, the fired commands), as in production.
|
||||
impl eframe::App for crate::WordApp {
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, _raw: &mut egui::RawInput) {
|
||||
craft::ui::shell::embed::before_input(ctx, |out| self.frame_input(out));
|
||||
}
|
||||
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
logic(ctx, self);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
crate::WordApp::ui(self, ui);
|
||||
}
|
||||
/// [`logic`] for a kittest closure, where the harness's `step` and `run_steps` skip eframe's input hook: the app
|
||||
/// makes its input (`WordApp::frame_input`) at the head of the pass, and the runtime takes it when the next pass
|
||||
/// begins (it refuses input during a pass), so command states, fired commands and focus requests reach the
|
||||
/// passes after it, one frame behind. Needs a harness from [`builder`] or [`builder_with`].
|
||||
pub(crate) fn driver_logic(ctx: &egui::Context, app: &mut crate::WordApp) {
|
||||
let input = app.frame_input(craft::ui::runtime::frame::take_output(ctx));
|
||||
PENDING.with(|p| *p.borrow_mut() = Some(input));
|
||||
logic(ctx, app);
|
||||
}
|
||||
|
||||
/// One frame of `app` on a bare context from [`context`], as the app's driver runs it: the runtime is handed the
|
||||
|
||||
+104
-20
@@ -80,12 +80,10 @@ fn press_ctrl_f1(h: &mut egui_kittest::Harness<'static, WordApp>) {
|
||||
/// A harness over the app, as the tables below drive it.
|
||||
type Rig = egui_kittest::Harness<'static, WordApp>;
|
||||
|
||||
/// One key press with `modifiers`, then two frames: the runtime fires the chord's command in the first, and the app
|
||||
/// runs it before the second (`raw_input_hook`), as on the desktop.
|
||||
/// One key press with `modifiers`, then a frame.
|
||||
fn press(h: &mut Rig, key: egui::Key, modifiers: egui::Modifiers) {
|
||||
h.event(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers });
|
||||
h.step();
|
||||
h.step();
|
||||
}
|
||||
|
||||
/// The style of the first paragraph.
|
||||
@@ -182,6 +180,9 @@ fn row_bound_ctrl_f1_runs_the_bound_command() {
|
||||
let mut h = canvas_harness();
|
||||
// PLAN(shell-w7): sh.A11 `Session::keymap_mut` over `Overrides::insert`.
|
||||
h.state_mut().session.keymap_mut().insert("view.focus", vec!["Mod+F1".into()]);
|
||||
// The harness hands the app's input (with the user's bindings) to the runtime one frame behind (`driver_logic`),
|
||||
// so the binding reaches the keymap in the frame after it is made, as in the row for Mod+Shift+0.
|
||||
h.step();
|
||||
press_ctrl_f1(&mut h);
|
||||
assert!(h.state().session.view.focus_mode, "the bound command ran");
|
||||
assert!(!h.state().ui.ribbon_collapsed, "the ribbon is unchanged");
|
||||
@@ -270,14 +271,13 @@ fn row_mod_shift_0_resets_the_interface_size_unless_bound() {
|
||||
assert_eq!(body_text(h.state()), "}", "AltGr+0 types the character");
|
||||
h.event(egui::Event::Key { key: egui::Key::Num0, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: chord });
|
||||
h.step();
|
||||
h.step();
|
||||
assert!(h.state().ui.interface_size.is_auto(), "Ctrl+Shift+0 returns to Auto");
|
||||
// A binding the user made for the chord wins.
|
||||
h.state_mut().run("ui.interfaceSize", json!({"percent": 300})).unwrap();
|
||||
// PLAN(shell-w7): sh.A11 `Session::keymap_mut` over `Overrides::insert`.
|
||||
h.state_mut().session.keymap_mut().insert("view.focus", vec!["Mod+Shift+0".into()]);
|
||||
h.event(egui::Event::Key { key: egui::Key::Num0, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: chord });
|
||||
h.step();
|
||||
h.event(egui::Event::Key { key: egui::Key::Num0, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: chord });
|
||||
h.step();
|
||||
assert_eq!(h.state().ui.interface_size.percent(), Some(300), "the size stays");
|
||||
assert!(h.state().session.view.focus_mode, "the user's binding runs");
|
||||
@@ -296,7 +296,7 @@ fn row_mod_shift_equals_stays_superscript() {
|
||||
let chord = egui::Modifiers { alt: false, ctrl: true, shift: true, mac_cmd: false, command: true };
|
||||
h.event(egui::Event::Key { key: egui::Key::Equals, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: chord });
|
||||
h.step();
|
||||
// The chord fires its command in that pass; the app runs it before the next pass (`raw_input_hook`).
|
||||
// The chord fires its command in that pass; the app runs it when the next pass begins (`driver_logic`).
|
||||
h.step();
|
||||
assert_eq!(h.state().ui.interface_size.percent(), Some(300), "Ctrl+Shift+= doesn't reset");
|
||||
let pos = wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path::top(0), off: 0 };
|
||||
@@ -490,7 +490,14 @@ fn a_japanese_file_name_is_drawn_in_the_caption() {
|
||||
/// first frame fires that release builds and the components' own trials never reach.
|
||||
#[test]
|
||||
fn the_app_window_shows_for_a_few_frames() {
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| app());
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
app(),
|
||||
);
|
||||
h.run_steps(3);
|
||||
assert!(h.state().has_document(), "the window opened on a document");
|
||||
assert!(!h.state().quit_requested);
|
||||
@@ -626,7 +633,14 @@ fn display_server_is_a_ui_command_and_survives_a_restart() {
|
||||
}
|
||||
|
||||
fn harness(a: WordApp) -> egui_kittest::Harness<'static, WordApp> {
|
||||
crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a)
|
||||
crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
)
|
||||
}
|
||||
|
||||
/// #1908: with no document open the Home ribbon's split buttons grey out like the plain
|
||||
@@ -1525,7 +1539,14 @@ fn every_cut_entry_point_publishes_to_the_clipboard() {
|
||||
assert!(copied(&ctx).contains(&text), "ribbon Cut published {text:?}: {:?}", copied(&ctx));
|
||||
|
||||
// A real Cut key event through the app's key handling.
|
||||
let mut h = crate::test_harness::builder_with(spec).with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| typed());
|
||||
let mut h = crate::test_harness::builder_with(spec).with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
typed(),
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
@@ -1988,7 +2009,14 @@ fn the_default_app_button_shows_only_with_the_hosts_hook() {
|
||||
}));
|
||||
}
|
||||
a.run("ui.backstage", json!({"value": true, "page": "options"})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("Show the community button in the title bar").is_some(), "hook {hook}: the Options page rendered");
|
||||
// The row carries the label too (macOS shows it, with Finder's steps instead of a button): ask for the button.
|
||||
@@ -2041,7 +2069,14 @@ fn the_host_hears_about_edits_made_while_drawing() {
|
||||
let mut a = app();
|
||||
let seen = reported.clone();
|
||||
a.services.on_dirty = Some(Box::new(move |d| seen.set(Some(d))));
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
@@ -2057,7 +2092,14 @@ fn the_host_hears_about_edits_made_while_drawing() {
|
||||
fn paragraph_alignment_keeps_the_canvas_focused_for_typing() {
|
||||
use wordcraft_doc::Align;
|
||||
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| typed());
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
typed(),
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
@@ -2066,7 +2108,7 @@ fn paragraph_alignment_keeps_the_canvas_focused_for_typing() {
|
||||
[("Align Left", Align::Left, " left"), ("Center", Align::Center, " center"), ("Align Right", Align::Right, " right")]
|
||||
{
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Button, label).click();
|
||||
// The click fires the button's command in that pass; the app runs it before the next pass (`raw_input_hook`).
|
||||
// The click fires the button's command in that pass; the app runs it when the next pass begins (`driver_logic`).
|
||||
h.step();
|
||||
h.step();
|
||||
|
||||
@@ -2106,7 +2148,14 @@ fn type_after_click(h: &mut egui_kittest::Harness<'_, WordApp>, what: &str, text
|
||||
fn clicks_on_ribbon_and_status_bar_chrome_keep_typing_in_the_document() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| typed());
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
typed(),
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
@@ -3305,14 +3354,21 @@ fn ctrl_shift_equals_on_the_zero_key_stays_superscript() {
|
||||
a.run("document.setText", json!({"text": "x"})).unwrap();
|
||||
a.run("select.all", json!({})).unwrap();
|
||||
a.run("ui.interfaceSize", json!({"percent": 300})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
let chord = egui::Modifiers { alt: false, ctrl: true, shift: true, mac_cmd: false, command: true };
|
||||
h.event(egui::Event::Key { key: egui::Key::Equals, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: chord });
|
||||
h.step();
|
||||
// The chord fires its command in that pass; the app runs it before the next pass (`raw_input_hook`).
|
||||
// The chord fires its command in that pass; the app runs it when the next pass begins (`driver_logic`).
|
||||
h.step();
|
||||
assert_eq!(h.state().ui.interface_size.percent(), Some(300), "Ctrl+Shift+= doesn't reset");
|
||||
let pos = wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path::top(0), off: 0 };
|
||||
@@ -3325,7 +3381,14 @@ fn ctrl_shift_equals_on_the_zero_key_stays_superscript() {
|
||||
#[test]
|
||||
fn f11_and_escape_toggle_full_screen() {
|
||||
use egui::ViewportCommand::Fullscreen;
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| app());
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
app(),
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
@@ -3369,7 +3432,14 @@ fn f11_and_escape_toggle_full_screen() {
|
||||
#[test]
|
||||
fn escape_collapses_a_selection_before_leaving_full_screen() {
|
||||
use egui::ViewportCommand::Fullscreen;
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| app());
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
app(),
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
@@ -3508,7 +3578,14 @@ fn pasted_picture_inserts_only_when_the_page_is_the_edit_target() {
|
||||
fn paste_harness(a: WordApp) -> egui_kittest::Harness<'static, WordApp> {
|
||||
use craft::platform::clipboard::Clipboard;
|
||||
let spec = || crate::test_harness::install_spec().clipboard(Clipboard::new(LatePaste::default()));
|
||||
let mut h = crate::test_harness::builder_with(spec).with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
let mut h = crate::test_harness::builder_with(spec).with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
@@ -3770,7 +3847,14 @@ fn render_without_a_path_replies_with_the_png() {
|
||||
#[test]
|
||||
fn shift_f10_opens_the_context_menu_at_the_caret() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| app());
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
app(),
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
|
||||
@@ -127,11 +127,7 @@ fn discover_printers(a: &mut WordApp) {
|
||||
}
|
||||
// Discovery runs on native hosts only: where the test host isn't one, the app has found the
|
||||
// recorder's printer and chosen it, as `native_print.rs` sets its own up.
|
||||
let name = if crate::printing::printer_name(&a.printing.settings).is_empty() {
|
||||
"Test queue".to_string()
|
||||
} else {
|
||||
crate::printing::printer_name(&a.printing.settings).to_string()
|
||||
};
|
||||
let name = if a.printing.settings.printer.is_empty() { "Test queue".to_string() } else { a.printing.settings.printer.clone() };
|
||||
if !a.printing.printers.iter().any(|p| p.name == name) {
|
||||
a.printing.printers.push(crate::printing::Printer::new(name.clone()).is_default(true));
|
||||
}
|
||||
@@ -638,7 +634,7 @@ fn return_on_the_print_page_prints() {
|
||||
fn a_successful_native_print_returns_to_the_document() {
|
||||
for ok in [true, false] {
|
||||
let mut a = app();
|
||||
a.printing.settings.destination = crate::printing::Destination::Printer("Test Printer".into());
|
||||
a.printing.settings.printer = "Test Printer".into();
|
||||
a.services.print = Some(Recorder::new(if ok { Reply::Sent } else { Reply::Fail("no paper") }).with_printers(["Test Printer"]).spool());
|
||||
discover_printers(&mut a);
|
||||
a.run("file.print", json!({})).unwrap();
|
||||
@@ -670,7 +666,7 @@ fn cancelling_a_waiting_print_job_frees_the_print_page() {
|
||||
let mut texts: [Option<String>; 2] = [None, None];
|
||||
for (never_sent, close_document) in [(true, false), (false, false), (true, true), (false, true)] {
|
||||
let mut a = app();
|
||||
a.printing.settings.destination = crate::printing::Destination::Printer("Office".into());
|
||||
a.printing.settings.printer = "Office".into();
|
||||
a.printing.settings.copies = 3;
|
||||
// The worker never answers, as when the driver doesn't.
|
||||
let rec = Recorder::cancelling(Reply::Hold, never_sent).with_printers(["Office"]);
|
||||
@@ -692,7 +688,7 @@ fn cancelling_a_waiting_print_job_frees_the_print_page() {
|
||||
assert_eq!(reply["cancelled"], never_sent);
|
||||
assert_eq!(rec.asked_to_cancel(), 1, "the backend was asked to stop the job");
|
||||
assert_eq!(a.printing.busy(), !never_sent, "never_sent {never_sent}: whether the page is still locked");
|
||||
assert_eq!(crate::printing::printer_name(&a.printing.settings), "Office", "the chosen printer is kept");
|
||||
assert_eq!(a.printing.settings.printer, "Office", "the chosen printer is kept");
|
||||
assert_eq!(a.printing.settings.copies, 3, "the settings are kept");
|
||||
assert_eq!(a.printing.printers.len(), 1, "the printer list is kept");
|
||||
let text = said(&a);
|
||||
@@ -737,7 +733,7 @@ fn alt_q_opens_search_and_typing_goes_there() {
|
||||
// Both in one frame's input, as the platform sends them: kittest's `event` runs a frame for each queued event.
|
||||
h.input_mut().events.extend([open.clone(), egui::Event::Text("q".into())]);
|
||||
h.step();
|
||||
// The chord fires the command in that pass; the app runs it before the next pass (`raw_input_hook`).
|
||||
// The chord fires the command in that pass; the app runs it when the next pass begins (`driver_logic`).
|
||||
h.step();
|
||||
// The title bar shows the Search box, so Search opens there, in place (#5398).
|
||||
assert!(h.state().dialog_host.open_dialogs().is_empty(), "no Search Commands dialog over the page");
|
||||
|
||||
@@ -69,7 +69,14 @@ fn table_properties_dialog_sets_every_selected_row() {
|
||||
a.run("table.properties", json!({})).unwrap();
|
||||
|
||||
// Drawn: one click on the mixed box turns breaking on for every row.
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
for _ in 0..4 {
|
||||
h.step();
|
||||
}
|
||||
@@ -298,7 +305,14 @@ fn recipient_grid_edits_the_right_record_through_the_ui() {
|
||||
a.run("mailings.recipients", json!({"csv": "Name,City\nAda,London\nAlan,Wilmslow\nGrace,London\nÉmile,Paris"})).unwrap();
|
||||
a.run("mailings.filterRecipients", json!({"rules": [{"field": "City", "op": "equal", "value": "London"}]})).unwrap();
|
||||
dialogs::open(&mut a, "recipientList", &json!({})).expect("the dialog opens");
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut State| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
let dlg = |h: &egui_kittest::Harness<'_, State>| {
|
||||
let d = h.state().dialog_host.get::<RecipientListDialog>().expect("the recipient dialog is open");
|
||||
@@ -422,7 +436,14 @@ fn an_existing_list_picked_on_the_web_loads_recipients() {
|
||||
/// pane's search box (with the selected text in it), not a dialog.
|
||||
#[test]
|
||||
fn find_replace_and_go_to_keys_like_word() {
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| app());
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
app(),
|
||||
);
|
||||
for _ in 0..6 {
|
||||
h.step();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
//! Scrolling performance with a very large table (#811).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::host::{Host, ManualJobs};
|
||||
use wordcraft_doc::table::{Cell, Table};
|
||||
use wordcraft_doc::{Block, Document, Path, StoryRef};
|
||||
|
||||
@@ -23,13 +20,16 @@ pub(crate) fn big_table_doc(rows: usize, cols: usize) -> Document {
|
||||
d
|
||||
}
|
||||
|
||||
/// A harness over `doc` whose host runs a job only when the test runs its queue ([`ManualJobs`]): page pictures render
|
||||
/// on the test thread at the points the test picks, so what is resident never depends on the runner's load.
|
||||
fn harness(doc: Document) -> (egui_kittest::Harness<'static, WordApp>, Arc<ManualJobs>) {
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let host = Host::builder(crate::APP).i18n(crate::i18n::catalogs()).lang(craft::i18n::Lang::EN).jobs(jobs.clone()).build();
|
||||
let a = WordApp::new(wordcraft_engine::Session::new(doc), Services::default()).with_host(Arc::new(host));
|
||||
(crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a), jobs)
|
||||
fn harness(doc: Document) -> egui_kittest::Harness<'static, WordApp> {
|
||||
let a = WordApp::new(wordcraft_engine::Session::new(doc), Services::default());
|
||||
crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
)
|
||||
}
|
||||
|
||||
/// Queues a pointer move to (720, 500) and a vertical point-unit wheel event that scrolls the view `dy` points.
|
||||
@@ -50,43 +50,34 @@ fn wheel(h: &mut egui_kittest::Harness<'static, WordApp>, dy: f32) {
|
||||
/// #811: scrolling through one very large table was slow because every frame fingerprinted every
|
||||
/// item of every page (thousands of cell borders a page) for the page texture cache, and every
|
||||
/// page ever shown kept its texture. Now a frame lays nothing out again, fingerprints a page once
|
||||
/// per layout and only when it is on screen, and keeps textures only near the view. The pictures render on the
|
||||
/// host's jobs, which the test runs after each scroll step, so the renders for the view have finished when the next
|
||||
/// frame uploads them.
|
||||
/// per layout and only when it is on screen, and keeps textures only near the view.
|
||||
#[test]
|
||||
fn scrolling_a_big_table_fingerprints_only_pages_coming_into_view() {
|
||||
let (mut h, jobs) = harness(big_table_doc(400, 8));
|
||||
let mut h = harness(big_table_doc(600, 8));
|
||||
h.run_steps(4);
|
||||
let layout = h.state_mut().session.layout();
|
||||
let pages = layout.pages.len();
|
||||
// The scroll below crosses about 17 pages; the table runs well past that on every platform's fonts (29 pages on
|
||||
// macOS, more elsewhere), so the view never reaches its end.
|
||||
assert!(pages > 25, "the table runs over many pages ({pages})");
|
||||
assert!(pages > 30, "the table runs over many pages ({pages})");
|
||||
let first = h.state().canvas.page_keys.hashed;
|
||||
assert!(first > 0 && first < 6, "only the pages on screen are fingerprinted, not all {pages}: {first}");
|
||||
// Idle frames do no per-page work.
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().canvas.page_keys.hashed, first, "idle frames fingerprint nothing");
|
||||
assert!(jobs.waiting() > 0, "the pages in view render on the host's jobs");
|
||||
// Scroll a long way down: each newly shown page is fingerprinted once. The renders a step asks for finish before
|
||||
// the next step, whose frame uploads them.
|
||||
// Scroll a long way down: each newly shown page is fingerprinted once.
|
||||
let mut max_textures = 0;
|
||||
for _ in 0..9 {
|
||||
wheel(&mut h, -2000.0);
|
||||
for _ in 0..60 {
|
||||
wheel(&mut h, -400.0);
|
||||
h.step();
|
||||
max_textures = max_textures.max(h.state().canvas.resident_pictures);
|
||||
jobs.run_all();
|
||||
}
|
||||
h.step();
|
||||
let offset = h.state().canvas.view.offset.1;
|
||||
assert!(offset > 16_000.0, "scrolled through many pages: {offset}");
|
||||
assert!(offset > 20_000.0, "scrolled through many pages: {offset}");
|
||||
let after = std::sync::Arc::clone(&h.state_mut().session.layout());
|
||||
assert!(std::sync::Arc::ptr_eq(&layout, &after), "scrolling never lays the document out again");
|
||||
let hashed = h.state().canvas.page_keys.hashed;
|
||||
// 9 steps of 2'000 pt cross about 18'000 / 1'056 ≈ 17 pages (at 100%, 1.33 px a point).
|
||||
assert!(hashed < pages && hashed <= first + 26, "pages fingerprinted: {hashed} of {pages}");
|
||||
// 60 steps of 400 pt cross about 24'000 / 1'056 ≈ 23 pages (at 100%, 1.33 px a point).
|
||||
assert!(hashed < pages && hashed <= first + 30, "pages fingerprinted: {hashed} of {pages}");
|
||||
// Textures stay bounded to the pages near the view.
|
||||
max_textures = max_textures.max(h.state().canvas.resident_pictures);
|
||||
assert!(max_textures <= 12, "textures kept while scrolling: {max_textures}");
|
||||
assert!(h.state().canvas.resident_pictures >= 1, "the pages in view stay rendered");
|
||||
}
|
||||
|
||||
@@ -85,7 +85,14 @@ fn picking_a_wordart_style_hands_the_keyboard_back_to_the_page() {
|
||||
use egui_kittest::kittest::{By, Queryable};
|
||||
let mut a = app();
|
||||
a.run("ui.tab", json!({"tab": "Insert"})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
// Insert › Decorative Text is the WordArt gallery's opener, under that name in production too.
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Button, "Decorative Text").click();
|
||||
@@ -151,7 +158,14 @@ fn citations_provider_menu_has_zotero_checked() {
|
||||
}
|
||||
assert_eq!(a.session.undo_depth(), depth, "not an undo step");
|
||||
a.run("ui.tab", json!({"tab": "Citations"})).unwrap();
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_eframe(|_| a);
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
crate::test_harness::driver_logic(&ctx, app);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(4);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Button, "Provider").click();
|
||||
h.run_steps(3);
|
||||
|
||||
@@ -16,9 +16,6 @@ pub(crate) struct Runtime {
|
||||
/// The desktop app turns the check at start on; tests and the web build leave it off.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
startup_check: bool,
|
||||
/// How many times the test stub answered a check (see `stub_update_check`).
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) stub_calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
|
||||
}
|
||||
|
||||
impl Default for Runtime {
|
||||
@@ -28,8 +25,6 @@ impl Default for Runtime {
|
||||
updater: Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_translator(translate),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
startup_check: false,
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
stub_calls: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,20 +53,6 @@ impl WordApp {
|
||||
rt.updater = Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_translator(translate).with_source(refused_check());
|
||||
}
|
||||
|
||||
/// Answers every update check with "up to date" instead of asking GitHub, so a test's result
|
||||
/// doesn't depend on the network or its rate limit (#7463).
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) fn stub_update_check(&mut self) {
|
||||
let rt = &mut self.updates_rt;
|
||||
rt.startup_check = false;
|
||||
let calls = rt.stub_calls.clone();
|
||||
rt.updater =
|
||||
Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_translator(translate).with_source(std::sync::Arc::new(move || {
|
||||
calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
Ok(None)
|
||||
}));
|
||||
}
|
||||
|
||||
/// Starts the helper of an update that is ready, so that it installs once the process has
|
||||
/// ended. Call it once the exit is certain, before a path that ends the process without
|
||||
/// dropping the app. Later calls do nothing.
|
||||
@@ -87,7 +68,7 @@ impl WordApp {
|
||||
fn refused_check() -> craft::update::updater::CheckSource {
|
||||
let why = tl!("Updates are off in this window: WordCraft was started with another program's AppImage settings. Start WordCraft from its own menu entry to update it.")
|
||||
.to_string();
|
||||
std::sync::Arc::new(move || Err(why.clone().into()))
|
||||
std::sync::Arc::new(move || Err(why.clone()))
|
||||
}
|
||||
|
||||
/// Help ▸ Check for Updates. The result dialog opens from [`run`] while the updater has a status.
|
||||
|
||||
@@ -94,6 +94,9 @@ pub struct Windows {
|
||||
/// Whether the root OS window had focus in the last pass; a [`DocumentWindow`] reports its own gain
|
||||
/// (`focus_gained`), the root's is read from the window host's facts.
|
||||
root_focused: bool,
|
||||
/// The room each window's last draw had, by window key (tests read it).
|
||||
#[cfg(test)]
|
||||
drawn: std::collections::HashMap<u64, egui::Rect>,
|
||||
}
|
||||
|
||||
impl Windows {
|
||||
@@ -101,7 +104,16 @@ impl Windows {
|
||||
pub(crate) fn new(doc: u64) -> Windows {
|
||||
let mut list = WindowList::new();
|
||||
let id = list.open(Window::new(doc, None, None, false));
|
||||
Windows { native: cfg!(not(target_arch = "wasm32")), list, root: id, shown: id, arranged: arrange::State::default(), root_focused: false }
|
||||
Windows {
|
||||
native: cfg!(not(target_arch = "wasm32")),
|
||||
list,
|
||||
root: id,
|
||||
shown: id,
|
||||
arranged: arrange::State::default(),
|
||||
root_focused: false,
|
||||
#[cfg(test)]
|
||||
drawn: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether documents get native windows of their own.
|
||||
@@ -528,7 +540,10 @@ impl WordApp {
|
||||
let (raise, place) = (std::mem::take(&mut w.raise), std::mem::take(&mut w.place));
|
||||
let mut window = DocumentWindow::new(Self::title_in(&menu, id))
|
||||
.id(window_container_id(id))
|
||||
.overlay(|overlay| overlay.size_limits(SizeLimits::at_least(MIN_SIZE)));
|
||||
// The window's body is the whole interface, which lays itself out in the window's room. A
|
||||
// scrolling body gives it an unbounded height instead (#7149 item 5): the interface lands
|
||||
// 32768 points tall, off the window, and the window shows nothing.
|
||||
.overlay(|overlay| overlay.size_limits(SizeLimits::at_least(MIN_SIZE)).body_scroll(false));
|
||||
if raise {
|
||||
window = window.raise();
|
||||
}
|
||||
@@ -586,6 +601,8 @@ impl WordApp {
|
||||
if self.windows.shown() != key {
|
||||
return;
|
||||
}
|
||||
#[cfg(test)]
|
||||
self.windows.drawn.insert(key, ui.max_rect());
|
||||
self.window_ui(ui);
|
||||
arrange::forward_scroll(self, &ctx);
|
||||
}
|
||||
|
||||
@@ -23,13 +23,11 @@ struct Rig {
|
||||
commands: Vec<(ViewportId, ViewportCommand)>,
|
||||
/// The viewports that drew in the last frame, in order.
|
||||
drawn: Vec<ViewportId>,
|
||||
/// How the viewports asked to open their windows in every frame so far.
|
||||
builders: Vec<egui::ViewportBuilder>,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new() -> Rig {
|
||||
Rig { kit: Kit::new(), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new(), builders: Vec::new() }
|
||||
Rig { kit: Kit::new(), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new() }
|
||||
}
|
||||
|
||||
fn ctx(&self) -> egui::Context {
|
||||
@@ -60,7 +58,6 @@ impl Rig {
|
||||
craft::ui::shell::embed::logic(ui.ctx(), || a.close_decision());
|
||||
a.ui(ui);
|
||||
});
|
||||
self.builders.extend(out.builders.into_iter().map(|(_, b)| b));
|
||||
self.commands = out.commands;
|
||||
self.drawn = out.trees.iter().map(|(v, _)| *v).collect();
|
||||
self.closing.clear();
|
||||
@@ -142,6 +139,24 @@ fn new_opens_a_second_window_and_each_keeps_its_state() {
|
||||
assert_eq!((text(&a), a.ui.tab.as_str(), prompt(&a).as_deref()), ("Second".into(), crate::DEFAULT_TAB, None));
|
||||
}
|
||||
|
||||
/// Each window draws its interface in the room its OS window gives it. A window's body that scrolls lays the
|
||||
/// interface out 32768 points tall, so a second window opened blank (#7149 item 5).
|
||||
#[test]
|
||||
fn a_second_window_draws_its_interface_in_the_room_of_its_window() {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("First");
|
||||
rig.frames(&mut a, 3);
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
rig.frames(&mut a, 6);
|
||||
let child = a.active_viewport();
|
||||
assert_ne!(child, ViewportId::ROOT);
|
||||
assert!(rig.drawn.contains(&child), "the second window draws: {:?}", rig.drawn);
|
||||
let key = a.windows.active().unwrap();
|
||||
let room = a.windows.drawn.get(&key).copied().unwrap();
|
||||
// The kit's child window is 400 by 300 points.
|
||||
assert!(room.height() <= 300.0 && room.min.y >= 0.0 && room.max.y <= 300.0, "the interface has the window's room, not {room:?}");
|
||||
}
|
||||
|
||||
/// Each window has its own key, and the root window's stays `main` when it adopts another entry.
|
||||
#[test]
|
||||
fn window_keys_differ_and_the_root_keeps_main() {
|
||||
@@ -517,30 +532,3 @@ fn every_open_replaces_an_untouched_blank_document_in_its_window() {
|
||||
}
|
||||
std::fs::remove_dir_all(second.parent().unwrap()).ok();
|
||||
}
|
||||
|
||||
/// #3634: a NUL in the document title never reaches an OS window title (X11 and Wayland panic on
|
||||
/// it): not a native window's builder, not a `Title` command, not the window menu. Checks what the
|
||||
/// frames send, so a new title source that skips `display_title` fails here.
|
||||
#[test]
|
||||
fn nul_in_the_document_title_never_reaches_an_os_window_title() {
|
||||
for raw in ["\u{0}", "a\u{0}b"] {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("x");
|
||||
a.run("file.properties", json!({"title": raw})).unwrap();
|
||||
let mut sent = Vec::new();
|
||||
for i in 0..6 {
|
||||
if i == 3 {
|
||||
a.run("view.newWindow", json!({})).unwrap();
|
||||
assert_eq!(a.window_count(), 2);
|
||||
}
|
||||
rig.frame(&mut a);
|
||||
sent.extend(rig.commands.iter().filter_map(|(_, c)| if let ViewportCommand::Title(t) = c { Some(t.clone()) } else { None }));
|
||||
}
|
||||
sent.extend(rig.builders.iter().filter_map(|b| b.title.clone()));
|
||||
sent.extend(a.switch_windows_entries().into_iter().map(|e| e.1));
|
||||
assert!(rig.builders.iter().any(|b| b.title.is_some()), "the new window's builder carries a title");
|
||||
for t in &sent {
|
||||
assert!(std::ffi::CString::new(t.as_str()).is_ok(), "an OS window title without NUL ({raw:?}): {t:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use craft::menu::CommandRef;
|
||||
use craft::ui::contract::{ActivateOn, BodyCx, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::display::Divider;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::list::{ThumbAspect, ThumbSize};
|
||||
use craft::ui::list::ThumbAspect;
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
|
||||
@@ -184,7 +184,6 @@ pub fn transform_menu(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
|
||||
.select(SelectMode::None)
|
||||
.activate(ActivateOn::Click)
|
||||
.card_columns(4)
|
||||
.thumb_size(ThumbSize::Small)
|
||||
// Every warp shows; the menu's body is the one scroll.
|
||||
.natural_height(true)
|
||||
.show_items(ui, &source, &mut |id, _| {
|
||||
@@ -277,26 +276,4 @@ mod tests {
|
||||
a.run("caret.set", json!({"pos": wordcraft_doc::Pos::body(0, 2)})).unwrap();
|
||||
assert_eq!(current_outline(&a), None, "the body text has no outline");
|
||||
}
|
||||
|
||||
/// #7449: the Transform menu renders compact preview tiles (~46×32 pt)
|
||||
/// instead of expanding each warp thumbnail to default card dimensions (~132 pt).
|
||||
#[test]
|
||||
fn transform_menu_renders_compact_tiles() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
|
||||
let a = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Transform")), crate::Services::default());
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(600.0, 700.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
Menu::inline("Transform").show(ui, |ui, cx| transform_menu(ui, cx, app));
|
||||
},
|
||||
a,
|
||||
);
|
||||
h.run_steps(2);
|
||||
|
||||
let tile = h.get_by_role_and_label(Role::ListItem, "Arch Up").rect();
|
||||
assert!(tile.width() <= 60.0 && tile.height() <= 45.0, "transform tile is compact (~46×32 pt), got {:?}", tile.size());
|
||||
let grid = h.get_by_role_and_label(Role::ListBox, "Transform").rect();
|
||||
assert!(grid.width() <= 260.0, "4-column transform menu grid width stays compact (~200 pt), got {:?}", grid.size());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ let apps move windows, so there Arrange All and Side by Side only resize.
|
||||
| `ui.wheel` | `x`, `y`, `dy`, `dx?`, `unit?` (`point`/`line`/`page`), `phase?` (`start`/`move`/`end`), modifiers | mouse-wheel or trackpad scroll at window coordinates (`dy` < 0 scrolls down) |
|
||||
| `ui.key` | `key` (`B`, `Enter`, `Left`…), `shift?`, `alt?`, `cmd?` | key press through egui (shortcuts apply) |
|
||||
| `ui.text` | `text` | typed text through egui |
|
||||
| `ui.screenshot` | `path?`, `region?` (`[x0, y0, x1, y1]` in points) | PNG of the window (or of `region`) in the root viewport: written to `path`, or without one returned as base64 `png` in the reply. Capturing a secondary document window is not supported by the viewport renderer; select the root window with `view.switchWindows {"window": root}` first |
|
||||
| `ui.screenshot` | `path?` | PNG of the window in the root viewport: written to `path`, or without one returned as base64 `png` in the reply. Capturing a secondary document window is not supported by the viewport renderer; select the root window with `view.switchWindows {"window": root}` first |
|
||||
| `ui.render` | `path?`, `page?` (1-based), `scale?`, `doc?` | PNG of a page, rendered by the engine: written to `path`, or without one returned as base64 `png` in the reply (never a fixed name in the shared temporary folder) |
|
||||
| `ui.parity` | — | feature-catalog parity |
|
||||
| `ui.resize` | `width`, `height` | asks for that window content size in points; sizes that aren't positive and finite are refused, the rest are clamped to the app's minimum (600 × 480, #5886) and to the largest surface the GPU can draw (at most 16384; that limit wins over the minimum), and the reply's `width` and `height` are the size asked for |
|
||||
|
||||
+2
-6
File diff suppressed because one or more lines are too long
+5
-22
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user