Compare commits

..
102 Commits
Author SHA1 Message Date
skylar taylor f2e6403b9c Merge pull request #8914 from storytold/release-0.20.1-hotfix
Release 0.20.1: maximize and full screen on Windows again (#8838)
2026-12-04 12:45:16 -06:00
skylartaylor 1f1d8a05f7 Release 0.20.1: maximize and full-screen fix for Windows (#8838)
Pins craft-libs ad10c35a (wordcraft#8871's pin; one commit on the shipped 5299d8d9) and bumps to 0.20.1.
2026-12-04 18:39:29 +01:00
Martin BallandClaude Opus 5.5 72798d3db1 packaging(linux): riscv64 smoke test sets MALLOC_TRIM_THRESHOLD_ so the CLI doesn't restart under QEMU (#8786)
Since #7914 the CLI restarts itself to set MALLOC_TRIM_THRESHOLD_. Under user-mode
qemu-riscv64 with no binfmt handler the restart can't run the riscv64 binary, glibc's
execvp hands it to /bin/sh, and the release job fails with 'Syntax error: word
unexpected'. Setting the variable skips the restart. Real riscv64 hosts are unaffected.


Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 02:27:41 +00:00
Martin Ball f1665031b3 Merge remote-tracking branch 'origin/main' into release
; Conflicts:
;	Cargo.lock
;	Cargo.toml
2026-12-04 00:45:48 +00:00
Martin BallandClaude Opus 5.5 8baa46395f Release: version 0.20.0 (#8711)
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 00:42:46 +00:00
Martin BallandClaude Opus 5.5 2f08031e75 macOS: Cmd+Q and WordCraft › Quit ask about every unsaved document (#8709) (#8741)
* fix(macos): Cmd+Q and the app menu's Quit ask about every document (#8709)

The app menu had no Quit item, so craft added its own, whose click only
closed the root window. Add a ui.quit command (WordApp::quit, as the
Dock's Quit) and a Quit-role app-menu item that runs it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* native_menu test: CommandRef is not an Option (#8709)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 00:42:23 +00:00
Martin BallandClaude Opus 5.5 e9f07d8837 Multi-window: file.close save, ui.closeWindow window, close-prompt coverage (#7822) (#8624)
* Closing document windows: file.close save, ui.closeWindow window, prompt raised on window focus (#7822)

Spec rules 3, 5, 6 and 8 of docs/specs/multi-window-close.md that the close-owner
work (#8277) left open, with a test each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Review fixes: file.close save keeps the comment-draft refusal; drop redundant focus hunk (#7822)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* ADR 0001: X11, XWayland and BSD on X11 keep a visible root (amendment)

egui's windowless root returns UnsupportedConfiguration there; WordCraft
falls back to the windowed root. The close rules still apply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Repin craft-libs to 5299d8d9 (windowless root support, IconPicker previews, CellGrid fix)

craft-libs d73e274a -> 5299d8d9 (every craft-libs rev, craft-nightly and the
patches), egui 07c20531 -> 399fc6e0, winit 0dfcec0e -> 3fd7ae64, the revs
craft-libs main builds with. Cargo.lock updated for those packages only.

Adapt to the hosted unsaved-changes question: the dialog host takes
HostedUnsavedChangesDialog, not UnsavedChangesDialog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Windowless root: every document window is a child; X11 keeps the visible root (#7822)

Use eframe's RootViewportMode::Windowless with InstallSpec::windowless_root unless
the session is X11, and fall back to the visible root on UnsupportedConfiguration.
active_viewport/viewports no longer fall back to ROOT when windowless; close_decision
closes when no documents remain; a window that failed to open is dropped and the user
told; ui.closeWindow replies requested:false while a Save prompt is open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Windowless root: save window place every frame, raise Save prompt on sole-window close (#7822)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(windows): save on window-only file.close; point ui.closeWindow docs at ui.inspect; document save scope (#8624)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* ADR 0001: X11 keeps #7752; dialogs have no parent under the windowless root

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Windowless root: only the first window takes the saved place; a promoted survivor stays put (#7822)

Reported on macOS: closing the first window moved the surviving window to the
first window's saved place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* Windowless root: files dropped on a document window reach the intake (#7822)

eframe runs raw_input_hook only for the root and deferred viewports; document
windows are immediate viewports, so under the windowless root no drop reached
the app. A viewport hook forwards child-window drops. Pointed out by Skylar
(windowless/default-on-reference).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 00:42:19 +00:00
autocraft-bot[bot] 5073f8e7c2 Merge pull request #8728 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] f1fb526f3f Merge pull request #8721 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] de328db448 Merge pull request #8719 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 0600244e11 Merge pull request #8662
With AutoCraft's conflict resolution a0a3c553.
2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 1ffd5f8d4a Merge pull request #8647
With AutoCraft's conflict resolution 849eb756.
2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 0df3151f01 Merge pull request #8727 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] b4ecd20dba Merge pull request #8631 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] e3d1ee90c3 Merge pull request #6587
With AutoCraft's conflict resolution 8460bff5.
2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 3b0257ff33 Merge pull request #6943
With AutoCraft's conflict resolution edb53680.
2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 3b2ce5cb83 Merge pull request #8718 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] cfae52c97d Merge pull request #8714 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] d7986fc26c Merge pull request #8710 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] e7172b9a8a Merge pull request #8705 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] bbc587e2a6 Merge pull request #8704 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 92eb57fd08 Merge pull request #8703 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 161c127926 Merge pull request #8702 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 3138201a56 Merge pull request #8692 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 1591f99189 Merge pull request #8691 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] e2f2fe1f09 Merge pull request #8678 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 0e47c8613c Merge pull request #8690 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 1812618f10 Merge pull request #8689 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] b211131dec Merge pull request #8681 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] f1ad785403 Merge pull request #8675 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] e3653ada4b Merge pull request #8677 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 167e479382 Merge pull request #8676 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 81abc0d81b Merge pull request #8674 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] eb8a7e311c Merge pull request #8671 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 040150d486 Merge pull request #8670 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] b7e49e84b3 Merge pull request #8666 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 168e39e5a4 Merge pull request #8667 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 0fe7ede07e Merge pull request #8664 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 5b24de412e Merge pull request #8645 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 5dad217316 Merge pull request #8641 2026-12-03 22:27:58 +00:00
autocraft-bot[bot] 2ad2694407 Merge pull request #8284 2026-12-03 22:27:58 +00:00
Martin BallandClaude Opus 5.5 4622fef6ce Repin craft-libs to 5299d8d9 (windowless root support, IconPicker previews, CellGrid fix) (#8699)
* Repin craft-libs to 5299d8d9 (windowless root support, IconPicker previews, CellGrid fix)

craft-libs d73e274a -> 5299d8d9 (every craft-libs rev, craft-nightly and the
patches), egui 07c20531 -> 399fc6e0, winit 0dfcec0e -> 3fd7ae64, the revs
craft-libs main builds with. Cargo.lock updated for those packages only.

Adapt to the hosted unsaved-changes question: the dialog host takes
HostedUnsavedChangesDialog, not UnsavedChangesDialog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(comments): selecting a comment card no longer opens its message for edit

craft-libs now hides a card's Reply button and reply box while one of its
messages is in the editor. focus_balloon opened the lead message's edit on
every selection, so Reply was never reachable. As in Word, selecting a card
selects it and its anchor; editing starts on a double click in a message or
the message menu's Edit, and Reply stays available.

Tests that typed straight after clicking a balloon now open the edit as the
card's Edit does (click_balloon); the reply test only selects the card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

* fix(comments): a double click on the selected comment card opens its edit

Selecting a card no longer opens its message for edit (that hid Reply), so
craft-libs' CommentBalloons left no way to start an edit. A double click on
the selected card's own text now opens message 0 for editing, as in the
comments pane. Keyboard path (Enter/F2) is not added here.

Tests open the edit with that double click instead of setting state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 22:27:58 +00:00
yoriswind 061985fb6b Test AutoSave format eligibility separately from opt-out 2026-12-03 14:16:27 -08:00
autocraft-bot[bot] b8334518b3 Merge main (af4cacc4) into the pull request 2026-12-03 22:15:26 +00:00
batistalucasv 2b612d51fa Layout: a centre tab moved to the next line starts with no room, as a right tab does
A centre or decimal tab that moves on to the next line with its text kept the width it had on the line before, so the shift of its text was worked out from that old width and the text was off its stop. Every tab whose text is pending now starts with no room.
2026-12-03 19:09:33 -03:00
batistalucasv 472399cb33 Layout: the automatic-space check reads a run's East Asian theme slot over the inherited named font (#8697) 2026-12-03 19:08:54 -03:00
yoriswind 25b86d2a1d Preserve the document AutoSave choice on manual Save 2026-12-03 13:52:05 -08:00
batistalucasv dd3dedddae Tests: cover mid-document TOC insert and single-step undo (#8385) 2026-12-03 18:47:31 -03:00
batistalucasv 04e04e8119 test(ui-egui): trim frames and window size in Link shortcut test (#8338) 2026-12-03 18:45:54 -03:00
batistalucasv e3749fc2d0 test(widgets): drive font_box with Catalog::global and action rows in keystroke-frame test (#8447) 2026-12-03 18:33:49 -03:00
batistalucasv 020eba42ff test(ui-egui): close Backstage via ui.backstage command in keytips test (#8498) 2026-12-03 18:13:29 -03:00
batistalucasv 1a339aebb4 Tests: trim duplicate terminal-paragraph compare checks (#8503) 2026-12-03 17:38:12 -03:00
batistalucasv 5d46607ec4 docs(ui-egui): clarify perf_probe edit-burst comment (#8510) 2026-12-03 17:33:23 -03:00
batistalucasv 456aa68148 Tests: exercise the 0.4 pt boundary step in fit_one_page_respects_step_pt (#8432) 2026-12-03 17:25:04 -03:00
batistalucasv 83ada40e06 Canvas test: verify Ctrl/⌘ press in the grey area is ignored 2026-12-03 17:17:31 -03:00
yoriswind b36fa16a15 Index ruler grid spans in one pass 2026-12-03 12:00:31 -08:00
yoriswind 04cd0ca6fd Enter visible equations across hidden deletions 2026-12-03 11:54:42 -08:00
batistalucasv 05cbdfd9ff layout: update RTL table margin comments (#8516) 2026-12-03 16:51:11 -03:00
batistalucasv e66ba81d3f Layout: use unkerned width in hyphenation fit check (#8617) 2026-12-03 16:44:47 -03:00
batistalucasv 8bf97aa275 Layout: drop the line-end kerning pair from settled line positions (#8617) 2026-12-03 16:40:56 -03:00
batistalucasv a2960ce55d test(formats,engine): cover shared-model conversion error propagation (#8523) 2026-12-03 16:39:43 -03:00
batistalucasv 48b211621d Tests: remove redundant Dictate icon shape check from stub ribbon test (#8615) 2026-12-03 16:37:59 -03:00
batistalucasv c39e70fc85 engine: remove duplicate German date-field integration tests (#8540) 2026-12-03 16:33:51 -03:00
batistalucasv 0a1d913690 engine: drop redundant turns_on branches and cover collapsed caret (#8658) 2026-12-03 16:32:01 -03:00
batistalucasv c55e7a83e6 Layout: test a long word in a short at-least turned row (#8487) 2026-12-03 16:22:14 -03:00
batistalucasv 129b6ad2f9 xtask(wasm): check wasm-safe test targets and drop source-text test (#8579) 2026-12-03 16:18:01 -03:00
RickiNano fc3146206a Review: Accept/Reject All puts the caret before a removed last paragraph (#8500)
When Reject All (an inserted paragraph) or Accept All (a deleted one)
removed the last paragraph of a story or cell, the selection kept its
path until the final clamp, which moved it into the paragraph before
with the same offsets. A selection of "NEW" after "Keep this" became a
selection of "Kee", and typing replaced it.

Selection ends in the removed paragraph now go to the end of the
paragraph before it, as soon as remove_trailing_para removes it.
2026-12-03 20:17:53 +01:00
batistalucasv b682a1fd06 PDF export: tag header and footer link annotations with Link/OBJR (#8642) 2026-12-03 16:17:01 -03:00
batistalucasv 6bdd6769d1 Tests: retry transient Windows token-file timeout in control_server lifecycle test (#8556) 2026-12-03 16:09:40 -03:00
batistalucasv 6a6dfd7f58 Docs: restore ui.drag in control protocol reference (#8559) 2026-12-03 16:09:16 -03:00
batistalucasv 4c600213dc Tests: check nested group flattening in note separators (#8573)
Replace a_frame_shape_in_a_note_separator_reads_as_a_rectangle with
linked_nested_group_in_a_note_separator_is_flattened so the test checks
behaviour only blocks_from_shared provides (flattening a hyperlinked
nested group) rather than ShapeKind::Frame, which the serde convert
fallback now also handles.
2026-12-03 16:08:12 -03:00
autocraft-bot[bot] af4cacc45f Merge pull request #8637 2026-12-03 19:02:47 +00:00
batistalucasv 9d5789162f Layout: mark begins_section run-over case as inferred (#8569) 2026-12-03 16:01:11 -03:00
batistalucasv cdef8012e9 Tests: merge whole-paragraph mark compare checks into existing test (#8470) 2026-12-03 16:01:05 -03:00
batistalucasv 8bca61f529 docs(layout-parity): record turned text rule and Word evidence for at-least rows (#8486) 2026-12-03 16:00:58 -03:00
batistalucasv 4dd74c36d5 docs(layout): mention cell_frame in Joint::take_up doc comment
Fixes #8564
2026-12-03 15:59:36 -03:00
yoriswind 83381d344a Merge main and streamline hidden-deletion caret movement 2026-12-03 10:55:10 -08:00
batistalucasv 46050e5c4b Docs: document ui.move and pointer position parameters in the control protocol 2026-12-03 15:52:48 -03:00
batistalucasv 4073aa4274 docs(layout-parity): record list-number kerning in status line (#8583) 2026-12-03 15:26:11 -03:00
yoriswind 95388461a7 Layout: import Pos in the grid kerning regression 2026-12-03 10:18:59 -08:00
yoriswind 8544a588c1 test(table_resize): format the merged-row regression 2026-12-03 10:06:35 -08:00
yoriswind 9964e4e88c Layout: fit kerned characters into exact grid cells 2026-12-03 09:58:16 -08:00
yoriswind d25db5fa8f Layout: align table ruler feedback with the caret row grid 2026-12-03 09:47:53 -08:00
yoriswind 9386f754f4 test(engine): qualify caret regression selection type 2026-12-02 15:24:09 -08:00
autocraft-bot[bot] f670da8602 Part 1: in crates/layout/src/floats.rs, the re-placement condition is no
Part 1: in crates/layout/src/floats.rs, the re-placement condition is now `float.y < 0.0 && area.map_or(r.bottom(), |(_, b)| b) < y0 + lead - 0.5`. Floats without a wrap area (in front of or behind text) now need a negative offset and to sit above the pushed first line, like wrapping floats. A positive-offset label over a top-and-bottom picture is no longer moved down. fmt --check and clippy -D warnings are clean. In `cargo test -p wordcraft-layout`, 756 passed and 1 failed: the timing test a_megabyte_long_word_lays_out_quickly, which has no floats and failed again alone after 244 s. I think the sandbox is slow, but I didn't run it on the base commit. I didn't add a test for the label-over-picture case.
2026-12-02 20:00:12 +00:00
yoriswind a937df1bb7 fix(layout): keep visual caret out of omitted runs 2026-12-01 16:25:10 -08:00
yoriswind b6488c5773 fix(engine): skip hidden tracked deletions with the caret 2026-12-01 16:15:29 -08:00
skylartaylor 5d658dc033 Release: WordCraft v0.19.1 (main 09faec42ec, pre-UI-port) 2026-11-25 19:28:58 +01:00
skylartaylor 6b7788d8e0 Release: bump WordCraft to v0.19.1 (on 09faec42, the pre-UI-port candidate) 2026-11-25 19:27:28 +01:00
pakiat 64960989a1 Merge commit 'c369c3a20befef8742f8913128cacd79002435d6' into m/6943
# Conflicts:
#	docs/layout-parity.md
2026-11-23 07:41:22 +07:00
jayzed80 4e79e67534 Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts:
#	crates/layout/src/tests.rs
2026-11-18 21:15:56 +00:00
pakiat 0f83ea9cf4 Merge commit '6ef13b2cc8a60e6391d7a5b92459ec47598d58a9' into m/6943
# Conflicts:
#	docs/gaps.md
2026-11-18 22:32:56 +07:00
pakiatandClaude Opus 5.5 0859a447b6 Tables: a first row's w:tblPrEx left border is the half border a table moves in by
From mode 15 Word moves a table in by half its first cell's left border. The
cell's own border comes first, then the first row's table property exceptions,
then the table's. Measured in Word for Windows: an 8 pt table border with a 2 pt
exception puts the text 1 pt in, inline and floating. Inline tables had the
same gap, so both use one helper now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 06:13:43 +07:00
pakiat df07115145 Merge commit '22a73d9f2d10de6ee52780ab4a6019b864d9c598' into m/6943
# Conflicts:
#	docs/gaps.md
2026-11-18 06:09:09 +07:00
pakiatandClaude Opus 5.5 a761f276d5 Tables: a floating table placed by an offset takes its indent before Word 2013, half its border from it
Measured in Word for Windows 16.0.20527: before Word 2013 layout a
floating table placed by an offset has its first cell's text at the
offset moved by w:tblInd (WordCraft ignored the indent); from Word 2013
its edge is at the offset moved in by half its left border (WordCraft
left out the half border) and w:tblInd doesn't move it. Moved below
another floating table, it keeps its distance from the text's edge the
same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:49:39 +07:00
FredApps 2cde91a869 Release: WordCraft v0.19.0 (main 323cf78232) 2026-11-14 21:48:03 +01:00
FredApps 76e5732355 Release: WordCraft v0.19.0 2026-11-14 21:48:00 +01:00
jayzed80 50041c808c Address review: keep a re-placed float's x, and don't move a wrap area onto the first line (#6567)
A float placed again from a pushed-down first line takes only its new
vertical position, so its drawn rect and wrap area stay together across.
A wrapping float whose moved area would reach the first line stays where
it was: that line was laid out without it in the way.
2026-11-14 01:02:27 +00:00
jayzed80 c0c42caf95 Layout: measure sibling paragraph floats from a wrapped first line (#6567) 2026-11-14 00:13:46 +00:00
Dylan M. Taylor 079f478bd8 Merge tested main for v0.18.1 2026-11-11 18:38:09 -05:00
FredApps 7296cf64de Merge main into release for WordCraft v0.18.0 2026-11-11 19:36:24 +01:00
Dylan M. Taylor 5574b32600 Release 0.17.0 2026-11-09 06:34:22 -05:00
94 changed files with 3151 additions and 2432 deletions
Generated
+131 -145
View File
File diff suppressed because it is too large Load Diff
+55 -55
View File
@@ -13,7 +13,7 @@ run_slots = 3
test_threads = 4
[workspace.package]
version = "0.18.1"
version = "0.20.1"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -37,22 +37,22 @@ 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 = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
wordcraft-proof = { package = "craft-proof", git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-ssip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", 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" }
wordcraft-validate = { path = "crates/validate" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false }
craft-ui-test-kit = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -85,28 +85,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 = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", default-features = false, features = ["write"] }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", default-features = false, features = ["write"] }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", version = "=0.1.0" }
craft-wordmodel = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-docx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-rtf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["doc"] }
craft-doc-binary = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-flow = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-odf = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["text"] }
craft-markdown = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-html = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["flow"] }
craft-latex = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-math = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0", features = ["detect"] }
craft-sheet = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-ods = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xlsx = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", version = "=0.1.0" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", 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"
@@ -174,27 +174,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 = "d73e274a01408ef433a291a667e6014937d72165" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" }
winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
-5
View File
@@ -155,11 +155,6 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
## Progress log
- 2026-11-21: Page text on the shared page view is sharp again. After the port, pages were rasterised at the view's own scale and rounded up to whole pixels, which left a picture a pixel or two larger than its place on screen (2017 × 2852 for 2016 × 2851); the shared painter fits a picture into its place, so it was squeezed by a twentieth of a percent and the text slid off the pixel grid and back down the page: a reporter's screenshot showed baselines spread over three pixel rows. Pictures are now made exactly as many pixels each way as the place the view last rested at, which the painter draws one pixel for one. A headless test through the real page view and picture store holds this at three zooms and two screen densities. Not yet seen in the running app. Readiness estimates unchanged.
- 2026-11-20: The sharper page text, subpixel (LCD) text and the Screen text smoothing option are ported onto the shared page view and Options that the UI port (#7101) brought. Two things changed on the way. The page view asks for page pictures rounded up to a multiple of 16 pixels and scales them into place, which resamples every glyph (A4 at 100 % on a 2x screen: 2256 pixels for 2245), so pages are now rasterised at the view's own scale wherever it accounts for the side asked for, and subpixel text is drawn only on such pictures. And the app no longer reads the system's text settings itself: system access moved to craft-libs' `platform::appearance`, which has none, so pages are drawn each platform's fixed way plus the user's own Screen text smoothing choice until craft-libs reports them (the 2026-11-19 entry on following the system no longer holds). Two shared-API gaps are recorded in `docs/ui-parity.md`: the text settings reader, and drawing a screen-scale page picture at its own pixel size. Run on macOS only; not seen in the running app since the port. Readiness estimates unchanged.
- 2026-11-19: Page text can be drawn with subpixel (LCD) antialiasing: File › Options › General › Screen text smoothing offers Use system setting, Grayscale and Subpixel (LCD); `view.textSmoothing` reaches the same setting headlessly. A page is rasterised three times with only its text a third of a pixel apart and each colour channel is taken from the pass that matches its stripe, so drawing order, coloured text, dark pages and rotated text need no special cases and nothing but text gets coloured edges. Once the system settings are read (nothing reads them yet), "Use system setting" will turn it on where the system asks for it (ClearType, or `rgba` antialiasing on a Linux desktop) on screens below 2x; macOS never asks, so there it is the user's choice. Exports are unchanged. Run on macOS only, on headless rasters: not yet seen on a 1x LCD, on Windows or on Linux, and not timed. Readiness estimates unchanged.
- 2026-11-19: Page drawing can take the system's text settings (darkening strength, hinting, subpixel order), but nothing reads them from the system yet, so pages are drawn each platform's fixed way and "Use system setting" is greyscale. Readiness estimates unchanged.
- 2026-11-19: Page text on macOS and Windows is no longer soft. Baselines sit on whole device pixels, so the feet of the letters fill one pixel row instead of greying two; and the macOS font smoothing we imitate thickens letters sideways only, by widening each outline and filling it once, where a stroke all round added a third of a pixel of grey above and below every letter. Found by comparing 144 dpi screenshots of the same paragraph in WordCraft, Preview and OpenOffice: none of the three used subpixel antialiasing; WordCraft alone had its serifs spread over two rows. Linux and BSD text was already hinted onto the grid; exports are unchanged. Readiness estimates unchanged.
- 2026-12-01: Hindi interface language (`hi`): File › Options › Interface language offers हिन्दी, and `hi`, `hi-IN` and `hi_IN.UTF-8` system locales pick it. The catalog is craft-i18n's `locales/hi/wordcraft.tsv` (`craft-i18n.rev` at 217f413); interface text is drawn by the embedded Noto Sans Devanagari face. No Hindi proofing, so the Hindi interface doesn't set the language of new documents. Readiness estimates unchanged.
- 2026-11-28: Layout indexes numbering definitions for each list and STYLEREF walk. List labels still follow the document's literal labels, start overrides and nested restart rules (#3615).
+128 -14
View File
@@ -10,6 +10,7 @@ use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use craft::automation::AutomationError;
use craft::automation::args::ControlOptions;
use craft::automation::control::ControlRequest;
use craft::automation::server::{Listening, serve};
@@ -38,6 +39,22 @@ fn remove(path: Option<&Path>) {
}
}
/// Why starting the control server did not succeed.
enum StartError {
/// Windows external-tool timeout while creating or checking the owner-only token file.
TokenTimeout(String),
/// Any other bind, token, or accept-thread error.
Other(String),
}
impl StartError {
fn message(&self) -> &str {
match self {
Self::TokenTimeout(msg) | Self::Other(msg) => msg,
}
}
}
/// Bind `127.0.0.1:port`, settle the token and serve. `None` when the port cannot be bound or
/// the token cannot be set up (the control channel is off); a taken port leaves no token file.
///
@@ -45,35 +62,49 @@ fn remove(path: Option<&Path>) {
/// `port` in `settings`; a file left by a run that did not exit cleanly is replaced. Without a
/// settings folder a fresh token is generated and reported by the log.
pub fn start(options: &ControlOptions, port: u16, host: WindowHost, settings: Option<&Path>) -> Option<(Receiver<ControlRequest>, Control)> {
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
log::error!("control server failed to bind 127.0.0.1:{port}: {e}");
return None;
match start_with(options, port, host, settings, ControlOptions::server_token) {
Ok(started) => Some(started),
Err(err) => {
log::error!("{}", err.message());
None
}
};
}
}
fn start_with(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
token_for: impl FnOnce(&ControlOptions) -> Result<String, AutomationError>,
) -> Result<(Receiver<ControlRequest>, Control), StartError> {
let listener =
TcpListener::bind(("127.0.0.1", port)).map_err(|e| StartError::Other(format!("control server failed to bind 127.0.0.1:{port}: {e}")))?;
let created = settings.filter(|_| options.token.is_none() && options.token_file.is_none()).map(|dir| wordcraft_control_key::key_path(dir, port));
// The port was free, so no other run owns a file left here.
remove(created.as_deref());
let effective = ControlOptions { token_file: created.clone().or_else(|| options.token_file.clone()), ..options.clone() };
let token = match effective.server_token() {
let token = match token_for(&effective) {
Ok(t) => t,
Err(e) => {
remove(created.as_deref());
log::error!("control server off: {e}");
return None;
let msg = format!("control server off: {e}");
return Err(if matches!(&e, AutomationError::Io(text) if text.contains("did not finish within ")) {
StartError::TokenTimeout(msg)
} else {
StartError::Other(msg)
});
}
};
let notice = effective.token_notice(&token);
match serve(listener, token, host) {
Ok((rx, listening)) => {
log::info!("control server listening on {}, {notice}", listening.addr);
Some((rx, Control { listening, created }))
Ok((rx, Control { listening, created }))
}
Err(e) => {
remove(created.as_deref());
log::error!("control server off: cannot start the accept thread ({e})");
None
Err(StartError::Other(format!("control server off: cannot start the accept thread ({e})")))
}
}
}
@@ -87,6 +118,41 @@ mod tests {
WindowHost::of(&egui::Context::default())
}
/// Attempts for `start_with` when Windows `owner_only` hits its 10 s external-tool limit on
/// a busy CI runner (#8556). Non-timeout failures stop on the first attempt.
const TOKEN_TIMEOUT_ATTEMPTS: usize = 3;
fn try_start_retrying_token_timeout(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
mut token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
) -> Result<(Receiver<ControlRequest>, Control), (usize, StartError)> {
let mut attempt = 1;
loop {
match start_with(options, port, host.clone(), settings, &mut token_for) {
Ok(started) => return Ok(started),
Err(StartError::TokenTimeout(msg)) if attempt < TOKEN_TIMEOUT_ATTEMPTS => {
log::warn!("retrying control server start after Windows token-file timeout ({attempt}/{TOKEN_TIMEOUT_ATTEMPTS}): {msg}");
attempt += 1;
}
Err(err) => return Err((attempt, err)),
}
}
}
fn start_retrying_token_timeout(
options: &ControlOptions,
port: u16,
host: WindowHost,
settings: Option<&Path>,
token_for: impl FnMut(&ControlOptions) -> Result<String, AutomationError>,
) -> (Receiver<ControlRequest>, Control) {
try_start_retrying_token_timeout(options, port, host, settings, token_for)
.unwrap_or_else(|(attempt, err)| panic!("control server start failed on attempt {attempt}: {}", err.message()))
}
#[test]
fn the_token_file_is_written_after_the_bind_and_removed_on_exit() {
let dir = std::env::temp_dir().join(format!("wordcraft-control-life-{}", std::process::id()));
@@ -101,7 +167,7 @@ mod tests {
drop(taken);
// Bound: the default file holds the token that opens the port.
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
let path = control.created.clone().unwrap();
assert_eq!(path, wordcraft_control_key::key_path(&dir, 0));
let token = std::fs::read_to_string(&path).unwrap();
@@ -117,13 +183,61 @@ mod tests {
// A token file the user supplied stays.
let supplied = dir.join("supplied-token");
let options = ControlOptions { token_file: Some(supplied.clone()), ..ControlOptions::default() };
let (_rx, control) = start(&options, 0, host(), Some(&dir)).unwrap();
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), ControlOptions::server_token);
assert!(control.created.is_none());
control.shut_down();
assert!(supplied.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_transient_token_file_timeout_retries_while_other_errors_stop() {
let dir = std::env::temp_dir().join(format!("wordcraft-control-retry-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let options = ControlOptions::default();
// A Windows `owner_only` external-tool timeout retries and recovers on a later attempt.
let mut timeout_then_ok = 0usize;
let (_rx, control) = start_retrying_token_timeout(&options, 0, host(), Some(&dir), |effective| {
timeout_then_ok += 1;
if timeout_then_ok == 1 {
let path = effective.token_file.as_ref().unwrap();
Err(AutomationError::Io(format!(
"{}: cannot create the control token file for its owner only: powershell.exe did not finish within 10 s and was ended",
path.display()
)))
} else {
Ok(TOKEN.to_string())
}
});
assert_eq!(timeout_then_ok, 2);
control.shut_down();
// Repeated timeouts stop after `TOKEN_TIMEOUT_ATTEMPTS` instead of looping forever.
let mut exhausted = 0usize;
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
exhausted += 1;
Err(AutomationError::Io("powershell.exe did not finish within 10 s and was ended".into()))
}) else {
panic!("exhausted timeouts must fail");
};
assert_eq!((attempt, exhausted), (TOKEN_TIMEOUT_ATTEMPTS, TOKEN_TIMEOUT_ATTEMPTS));
assert!(matches!(err, StartError::TokenTimeout(_)));
// Non-timeout failures stop on the first attempt.
let mut other = 0usize;
let Err((attempt, err)) = try_start_retrying_token_timeout(&options, 0, host(), Some(&dir), |_| {
other += 1;
Err(AutomationError::Io("permission denied".into()))
}) else {
panic!("non-timeout error must fail");
};
assert_eq!((attempt, other), (1, 1));
assert!(matches!(err, StartError::Other(msg) if msg.contains("permission denied")));
let _ = std::fs::remove_dir_all(&dir);
}
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
fn boot() -> (u16, Receiver<ControlRequest>, Control) {
+195 -134
View File
@@ -152,6 +152,21 @@ impl eframe::App for App {
}
}
/// Files dropped on a document window. eframe hands `raw_input_hook` only the root's and deferred
/// viewports' input, and document windows are immediate viewports (every one under the windowless
/// root), so their drops come through this hook. It runs first and takes the batch, so nothing reads
/// it twice.
struct ChildDrops(IntakeSender);
impl eframe::ViewportHooks for ChildDrops {
fn raw_input(&self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
if raw.viewport_id != egui::ViewportId::ROOT && !raw.dropped_files.is_empty() {
self.0.dropped(dropped_files(raw));
raw.dropped_files.clear();
}
}
}
/// The files dropped in this frame's input, as the intake carries them: a file with a path by its
/// path, a file without one by its bytes.
fn dropped_files(raw: &egui::RawInput) -> Vec<DroppedFile> {
@@ -463,6 +478,46 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
Some(launch_profile::passthrough_args(early.passthrough_args, had_separator))
}
/// Runs the app with the windowless root when `windowless` is set, and with the visible root when it is not. eframe
/// refuses a windowless root on a session that cannot run it before it calls the creator, which then stays in its
/// cell for a retry with the visible root: the app always starts.
fn run_with_visible_root_fallback(
creator: eframe::AppCreator<'static>,
windowless: Arc<std::sync::atomic::AtomicBool>,
mut options: eframe::NativeOptions,
) -> eframe::Result {
use std::sync::atomic::Ordering::Relaxed;
let creator = std::rc::Rc::new(std::cell::RefCell::new(Some(creator)));
let name = wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity());
let run = |options: eframe::NativeOptions| {
let creator = creator.clone();
eframe::run_native(
name,
options,
Box::new(move |cc| match creator.borrow_mut().take() {
Some(create) => create(cc),
None => Err("the app was already created".into()),
}),
)
};
let on = windowless.load(Relaxed);
// The clone keeps no event-loop hook, which only the X11 start sets and that start is windowed.
let mut visible_root = on.then(|| options.clone());
if on {
options.root_viewport_mode = eframe::RootViewportMode::Windowless;
}
let result = run(options);
if let Err(eframe::Error::UnsupportedConfiguration(reason)) = &result
&& let Some(options) = visible_root.take()
&& creator.borrow().is_some()
{
log::warn!("windowless root unavailable ({reason}); starting with a visible root window");
windowless.store(false, Relaxed);
return run(options);
}
result
}
/// Parses the command line, installs logging and the panic hook, restores preferences and window
/// geometry, opens requested documents or the Start screen, starts the control server when
/// asked, and runs the eframe event loop.
@@ -676,6 +731,7 @@ fn main() -> eframe::Result {
// Registered before the event loop starts, so it catches the Finder event that launched us as
// well as later ones. Lives until the event loop returns.
let drops = intake.sender();
options.viewport_hooks = Some(Arc::new(ChildDrops(drops.clone())));
#[cfg(target_os = "macos")]
let _apple_events = craft::platform::open::apple_events::install(sender);
#[cfg(not(target_os = "macos"))]
@@ -705,147 +761,152 @@ fn main() -> eframe::Result {
let noticed_for_exit = unclean_notice_shown.clone();
let noticed_in_window = unclean_notice_shown.clone();
let exit_settings = settings.clone();
let result = eframe::run_native(
wordcraft_ui_egui::os_window::name_for(wordcraft_ui_egui::os_window::identity()),
options,
Box::new(move |cc| {
let ctx = cc.egui_ctx.clone();
let _ = repaint.set(ctx.clone());
let wake = {
let ctx = ctx.clone();
move || ctx.request_repaint()
};
// The interface language: the saved choice, else the system's.
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
let host = Arc::new(
Host::builder(wordcraft_ui_egui::APP)
.i18n(wordcraft_ui_egui::i18n::catalogs())
.files(Arc::new(file_service))
.settings(Arc::new(settings.clone()))
.lang(lang.craft_lang())
.build(),
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
// The system region picks the new document's paper, the units and the decimal
// separator (#838).
let region = region::system();
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(&region) };
let mut session = Session::new(doc);
session.system_region = region;
// The custom dictionary's words (#40) count as loaded settings.
if prefs::enabled()
&& let Some(path) = prefs::user_dict_path()
{
prefs::load_user_dictionary(&mut session, &settings, path);
// The root window is never shown (ADR 0001): eframe runs a windowless root and every document is a child
// window. X11, XWayland and BSD on X11 cannot, so they keep the visible root (the ADR's amendment). The mode
// is read by the app creator, which runs once the mode is settled.
let windowless = Arc::new(std::sync::atomic::AtomicBool::new(!x11));
let windowless_in_app = windowless.clone();
let creator: eframe::AppCreator<'static> = Box::new(move |cc| {
let ctx = cc.egui_ctx.clone();
let _ = repaint.set(ctx.clone());
let wake = {
let ctx = ctx.clone();
move || ctx.request_repaint()
};
// The interface language: the saved choice, else the system's.
let lang = wordcraft_ui_egui::i18n::Lang::from_pref(&settings.lock().get().language);
let (file_service, panels) = FileService::new(Wake::new(wake.clone()));
let host = Arc::new(
Host::builder(wordcraft_ui_egui::APP)
.i18n(wordcraft_ui_egui::i18n::catalogs())
.files(Arc::new(file_service))
.settings(Arc::new(settings.clone()))
.lang(lang.craft_lang())
.build(),
);
let shell = ShellInfo::current().backend(if x11 { Backend::X11 } else { Backend::from_env() });
let mut spec = InstallSpec::new(shell, Arc::new(SystemWindows))
.app_id(wordcraft_ui_egui::os_window::app_id())
.system(SystemReader::start(wake))
.clipboard(Clipboard::new(SystemClipboard::new().decoder(decode_png)))
.placement(placement);
// The runtime and eframe must agree on the root.
if windowless_in_app.load(std::sync::atomic::Ordering::Relaxed) {
spec = spec.windowless_root();
}
// PLAN: assumed `wordcraft_ui_egui::ui_fonts` re-exports sh.A10's `app::fonts::ui_fonts` (`mod app` is private; app-hub/shell-w11).
embed::install(&ctx, spec, &wordcraft_ui_egui::ui_fonts(lang)).map_err(|e| format!("the runtime could not be installed: {e}"))?;
// The system region picks the new document's paper, the units and the decimal
// separator (#838).
let region = region::system();
let doc = if sample { wordcraft_engine::sample::sample_document() } else { wordcraft_engine::blank_document(&region) };
let mut session = Session::new(doc);
session.system_region = region;
// The custom dictionary's words (#40) count as loaded settings.
if prefs::enabled()
&& let Some(path) = prefs::user_dict_path()
{
prefs::load_user_dictionary(&mut session, &settings, path);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
if let Some(state) = &cc.wgpu_render_state {
let info = state.adapter.get_info();
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
if software {
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
}
let spool = Spool::new(host.jobs_shared().clone());
let mut app = WordApp::new(session, services(spool.clone(), intake, nightly)).with_host(host).with_settings(settings.clone());
// Drawn by the processor (WARP, llvmpipe; #2221), animations that follow the system stop.
if let Some(state) = &cc.wgpu_render_state {
let info = state.adapter.get_info();
let software = info.device_type == eframe::wgpu::DeviceType::Cpu;
if software {
log::warn!("graphics: drawing in software on {} ({:?}): animations that follow the system are off", info.name, info.backend);
}
app.set_software_drawing(software);
app.set_software_drawing(software);
}
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
// PLAN: writer note 9 puts `with_settings` after `with_control`; it comes first here because
// the region check below reads the saved region the settings apply.
if std::env::var("WORDCRAFT_FILE_DIALOG").is_ok_and(|v| v.trim().eq_ignore_ascii_case("builtin")) {
app = app.with_fallback_chooser(true);
}
// Language packs from the suite's font store; an Install click is the person's own.
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
if nightly {
// The Launcher installs Nightly; Help › Check for Updates says so instead.
app.use_launcher_updates();
} else {
app.set_startup_update_check(true);
// After the preferences, so the reason it gives is in the interface language.
if updates_unsafe {
app.disable_self_update();
}
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
let doc = app.session.blank_document();
app.replace_startup_document(doc);
}
app.tell_about_font_downloads();
if prefs::enabled()
&& let Some(dir) = wordcraft_control_key::settings_dir()
{
let ctx = ctx.clone();
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
log::warn!("local recovery unavailable: {e}");
}
// Language packs from the suite's font store; an Install click is the person's own.
// Nightly keeps its own store in the profile, so a pack installed there is not a
// change to the stable apps' shared fonts.
match launch_profile::current().root() {
Some(root) => wordcraft_engine::packs::use_font_store_in(root.join("FontStore"), true),
None => {
wordcraft_engine::packs::use_font_store(true);
}
}
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) = control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
app = app.with_control(ControlChannel::new(rx));
control_server = Some(started);
}
// Nothing to open (no files, no sample, no control channel driving the editor): start
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
// the OS hands over later open on top of it and close it.
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
app.start_screen();
}
// A Word template named here starts a new document based on it (#3433).
for f in files {
if let Err(e) = app.open_from_platform(&f, None) {
app.report_open_failure(&f, &e);
}
// A region chosen in File › Options replaces the system's for the first blank
// document too (#838).
if !sample && app.session.prefs.region.is_some() {
let doc = app.session.blank_document();
app.replace_startup_document(doc);
}
app.tell_about_font_downloads();
if prefs::enabled()
&& let Some(dir) = wordcraft_control_key::settings_dir()
{
let ctx = ctx.clone();
if let Err(e) = app.session.enable_recovery(dir.join("recovery"), Arc::new(move || ctx.request_repaint())) {
log::warn!("local recovery unavailable: {e}");
}
}
let mut control_server = None;
if !nightly
&& let Some(port) = control.port
&& let Some((rx, started)) =
control_server::start(&control, port, WindowHost::of(&ctx), wordcraft_control_key::settings_dir().as_deref())
{
app = app.with_control(ControlChannel::new(rx));
control_server = Some(started);
}
// Nothing to open (no files, no sample, no control channel driving the editor): start
// on File › Home, as Word does (#766), unless the Start screen option is off. Files
// the OS hands over later open on top of it and close it.
if files.is_empty() && other_files.is_empty() && !sample && control.port.is_none() {
app.start_screen();
}
// A Word template named here starts a new document based on it (#3433).
for f in files {
if let Err(e) = app.open_from_platform(&f, None) {
app.report_open_failure(&f, &e);
}
}
for f in other_files {
open_non_unicode(&mut app, &f);
}
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
}
for f in other_files {
open_non_unicode(&mut app, &f);
}
// The personal agent files, the session record and the control token all live in the
// profile; the app's own services are built with the nightly rule in mind.
if let Some(warning) = &session_health_warning {
app.status_long(warning.clone());
}
if previous_nightly_unclean {
app.status_long(
"The previous WordCraft Nightly session did not finish normally. You can report a problem from Help › About. No diagnostics have been sent.",
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
#[cfg(target_os = "macos")]
native_menu: native_menu::install(&ctx, &app),
app,
panels,
drops,
settings,
spool,
control: control_server,
exit: Some(Box::new(move || {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
}),
);
noticed_in_window.store(true, std::sync::atomic::Ordering::Relaxed);
}
Ok(Box::new(App {
#[cfg(target_os = "macos")]
native_menu: native_menu::install(&ctx, &app),
app,
panels,
drops,
settings,
spool,
control: control_server,
exit: Some(Box::new(move || {
nightly_session::finish_once(&session_for_exit, noticed_for_exit.load(std::sync::atomic::Ordering::Relaxed));
})),
}))
});
let result = run_with_visible_root_fallback(creator, windowless, options);
// The exit hook has run; this is the no-op fallback for a start that created no window.
nightly_session::finish_once(&nightly_watch, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
// The app is dropped by now: whatever it saved on the way out is in the store.
+19 -2
View File
@@ -6,13 +6,22 @@ use wordcraft_ui_egui::{WordApp, i18n};
const APP_NAME: &str = "WordCraft";
const ABOUT: &str = "About WordCraft";
const QUIT: &str = "Quit WordCraft";
/// The application menu, with `tr` the translation of an English string.
pub(super) fn layout(tr: &dyn Fn(&'static str) -> String) -> Layout {
let about = Item::new(CommandRef::with_params("ui.dialog", json!({"name": "about"})), tr(ABOUT)).role(ItemRole::About);
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into()]).role(MenuRole::App)]);
// Without its own Quit `mac_layout` adds one whose click only closes the root window: it must ask about every document.
let quit = Item::new(CommandRef::new("ui.quit"), tr(QUIT)).role(ItemRole::Quit);
let bar = MenuBar::new(vec![Menu::new(APP_NAME, vec![about.into(), quit.into()]).role(MenuRole::App)]);
// `mac_layout` words About as the template; WordCraft's catalogs translate the whole label.
let label = |s: &'static str| tr(if s == "About {app}" { ABOUT } else { s });
let label = |s: &'static str| {
tr(match s {
"About {app}" => ABOUT,
"Quit {app}" => QUIT,
s => s,
})
};
let mut layout = mac_layout(&bar, &LayoutOptions::new(APP_NAME).label(&label));
// WordCraft's document menus live in its ribbon; keep only the application menu.
layout.bar.menus.retain(|menu| menu.role == MenuRole::App);
@@ -61,4 +70,12 @@ mod tests {
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
assert_eq!(about.label, "Über WordCraft");
}
/// ⌘Q and the menu's Quit run `ui.quit`, which asks about unsaved documents; craft's built-in Quit only closes the root window (#8709).
#[test]
fn quit_runs_the_command_that_asks_about_documents() {
let layout = layout(&|s| s.to_owned());
let quit = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::Quit)).unwrap();
assert_eq!(quit.command.id, "ui.quit");
}
}
+24 -1
View File
@@ -23,7 +23,8 @@ mod para_props;
mod table_props;
pub use char_props::{
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, Underline, VertAlign,
CharProps, CombineBrackets, DEFAULT_FONT_SIZE, EastAsianLayout, EmphasisMark, Highlight, Ligatures, NumChange, PropChange, ThemeFont, Underline,
VertAlign,
};
pub use color::{Rgb, TextColor};
pub use para_props::{
@@ -200,4 +201,26 @@ mod tests {
assert_eq!(changed.sym_font.as_deref(), Some("Wingdings"));
assert_eq!(p.cleared().sym_font.as_deref(), Some("Wingdings"));
}
#[test]
fn named_east_asian_font_replaces_theme_slot_and_minus_round_trips() {
let mut base = CharProps { font_ea: Some("Times New Roman".into()), font_ea_theme: Some(ThemeFont::MinorEastAsia), ..Default::default() };
let named = CharProps { font_ea: Some("SimSun".into()), ..Default::default() };
base.overlay(&named);
assert_eq!(base.font_ea.as_deref(), Some("SimSun"));
assert_eq!(base.font_ea_theme, None);
// Changing only `font_ea` while keeping `font_ea_theme` preserves the slot across minus/overlay.
let themed_base = CharProps { font_ea: Some("SimSun".into()), font_ea_theme: Some(ThemeFont::MinorEastAsia), ..Default::default() };
let run = CharProps { font_ea: Some("MS Mincho".into()), ..themed_base.clone() };
let mut back = themed_base.clone();
back.overlay(&run.clone().minus(&themed_base));
assert_eq!(back, run);
// Clearing `font_ea_theme` while keeping the same `font_ea` preserves `font_ea` in the patch.
let cleared_slot = CharProps { font_ea_theme: None, ..themed_base.clone() };
let mut back_cleared = themed_base.clone();
back_cleared.overlay(&cleared_slot.clone().minus(&themed_base));
assert_eq!(back_cleared, cleared_slot);
}
}
+76 -2
View File
@@ -329,6 +329,10 @@ pub struct CharProps {
/// inherit, then `font`.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea: Option<String>,
/// The theme font slot of the East Asian font (`w:rFonts/@w:eastAsiaTheme`: `minorEastAsia`,
/// `majorEastAsia`…), taking precedence over `font_ea` when set.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea_theme: Option<ThemeFont>,
/// Complex-script size, points (`w:szCs`). `None` leaves the inherited value unchanged.
#[serde(skip_serializing_if = "Option::is_none")]
pub size_cs: Option<f32>,
@@ -450,6 +454,62 @@ impl CombineBrackets {
}
}
/// A theme font slot in `w:rFonts` (`ST_Theme`, ECMA-376 §17.18.96).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ThemeFont {
MajorEastAsia,
MajorBidi,
MajorAscii,
MajorHAnsi,
MinorEastAsia,
MinorBidi,
MinorAscii,
MinorHAnsi,
}
impl ThemeFont {
const ALL: [ThemeFont; 8] = [
ThemeFont::MajorEastAsia,
ThemeFont::MajorBidi,
ThemeFont::MajorAscii,
ThemeFont::MajorHAnsi,
ThemeFont::MinorEastAsia,
ThemeFont::MinorBidi,
ThemeFont::MinorAscii,
ThemeFont::MinorHAnsi,
];
/// The OOXML `ST_Theme` value.
pub fn as_str(self) -> &'static str {
match self {
ThemeFont::MajorEastAsia => "majorEastAsia",
ThemeFont::MajorBidi => "majorBidi",
ThemeFont::MajorAscii => "majorAscii",
ThemeFont::MajorHAnsi => "majorHAnsi",
ThemeFont::MinorEastAsia => "minorEastAsia",
ThemeFont::MinorBidi => "minorBidi",
ThemeFont::MinorAscii => "minorAscii",
ThemeFont::MinorHAnsi => "minorHAnsi",
}
}
/// Parse an OOXML `ST_Theme` value (`None` for any value outside the schema).
pub fn parse(s: &str) -> Option<ThemeFont> {
ThemeFont::ALL.into_iter().find(|t| t.as_str() == s)
}
/// Whether this slot picks the theme's major (heading) font rather than minor (body).
pub fn is_major(self) -> bool {
matches!(self, ThemeFont::MajorEastAsia | ThemeFont::MajorBidi | ThemeFont::MajorAscii | ThemeFont::MajorHAnsi)
}
/// Whether this is one of the Latin theme slots (`ascii` / `hAnsi`).
pub fn is_latin(self) -> bool {
matches!(self, ThemeFont::MajorAscii | ThemeFont::MajorHAnsi | ThemeFont::MinorAscii | ThemeFont::MinorHAnsi)
}
}
/// A tracked formatting change (ECMA-376 §17.13.5: `w:rPrChange`, `w:pPrChange`,
/// `w:tblPrChange`, `w:trPrChange`, `w:tcPrChange`, `w:sectPrChange`): the properties as they
/// were before the change, and the revision (author, date) that made it.
@@ -509,7 +569,16 @@ impl CharProps {
}
fn minus_script_style(&mut self, base: &CharProps) {
drop_same_fields!(self, base; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
// A theme slot stays while its named font does; a same font stays when its slot differs.
let keep = self.font_ea_theme;
let ea = self.font_ea.clone();
drop_same_fields!(self, base; cs, font_cs, font_ea, font_ea_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
if self.font_ea.is_none() && keep != base.font_ea_theme {
self.font_ea = ea;
}
if self.font_ea.is_some() {
self.font_ea_theme = keep;
}
}
fn minus_document_marks(&mut self, base: &CharProps) {
@@ -540,7 +609,12 @@ impl CharProps {
}
fn overlay_script_style(&mut self, patch: &CharProps) {
overlay_fields!(self, patch; cs, font_cs, font_ea, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
// A named East Asian font without a theme slot replaces the slot too: Word gives the slot
// precedence over the named font, so keeping it would hide the font just chosen.
if patch.font_ea.is_some() && patch.font_ea_theme.is_none() {
self.font_ea_theme = None;
}
overlay_fields!(self, patch; cs, font_cs, font_ea, font_ea_theme, size_cs, bold_cs, italic_cs, lang_bidi, lang_ea, east_asian_layout);
}
fn overlay_document_marks(&mut self, patch: &CharProps) {
+6 -1
View File
@@ -4,7 +4,7 @@
use serde::{Deserialize, Serialize};
use crate::props::{
Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, Underline, VertAlign,
Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, ThemeFont, Underline, VertAlign,
};
use crate::styles::{StyleKind, StyleSheet};
@@ -71,6 +71,10 @@ pub struct ResolvedChar {
/// East Asian font (Chinese, Japanese and Korean text), when one is set.
#[serde(skip_serializing_if = "Option::is_none")]
pub font_ea: Option<String>,
/// Theme font slot for the East Asian font (`w:eastAsiaTheme`), taking precedence over
/// `font_ea` when set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub font_ea_theme: Option<ThemeFont>,
pub size_cs: f32,
pub bold_cs: bool,
pub italic_cs: bool,
@@ -117,6 +121,7 @@ impl ResolvedChar {
cs: c.cs.unwrap_or(false),
font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()),
font_ea: c.font_ea.clone(),
font_ea_theme: c.font_ea_theme,
size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0),
// A run marked complex script (`w:cs`) is bold and italic only by `w:bCs` and `w:iCs`:
// Word draws Thai with `<w:b/><w:cs/>` and no `w:bCs` upright and plain (measured in
+36 -16
View File
@@ -1330,6 +1330,8 @@ fn hinted_east_asian_or_cs_font_does_not_replace_the_latin_font() {
assert_eq!((ea.font.as_str(), ea.font_ea.as_deref()), ("Times New Roman", Some("宋体")));
let cs = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[1].props);
assert_eq!((cs.font.as_str(), cs.font_cs.as_str()), ("Times New Roman", "Arial"));
assert_eq!(ea.font_ea_theme, None, "named w:eastAsia replaces Heading2's w:eastAsiaTheme");
assert_eq!(cs.font_ea_theme, Some(wordcraft_doc::props::ThemeFont::MajorEastAsia));
}
#[test]
@@ -2444,33 +2446,51 @@ fn note_separators_and_continuation_notice_round_trip() {
check(&wordcraft_docx::read(&out).unwrap());
}
/// A picture frame shape in a footnote or endnote separator opens as the same shape kind as it does
/// in the body, instead of failing the whole document. (The test name dates from when the body
/// opened this shape as a rectangle.)
/// A hyperlinked nested group in a footnote or endnote separator is flattened through the block
/// mapping just as it is in the document body.
#[test]
fn a_frame_shape_in_a_note_separator_reads_as_a_rectangle() {
let frame = r#"<w:r><w:drawing><wp:inline><wp:extent cx="508000" cy="381000"/><wp:docPr id="1" name="F"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#;
fn linked_nested_group_in_a_note_separator_is_flattened() {
let inner = r#"<wpg:grpSp><wpg:cNvPr id="3" name="Inner"><a:hlinkClick r:id="rId9"/></wpg:cNvPr><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="635000" y="0"/><a:ext cx="635000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="635000" cy="635000"/></a:xfrm></wpg:grpSpPr><wps:wsp><wps:cNvPr id="4" name="Frame"/><wps:cNvSpPr/><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="635000"/></a:xfrm><a:prstGeom prst="frame"/></wps:spPr><wps:bodyPr/></wps:wsp></wpg:grpSp>"#;
let group = format!(
r#"<w:r><w:drawing><wp:inline><wp:extent cx="1270000" cy="635000"/><wp:docPr id="1" name="Outer"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup"><wpg:wgp><wpg:cNvGrpSpPr/><wpg:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="1270000" cy="635000"/><a:chOff x="0" y="0"/><a:chExt cx="1270000" cy="635000"/></a:xfrm></wpg:grpSpPr>{inner}</wpg:wgp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>"#
);
let notes = |root: &str, item: &str| {
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{frame}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
format!(r#"<w:{root} {W_NS}><w:{item} w:type="separator" w:id="-1"><w:p>{group}<w:r><w:separator/></w:r></w:p></w:{item}></w:{root}>"#)
};
let footnotes = notes("footnotes", "footnote");
let endnotes = notes("endnotes", "endnote");
let link_rels = rels(&[("rId9", "hyperlink", "https://example.com/")]);
let bytes = docx(
&format!("<w:p>{frame}</w:p>"),
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml")],
&[("word/footnotes.xml", &footnotes), ("word/endnotes.xml", &endnotes)],
&format!("<w:p>{group}</w:p>"),
&[("rId1", "footnotes", "footnotes.xml"), ("rId2", "endnotes", "endnotes.xml"), ("rId9", "hyperlink", "https://example.com/")],
&[
("word/footnotes.xml", &footnotes),
("word/_rels/footnotes.xml.rels", &link_rels),
("word/endnotes.xml", &endnotes),
("word/_rels/endnotes.xml.rels", &link_rels),
],
);
let d = wordcraft_docx::read(&bytes).unwrap();
let shapes = |p: &Paragraph| -> Vec<(ShapeKind, f32)> {
p.objects.iter().filter_map(|o| if let InlineObject::Shape { kind, w, .. } = o { Some((*kind, *w)) } else { None }).collect()
let flattened = |p: &Paragraph| -> Vec<(f32, f32, ShapeKind, f32)> {
let Some(children) = p.objects.iter().find_map(|o| match o {
InlineObject::Group { children, .. } => Some(children),
_ => None,
}) else {
panic!("{:?}", p.objects);
};
children
.iter()
.map(|c| match &c.obj {
InlineObject::Shape { kind, w, .. } => (c.x, c.y, *kind, *w),
other => panic!("{other:?}"),
})
.collect()
};
let in_body = shapes(d.body[0].as_para().unwrap());
assert_eq!(in_body.len(), 1, "{in_body:?}");
assert_eq!(in_body[0].1, 40.0);
assert_eq!(in_body[0].0, ShapeKind::Frame);
let in_body = flattened(d.body[0].as_para().unwrap());
assert_eq!(in_body, [(50.0, 0.0, ShapeKind::Frame, 50.0)]);
for separators in [&d.footnote_separators, &d.endnote_separators] {
let sep = separators.separator.as_ref().unwrap()[0].as_para().unwrap();
assert_eq!(shapes(sep), in_body);
assert_eq!(flattened(sep), in_body);
}
}
+1
View File
@@ -132,6 +132,7 @@ fn every_char_prop_round_trips() {
cs: Some(true),
font_cs: Some("B Nazanin".into()),
font_ea: Some("宋体".into()),
font_ea_theme: Some(wordcraft_doc::props::ThemeFont::MinorEastAsia),
size_cs: Some(13.0),
bold_cs: Some(false),
italic_cs: Some(true),
+68 -37
View File
@@ -3,7 +3,7 @@
use serde_json::Value;
use wordcraft_doc::math_edit::MathPos;
use wordcraft_doc::para::OBJ;
use wordcraft_doc::{InlineObject, Pos, StoryRef};
use wordcraft_doc::{InlineObject, Paragraph, Pos, StoryRef};
use wordcraft_layout::ViewMode;
use super::{parse_pos, sel_result};
@@ -110,7 +110,8 @@ fn bidi_para(s: &Session) -> bool {
/// Left/Right: with a selection and no Shift, collapse to its edge.
fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if !extend(v) && !s.sel.is_collapsed() {
let ext = extend(v);
if !ext && !s.sel.is_collapsed() {
let (a, b) = s.sel.ordered();
// The left edge of a selection in right-to-left text is its logical end.
let to_start = is_left != rtl_para(s);
@@ -121,26 +122,32 @@ fn lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
if bidi_para(s) {
return visual_lr(s, v, is_left);
}
if !extend(v)
let from = s.sel.focus.clone();
// Equation entry and the grapheme step start at the same visible edge.
let edge = logical_edge(s, &from, is_left);
if !ext
&& !s.math_left
&& let Some(r) = into_equation(s, is_left)
&& let Some(r) = into_equation(s, &from, edge, is_left)
{
return r;
}
mv(s, v, if is_left { left } else { right })
s.goal_x = None;
let to = step_from_edge(s, &from, edge, is_left);
apply(s, to, ext);
sel_result(s)
}
/// Left/Right onto an equation opens it, at its end from the right and at its start from the
/// left, as in Word (#4138). Leaving it puts the caret on the far side, so the same arrow then
/// moves on instead of going back in. A caret.left/right that itself left an equation (sent
/// while editing one) moves on too.
fn into_equation(s: &mut Session, is_left: bool) -> Option<CmdResult> {
let f = s.sel.focus.clone();
let off = if is_left { f.off.checked_sub(OBJ.len_utf8())? } else { f.off };
if !matches!(s.doc.para_at(&f)?.object_at(off), Some(InlineObject::Equation { .. })) {
fn into_equation(s: &mut Session, from: &Pos, edge: usize, is_left: bool) -> Option<CmdResult> {
let off = if is_left { edge.checked_sub(OBJ.len_utf8())? } else { edge };
let para = s.doc.para_at(from)?;
if !matches!(para.object_at(off), Some(InlineObject::Equation { .. })) || (!s.view.show_markup && para.props_of_char(off).del.is_some()) {
return None;
}
s.sel = Selection::caret(Pos { off, ..f });
s.sel = Selection::caret(Pos { off, ..from.clone() });
s.goal_x = None;
s.pending = None;
Some(super::equation::edit_at(s, (!is_left).then(MathPos::default)))
@@ -159,62 +166,86 @@ fn visual_lr(s: &mut Session, v: &Value, is_left: bool) -> CmdResult {
Some(wordcraft_layout::VisualStep::Edge { start, stop, last_line, rtl }) => {
let at = |off| Pos { off, ..from.clone() };
if is_left != rtl {
match s.doc.para_at(&from) {
Some(para) if start > 0 => at(para.prev_boundary(start)),
_ => left(s, &at(0)),
}
logical_step(s, &at(start), true)
} else if !last_line {
at(stop)
} else {
let len = s.doc.para_at(&from).map_or(stop, |p| p.len());
right(s, &at(len))
logical_step(s, &at(len), false)
}
}
None if is_left => left(s, &from),
None => right(s, &from),
None => logical_step(s, &from, is_left),
};
apply(s, to, ext);
sel_result(s)
}
fn left(s: &mut Session, p: &Pos) -> Pos {
if let Some(para) = s.doc.para_at(p)
&& p.off > 0
{
return Pos { off: para.prev_boundary(p.off), ..p.clone() };
/// The two ends of a hidden deletion share a caret position. Cross the hidden
/// span before taking the normal grapheme step, including adjacent deletions.
fn hidden_deletion_edge(para: &Paragraph, off: usize, is_left: bool) -> usize {
// At a run boundary, inspect the byte on the side the caret is moving toward.
let Some(byte) = off.checked_sub(usize::from(is_left)).filter(|&byte| byte < para.len()) else { return off };
// Runs store lengths, so find the containing run from the nearer end of the paragraph.
let found = if byte < para.len() / 2 {
para.run_ranges().enumerate().find_map(|(i, (range, _))| range.contains(&byte).then_some((i, range)))
} else {
let mut end = para.len();
para.runs.iter().enumerate().rev().find_map(|(i, run)| {
let range = end - run.len..end;
end = range.start;
range.contains(&byte).then_some((i, range))
})
};
let Some((i, range)) = found else { return off };
if para.runs[i].props.del.is_none() {
return off;
}
match s.doc.prev_para(p.story, &p.path) {
Some(q) => {
let off = s.doc.para(p.story, &q).map(|x| x.len()).unwrap_or(0);
Pos { story: p.story, path: q, off }
}
None => p.clone(),
if is_left {
range.start - para.runs[..i].iter().rev().take_while(|run| run.props.del.is_some()).map(|run| run.len).sum::<usize>()
} else {
range.end + para.runs[i + 1..].iter().take_while(|run| run.props.del.is_some()).map(|run| run.len).sum::<usize>()
}
}
fn right(s: &mut Session, p: &Pos) -> Pos {
if let Some(para) = s.doc.para_at(p)
&& p.off < para.len()
fn logical_edge(s: &Session, from: &Pos, is_left: bool) -> usize {
if !s.view.show_markup
&& let Some(para) = s.doc.para_at(from)
{
return Pos { off: para.next_boundary(p.off), ..p.clone() };
return hidden_deletion_edge(para, from.off, is_left);
}
match s.doc.next_para(p.story, &p.path) {
Some(q) => Pos { story: p.story, path: q, off: 0 },
None => p.clone(),
from.off
}
fn logical_step(s: &Session, from: &Pos, is_left: bool) -> Pos {
step_from_edge(s, from, logical_edge(s, from, is_left), is_left)
}
fn step_from_edge(s: &Session, from: &Pos, edge: usize, is_left: bool) -> Pos {
if let Some(para) = s.doc.para_at(from) {
if is_left && edge > 0 {
return Pos { off: para.prev_boundary(edge), ..from.clone() };
}
if !is_left && edge < para.len() {
return Pos { off: para.next_boundary(edge), ..from.clone() };
}
}
let neighbor = if is_left { s.doc.prev_para(from.story, &from.path) } else { s.doc.next_para(from.story, &from.path) };
let Some(path) = neighbor else { return from.clone() };
let off = if is_left { s.doc.para(from.story, &path).map_or(0, Paragraph::len) } else { 0 };
Pos { story: from.story, path, off }
}
fn word_left(s: &mut Session, p: &Pos) -> Pos {
match s.doc.para_at(p) {
Some(para) if p.off > 0 => Pos { off: para.word_start(p.off), ..p.clone() },
_ => left(s, p),
_ => logical_step(s, p, true),
}
}
fn word_right(s: &mut Session, p: &Pos) -> Pos {
match s.doc.para_at(p) {
Some(para) if p.off < para.len() => Pos { off: para.word_end(p.off), ..p.clone() },
_ => right(s, p),
_ => logical_step(s, p, false),
}
}
+1 -1
View File
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
sel_result(s)
})
.key("Mod+W / Mod+F4")
.params(r#"{"force"?: bool (desktop app's control channel and MCP bridge only: without it a document with unsaved changes is an error and stays open; with it the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
.params(r#"{"save"?: bool (desktop app's control channel and MCP bridge only: save the shown document, then close it; it does not apply to a background `doc`, which needs force or its own save first), "force"?: bool (desktop app's control channel and MCP bridge only: without save or force a document with unsaved changes is an error and stays open; with force the changes are discarded. Headless sessions never ask; file.closeDocument closes a document there)}"#)
.pure(),
CommandSpec::new("file.closeDocument", "Close Document", "Agents", close_document)
.params(r#"{"id"?: n (an open document, see view.switchWindows; default the active one), "force"?: bool (discard unsaved changes; without it a document with unsaved changes is an error and stays open)} → {"closed": id, "active": id, "documents": [{"id", "title", "path", "dirty", "active"}]}; closing the last document leaves a new blank one"#)
+7 -3
View File
@@ -352,11 +352,14 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
out
}
/// Whether a toggle without a `value` turns its format on. A selection follows its first character
/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516).
/// Whether a toggle without a `value` turns its format on. A selection (including a selected
/// text box or a non-empty column block, whose `sel` is non-collapsed) follows its first
/// character in document order, as Word does: one that starts formatted loses the format, all of
/// it (#6516). A collapsed caret (including an empty column block) requires the whole word to
/// carry the format before toggling it off.
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
let chars = resolved(s);
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
if !s.sel.is_collapsed() {
return !chars.first().is_some_and(has);
}
!chars.iter().all(has)
@@ -424,6 +427,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
}
if let Some(n) = &ea {
c.font_ea = Some(n.clone());
c.font_ea_theme = None;
}
})
}
+25
View File
@@ -908,4 +908,29 @@ mod tests {
let spec = s.registry.get(TEXT).unwrap();
assert!(spec.mutates, "view.markdownSourceText mutates session and dirty state");
}
/// Verifies entering and applying Markdown Source keep the document intact and report errors
/// when Markdown conversion fails.
#[test]
fn failed_markdown_conversion_keeps_document_and_reports_error() {
let mut s = session(SAMPLE);
s.md_file = FileText::default();
let err = wordcraft_formats::with_shared_conversion_error("bridge failed", || s.run(TOGGLE, &json!({}))).unwrap_err();
assert!(err.to_string().contains("bridge failed"), "{err}");
assert!(s.md_source.is_none());
for skip in [1, 2] {
let err = wordcraft_formats::with_shared_conversion_error_after(skip, "bridge failed", || s.run(TOGGLE, &json!({}))).unwrap_err();
assert!(err.to_string().contains("bridge failed"), "skip={skip}: {err}");
assert!(s.md_source.is_none());
}
let mut s = session(SAMPLE);
s.run(TOGGLE, &json!({})).unwrap();
let before = body_text(&s);
set_text(&mut s, "# Replaced\n");
wordcraft_formats::with_shared_conversion_error("bridge failed", || apply(&mut s));
assert_eq!(body_text(&s), before, "failed apply leaves the document intact");
assert!(s.status.contains("bridge failed"), "{}", s.status);
}
}
+7 -1
View File
@@ -54,7 +54,13 @@ type Reset = (fn(&CharProps) -> bool, fn(&mut CharProps));
const RESETS: [Reset; 24] = [
(|c| c.font.is_some(), |c| c.font = None),
(|c| c.font_cs.is_some(), |c| c.font_cs = None),
(|c| c.font_ea.is_some(), |c| c.font_ea = None),
(
|c| c.font_ea.is_some() || c.font_ea_theme.is_some(),
|c| {
c.font_ea = None;
c.font_ea_theme = None;
},
),
(|c| c.size.is_some(), |c| c.size = None),
(|c| c.size_cs.is_some(), |c| c.size_cs = None),
(|c| c.color.is_some(), |c| c.color = None),
+90
View File
@@ -697,6 +697,96 @@ fn a_toc_replaced_right_before_a_table_still_lands_the_caret_in_a_paragraph() {
assert!(matches!(&*s.doc.body[new_end + 1], Block::Para(_)));
}
/// Inserting a table of contents in the middle of a document places the caret in the paragraph
/// right after the table and leaves the text above and below it unchanged.
#[test]
fn a_toc_inserted_in_the_middle_of_a_document_leaves_the_caret_after_it() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Intro\nAfter TOC\nChapter One\nBody below."));
s.run("select.text", &json!({"text": "Chapter One"})).unwrap();
s.run("styles.apply", &json!({"style": "Heading 1"})).unwrap();
s.sel = Selection::caret(Pos { story: StoryRef::Body, path: Path::top(1), off: 0 });
s.run("references.toc", &json!({"levels": 2})).unwrap();
let (start, end) = toc_range(&s).unwrap();
assert!(start > 0, "the TOC is inserted after the intro paragraph");
assert_eq!(s.doc.body[0].as_para().map(|p| p.plain_text()).as_deref(), Some("Intro"));
assert_eq!(
s.sel.focus,
Pos { story: StoryRef::Body, path: Path::top(end + 1), off: 0 },
"the caret must land in the paragraph right after the TOC"
);
let below: Vec<String> = s.doc.body[end + 1..].iter().filter_map(|b| b.as_para()).map(|p| p.plain_text()).collect();
assert_eq!(below, ["After TOC", "Chapter One", "Body below."]);
}
/// One undo removes both the table of contents and the empty paragraph `caret_after_toc` adds
/// when the table ends the document or comes right before a table, leaving no stray blank
/// paragraph behind.
#[test]
fn undoing_a_toc_removes_both_the_table_and_the_added_paragraph() {
let toc_instr = |s: &Session, i: usize| {
s.doc.body[i].as_para().and_then(|p| {
p.objects.iter().find_map(|o| match o {
InlineObject::Field { instr, .. } => Some(instr.clone()),
_ => None,
})
})
};
// Fresh insert on an empty document undoes in one step.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
assert!(toc_range(&s).is_some());
assert_eq!(s.undo_depth(), 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), 0);
assert!(toc_range(&s).is_none());
assert_eq!(s.doc.body.len(), 1);
assert_eq!(s.doc.plain_text(StoryRef::Body), "");
// Table ending the document: `caret_after_toc` appends an empty paragraph, and one undo
// removes both the replaced table and that added paragraph.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
let (start, end) = toc_range(&s).unwrap();
while s.doc.body.len() > end + 1 {
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
}
let before_blocks = s.doc.body.len();
let depth = s.undo_depth();
s.run("references.toc", &json!({"levels": 3})).unwrap();
let (_, new_end) = toc_range(&s).unwrap();
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
assert_eq!(s.doc.body.len(), before_blocks + 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), depth);
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added trailing paragraph");
assert_eq!(toc_range(&s), Some((start, end)));
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
// Table right before another table: `caret_after_toc` inserts an empty paragraph before the
// table, and one undo removes both the replaced TOC and that added paragraph.
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("references.toc", &json!({"levels": 2})).unwrap();
s.run("insert.table", &json!({"rows": 1, "cols": 1})).unwrap();
let (start, end) = toc_range(&s).unwrap();
while s.doc.body.get(end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())) {
s.doc.remove_block(StoryRef::Body, &Path::top(end + 1)).unwrap();
}
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
let before_blocks = s.doc.body.len();
let depth = s.undo_depth();
s.run("references.toc", &json!({"levels": 3})).unwrap();
let (_, new_end) = toc_range(&s).unwrap();
assert!(s.doc.body.get(new_end + 1).is_some_and(|b| b.as_para().is_some_and(|p| p.is_empty())));
assert_eq!(s.doc.body.len(), before_blocks + 1);
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(s.undo_depth(), depth);
assert_eq!(s.doc.body.len(), before_blocks, "undo must remove the added paragraph before the table");
assert_eq!(toc_range(&s), Some((start, end)));
assert!(matches!(&*s.doc.body[end + 1], Block::Table(_)));
assert!(toc_instr(&s, start).as_deref().is_some_and(|i| i.contains(r#"\o "1-2""#)));
}
/// A fresh scratch directory for the file-name tests below.
#[cfg(not(target_arch = "wasm32"))]
fn filename_scratch_dir(tag: &str) -> std::path::PathBuf {
+8 -2
View File
@@ -270,8 +270,14 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let trailing = is_last && s.doc.para(st, &path).is_some_and(|p| (p.mark.del.is_some() && accept) || (p.mark.ins.is_some() && !accept));
let len = s.doc.para(st, &path).map(|p| p.len()).unwrap_or(0);
resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing {
remove_trailing_para(s, st, &path)?;
if trailing && remove_trailing_para(s, st, &path)? {
// Selection ends in the removed paragraph go to the end of the one before it;
// clamping later would keep their offsets in that paragraph's text (#8500).
for end in [&mut s.sel.anchor, &mut s.sel.focus] {
if end.story == st && end.path == path {
*end = s.doc.clamp(&Pos { off: usize::MAX, ..end.clone() });
}
}
}
}
}
+50 -86
View File
@@ -16,72 +16,6 @@ fn empty_paras(s: &Session) -> usize {
s.doc.body.iter().filter(|b| matches!(b.as_para(), Some(p) if p.is_empty())).count()
}
#[test]
fn compare_marks_a_whole_paragraph_and_its_mark() {
// A whole inserted paragraph carries the insertion on its mark, not just on its runs.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().unwrap();
assert_eq!(mid.plain_text(), "NEW");
assert!(mid.mark.ins.is_some(), "the inserted paragraph's mark is not marked inserted");
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting an inserted paragraph left an empty paragraph behind");
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nNEW\nB");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0, "accepting an inserted paragraph left an empty paragraph behind");
// A whole deleted paragraph carries the deletion on its mark.
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().unwrap();
assert_eq!(mid.plain_text(), "OLD");
assert!(mid.mark.del.is_some(), "the deleted paragraph's mark is not marked deleted");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting a deleted paragraph left an empty paragraph behind");
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nOLD\nB");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
}
#[test]
fn compare_marks_an_empty_paragraphs_mark() {
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\n\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let empty = s.doc.body[1].as_para().unwrap();
assert!(empty.is_empty());
assert!(empty.mark.ins.is_some(), "the empty inserted paragraph's mark is not marked inserted");
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting an empty inserted paragraph left it behind");
// An empty deleted paragraph is stamped on its mark too.
let mut s = Session::new(Document::from_text("A\n\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let empty = s.doc.body[1].as_para().unwrap();
assert!(empty.is_empty());
assert!(empty.mark.del.is_some(), "the empty deleted paragraph's mark is not marked deleted");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting an empty deleted paragraph left it behind");
}
#[test]
fn compare_keeps_another_authors_deletion_stamp() {
// A paragraph the original already carries as a tracked deletion by another author: Compare
@@ -130,6 +64,24 @@ fn compare_terminal_deleted_paragraph_resolves_fully() {
assert_eq!(empty_paras(&s), 0, "accepting a terminal deleted paragraph left an empty paragraph behind");
}
#[test]
fn resolving_a_selected_terminal_paragraph_puts_the_caret_before_it() {
// A selection inside the terminal paragraph that Reject All (insertion) or Accept All
// (deletion) removes ends as a caret at the end of the paragraph before it, not over the
// same offsets of that paragraph's text (#8500).
let cases = [("A\nKeep this", "A\nKeep this\nNEW", "review.rejectAll"), ("A\nKeep this\nOLD", "A\nKeep this", "review.acceptAll")];
for (orig, revised, cmd) in cases {
let mut s = Session::new(Document::from_text(orig));
s.run("review.compare", &json!({"text": revised})).unwrap();
s.sel = Selection { anchor: Pos::body(2, 0), focus: Pos::body(2, 3) };
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep this", "{cmd}");
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}");
s.run("text.insert", &json!({"text": "Z"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}");
}
}
#[test]
fn reject_all_keeps_an_empty_inserted_paragraph_between_tables() {
// An empty paragraph between two tables is not the container's last block: removing it
@@ -220,16 +172,8 @@ fn compare_pins_accepting_a_deleted_section_keeps_the_next_paragraphs_style() {
}
#[test]
fn compare_marks_the_last_paragraphs_mark() {
// Inserted last paragraph: rejecting removes it whole.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.ins.is_some());
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
fn compare_keeps_terminal_paragraph_when_insertion_accepted_or_deletion_rejected() {
// Inserted last paragraph: accepting keeps it whole.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nB\nNEW"})).unwrap();
s.run("review.acceptAll", &json!({})).unwrap();
@@ -237,15 +181,7 @@ fn compare_marks_the_last_paragraphs_mark() {
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0);
// Deleted last paragraph: accepting removes it whole.
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
assert!(s.doc.body[2].as_para().unwrap().mark.del.is_some());
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0);
// Deleted last paragraph: rejecting keeps it whole.
let mut s = Session::new(Document::from_text("A\nB\nOLD"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
s.run("review.rejectAll", &json!({})).unwrap();
@@ -1744,7 +1680,8 @@ fn compare_lcs_window_move_past_cap_does_not_cascade_false_revisions() {
}
/// Verifies that `mark_block` records paragraph mark revisions on whole-block deletions,
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`.
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`
/// and `review.rejectAll`.
#[test]
fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes() {
// Whole block delete/insert: test with differing paragraph count so whole-block paths trigger
@@ -1762,17 +1699,34 @@ fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes()
assert!(del_para.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
assert_eq!(del_para.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
let mut s2_rej = Session::new(s2.doc.clone());
s2_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s2_rej.doc.plain_text(StoryRef::Body), orig_multi);
assert_eq!(s2_rej.doc.body.len(), 3);
assert_eq!(empty_paras(&s2_rej), 0, "rejecting a deleted paragraph left an empty paragraph behind");
// Accept all changes: deleted paragraph is removed
s2.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s2.doc.plain_text(StoryRef::Body), rev_multi);
assert_eq!(s2.doc.body.len(), 2);
assert_eq!(empty_paras(&s2), 0, "accepting a deleted paragraph left an empty paragraph behind");
// Test whole-block insertion
let mut s3 = Session::new(Document::from_text(rev_multi));
s3.run("review.compare", &json!({"text": orig_multi})).unwrap();
let ins_para = s3.doc.body[1].as_para().expect("block 1 must be paragraph");
assert!(ins_para.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
let mut s3_rej = Session::new(s3.doc.clone());
s3_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s3_rej.doc.plain_text(StoryRef::Body), rev_multi);
assert_eq!(s3_rej.doc.body.len(), 2);
assert_eq!(empty_paras(&s3_rej), 0, "rejecting an inserted paragraph left an empty paragraph behind");
s3.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s3.doc.plain_text(StoryRef::Body), orig_multi);
assert_eq!(s3.doc.body.len(), 3);
assert_eq!(empty_paras(&s3), 0, "accepting an inserted paragraph left an empty paragraph behind");
// Test empty paragraph deletion and insertion (len == 0, where only mark carries the revision)
let orig_empty = "Before.\n\nAfter.";
@@ -1784,14 +1738,24 @@ fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes()
assert!(empty_del.mark.del.is_some(), "empty paragraph deletion must set mark.del");
s4.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s4.doc.plain_text(StoryRef::Body), rev_empty);
assert_eq!(s4.doc.body.len(), 2);
assert_eq!(empty_paras(&s4), 0, "accepting an empty deleted paragraph left it behind");
let mut s5 = Session::new(Document::from_text(rev_empty));
s5.run("review.compare", &json!({"text": orig_empty})).unwrap();
let empty_ins = s5.doc.body[1].as_para().expect("empty paragraph block");
assert_eq!(empty_ins.len(), 0);
assert!(empty_ins.mark.ins.is_some(), "empty paragraph insertion must set mark.ins");
let mut s5_rej = Session::new(s5.doc.clone());
s5_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s5_rej.doc.plain_text(StoryRef::Body), rev_empty);
assert_eq!(s5_rej.doc.body.len(), 2);
assert_eq!(empty_paras(&s5_rej), 0, "rejecting an empty inserted paragraph left it behind");
s5.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s5.doc.plain_text(StoryRef::Body), orig_empty);
assert_eq!(s5.doc.body.len(), 3);
}
#[test]
-38
View File
@@ -52,15 +52,6 @@ pub fn specs() -> Vec<CommandSpec> {
}
Ok(json!({"paperColor": color}))
}).params(r#"{"value": "document" | "green" | "cream" | "gray"}"#).pure(),
// How the edges of page text are smoothed on screen. Screen only; never in the document.
CommandSpec::new("view.textSmoothing", "Screen Text Smoothing", "View › Display", |s, v| {
let smoothing: TextSmoothing = serde_json::from_value(v.get("value").cloned().unwrap_or(Value::Null))
.map_err(|_| CmdError::Params("screen text smoothing must be system, grayscale, or subpixel".into()))?;
s.prefs.text_smoothing = smoothing;
Ok(json!({"textSmoothing": smoothing}))
})
.params(r#"{"value": "system" | "grayscale" | "subpixel"}"#)
.pure(),
// Print Layout: hide the white space (margins, headers, footers) between pages. Screen only.
CommandSpec::new("view.hideWhiteSpace", "Hide White Space", "View › Show", |s, v| toggle(s, v, |x| &mut x.hide_white_space))
.params(r#"{"value"?: bool}"#)
@@ -358,35 +349,6 @@ fn read_line_spacing(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"spacing": spacing}))
}
/// How the edges of page text are smoothed on screen, saved with user preferences, never in the
/// document. Exports, prints and PDFs are not affected.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TextSmoothing {
/// As the system is set: subpixel where it asks for it (ClearType on Windows, `rgba`
/// antialiasing on a Linux desktop) and the screen is not a high-density one, else
/// greyscale. macOS never asks for it.
#[default]
System,
/// Greyscale antialiasing: grey edges, no colour.
Grayscale,
/// Subpixel (LCD) antialiasing, whatever the system says: edges three times as fine
/// sideways, with faint colour in them. In the system's stripe order, RGB when it gives none.
Subpixel,
}
impl TextSmoothing {
pub const ALL: [Self; 3] = [Self::System, Self::Grayscale, Self::Subpixel];
pub fn label(self) -> &'static str {
match self {
Self::System => "Use system setting",
Self::Grayscale => "Grayscale",
Self::Subpixel => "Subpixel (LCD)",
}
}
}
/// Screen-only paper presets, saved with user preferences, never in the document.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
-11
View File
@@ -10,10 +10,6 @@ pub struct Prefs {
/// On-screen paper for pages without a document background; excluded from saved documents.
#[serde(deserialize_with = "lenient_paper_color")]
pub paper_color: crate::cmd::view::PaperColor,
/// How the edges of page text are smoothed on screen (`view.textSmoothing`); excluded from
/// saved documents.
#[serde(deserialize_with = "lenient_text_smoothing")]
pub text_smoothing: crate::cmd::view::TextSmoothing,
/// Track Changes Options: what markup shows and how revisions are drawn (per user, as in
/// Word).
pub markup: wordcraft_layout::display::MarkupOptions,
@@ -76,7 +72,6 @@ impl Default for Prefs {
fn default() -> Self {
Prefs {
paper_color: Default::default(),
text_smoothing: Default::default(),
count_notes: true,
markup: Default::default(),
print_markup: false,
@@ -124,12 +119,6 @@ fn lenient_paper_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::
Ok(serde_json::from_value(value).unwrap_or_default())
}
/// Ignore an invalid saved text smoothing without discarding other preferences.
fn lenient_text_smoothing<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::cmd::view::TextSmoothing, D::Error> {
let value = serde_json::Value::deserialize(d)?;
Ok(serde_json::from_value(value).unwrap_or_default())
}
/// Ignore an invalid saved Page Color without discarding other preferences.
fn lenient_read_page_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::cmd::view::ReadPageColor, D::Error> {
let value = serde_json::Value::deserialize(d)?;
+142 -39
View File
@@ -293,14 +293,6 @@ fn custom_dictionary_words_persist_through_their_file() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn confined_sessions_test_is_native_only() {
let source = include_str!("tests.rs");
assert!(source.contains(
"#[cfg(not(target_arch = \"wasm32\"))]\n#[test]\nfn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots()"
));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn confined_sessions_neither_save_the_dictionary_nor_choose_folders_outside_their_roots() {
@@ -1170,6 +1162,27 @@ fn toggle_on_a_column_block_follows_first_character() {
assert_eq!(toggled(1, false), vec![true, true, true]);
}
/// A collapsed caret inside a partly formatted word (including when column mode just started with
/// an empty block) turns the format on unless the whole word already has it (#8658).
#[test]
fn toggle_at_collapsed_caret_in_partly_formatted_word_turns_on() {
let toggled = |column_mode: bool| -> String {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Abc"}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 0, "off": 1}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 1}}));
if column_mode {
run(&mut s, "select.column", json!({}));
}
run(&mut s, "format.bold", json!({}));
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
(0..3).map(|i| if p.props_of_char(i).bold == Some(true) { 'B' } else { '.' }).collect()
};
assert_eq!(toggled(false), "BBB");
assert_eq!(toggled(true), "BBB");
}
#[test]
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
@@ -5161,6 +5174,48 @@ fn no_markup_view_lays_out_the_final_text() {
assert!(gap(&mut s).abs() < 0.01);
}
#[test]
fn horizontal_caret_skips_hidden_tracked_deletions() {
let mut s = s();
let text = "Aé🧪ZUVΩT";
let before = Pos::body(0, "A".len());
let between = Pos::body(0, "Aé".len());
let after = Pos::body(0, "Aé🧪".len());
let far_start = Pos::body(0, "Aé🧪ZUV".len());
let far_end = Pos::body(0, "Aé🧪ZUVΩ".len());
run(&mut s, "document.setText", json!({"text": text}));
// Keep the adjacent deleted characters in separate formatting runs.
s.doc.format_range(&before, &between, &|c| c.bold = Some(true)).unwrap();
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "é🧪"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "select.text", json!({"text": "Ω"}));
run(&mut s, "text.delete", json!({}));
assert_eq!(s.doc.para_at(&before).unwrap().deleted_ranges(), [before.off..between.off, between.off..after.off, far_start.off..far_end.off]);
s.sel = crate::Selection::caret(before.clone());
run(&mut s, "caret.right", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé".len()), "visible markup still has ordinary caret stops");
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
s.sel = crate::Selection::caret(before.clone());
run(&mut s, "caret.right", json!({"extend": true}));
assert_eq!(s.sel.anchor, before);
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪Z".len()), "Right crosses the next visible character in one step");
s.sel = crate::Selection::caret(after);
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 0), "Left crosses the previous visible character in one step");
assert!(s.sel.is_collapsed());
s.sel = crate::Selection::caret(Pos::body(0, "Aé🧪Z".len()));
run(&mut s, "caret.right", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "a distant deletion does not change a visible stop");
s.sel = crate::Selection::caret(far_end);
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, "Aé🧪ZU".len()), "Left also skips the later deletion");
}
#[test]
fn replace_all_is_tracked() {
let mut s = s();
@@ -15279,37 +15334,6 @@ fn export_png_rejects_a_page_number_that_does_not_fit() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn screen_text_smoothing_is_a_persistent_preference_not_document_formatting() {
use crate::cmd::view::TextSmoothing;
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Screen text test", "raw": true}));
let before = serde_json::to_value(&s.doc).unwrap();
let docx_before = wordcraft_docx::write(&s.doc).unwrap();
s.dirty = false;
assert_eq!(s.prefs.text_smoothing, TextSmoothing::System, "follows the system until the user chooses");
for (value, expected) in [("subpixel", TextSmoothing::Subpixel), ("grayscale", TextSmoothing::Grayscale), ("system", TextSmoothing::System)] {
let r = run(&mut s, "view.textSmoothing", json!({"value": value}));
assert_eq!(r["textSmoothing"], value);
assert_eq!(s.prefs.text_smoothing, expected);
assert_eq!(serde_json::to_value(&s.doc).unwrap(), before);
assert!(!s.dirty);
assert_eq!(wordcraft_docx::write(&s.doc).unwrap(), docx_before);
let restored: crate::Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
assert_eq!(restored.text_smoothing, expected);
}
run(&mut s, "view.textSmoothing", json!({"value": "subpixel"}));
for v in [json!({}), json!({"value": "lcd"}), json!({"value": 42}), json!({"value": null}), json!({"value": ["subpixel"]})] {
assert!(s.run("view.textSmoothing", &v).is_err(), "{v}");
assert_eq!(s.prefs.text_smoothing, TextSmoothing::Subpixel, "a refused value changes nothing");
}
let legacy: crate::Prefs = serde_json::from_value(json!({})).unwrap();
assert_eq!(legacy.text_smoothing, TextSmoothing::System);
let future: crate::Prefs = serde_json::from_value(json!({"textSmoothing":"future", "countNotes":false})).unwrap();
assert_eq!(future.text_smoothing, TextSmoothing::System);
assert!(!future.count_notes);
}
#[test]
fn screen_paper_color_is_a_persistent_preference_not_document_formatting() {
use crate::cmd::view::PaperColor;
@@ -16251,3 +16275,82 @@ fn nested_group_text_box_survives_mutating_session_commands() {
assert_eq!(s.doc.plain_text(StoryRef::Part(id)), "nested group box");
}
}
#[test]
fn copy_refuses_to_fill_clipboard_by_halves_when_export_fails() {
let mut s = Session::new(wordcraft_doc::Document::from_text("first second"));
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, 5)}));
run(&mut s, "edit.copy", json!({}));
let prev_text = s.clipboard_text.clone();
let prev_html = s.clipboard_html.clone();
let prev_rtf = s.clipboard_rtf.clone();
let prev_history_len = s.clip_history.len();
assert_eq!(prev_text, "first");
assert!(!prev_html.is_empty() && !prev_rtf.is_empty());
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 6), "focus": Pos::body(0, 12)}));
// HTML export fails first.
let err = wordcraft_formats::with_shared_conversion_error("html failed", || s.run("edit.copy", &json!({}))).unwrap_err();
assert!(err.to_string().contains("html failed"), "{err}");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clipboard.as_ref().map(|f| f.plain_text()), Some("first".to_string()));
assert_eq!(s.clip_history.len(), prev_history_len);
// HTML export succeeds and RTF export fails: clipboard still keeps "first" whole.
let err = wordcraft_formats::with_shared_conversion_error_after(1, "rtf failed", || s.run("edit.copy", &json!({}))).unwrap_err();
assert!(err.to_string().contains("rtf failed"), "{err}");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clipboard.as_ref().map(|f| f.plain_text()), Some("first".to_string()));
assert_eq!(s.clip_history.len(), prev_history_len);
// Cut also refuses to delete the selection when export fails.
let err = wordcraft_formats::with_shared_conversion_error_after(1, "rtf failed", || s.run("edit.cut", &json!({}))).unwrap_err();
assert!(err.to_string().contains("rtf failed"), "{err}");
assert_eq!(text(&s), "first second");
assert_eq!(s.clipboard_text, prev_text);
assert_eq!(s.clipboard_html, prev_html);
assert_eq!(s.clipboard_rtf, prev_rtf);
assert_eq!(s.clip_history.len(), prev_history_len);
}
#[test]
fn paste_reports_or_falls_back_when_html_import_fails() {
let mut s = Session::new(wordcraft_doc::Document::from_text("kept"));
let err = wordcraft_formats::with_shared_conversion_error("html import failed", || {
s.run("edit.pasteSpecial", &json!({"as": "html", "html": "<p>new</p>"}))
})
.unwrap_err();
assert!(err.to_string().contains("html import failed"), "{err}");
assert_eq!(text(&s), "kept");
let fallback = wordcraft_formats::with_shared_conversion_error_after(0, "html import failed", || {
cmd::paste::rich_fragment(&mut s, &json!({"html": "<p>from html</p>", "rtf": "{\\rtf1 from rtf}"}))
});
assert_eq!(fallback.as_ref().map(|f| f.plain_text()), Some("from rtf".to_string()));
let none = wordcraft_formats::with_shared_conversion_error("html import failed", || {
cmd::paste::rich_fragment(&mut s, &json!({"html": "<p>from html</p>"}))
});
assert!(none.is_none());
}
#[test]
fn open_and_save_report_format_conversion_errors() {
let doc = wordcraft_doc::Document::from_text("hello");
wordcraft_formats::with_shared_conversion_error("bridge down", || {
for (name, bytes) in [("a.html", b"<p>hello</p>" as &[u8]), ("a.md", b"# hello"), ("a.tex", b"hello")] {
let err = crate::io::open_bytes(name, bytes).unwrap_err();
assert!(err.contains("bridge down"), "{name}: {err}");
}
for name in ["a.html", "a.md", "a.tex", "a.rtf"] {
let err = crate::io::save_bytes(name, &doc).unwrap_err();
assert!(err.contains("bridge down"), "{name}: {err}");
}
});
}
+21
View File
@@ -226,6 +226,27 @@ fn arrow_keys_move_visually_in_rtl_text() {
assert_eq!(s.sel.focus.off, b.off);
}
#[test]
fn arrow_keys_skip_hidden_deletions_in_rtl_text() {
let text = "אבגדה";
let mut s = session(text, true);
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "בגד"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
for (command, from, to, direction) in [("caret.left", 0, text.len(), -1.0), ("caret.right", text.len(), 0, 1.0)] {
s.sel = crate::Selection::caret(Pos::body(0, from));
for _ in 0..2 {
let before = caret_x(&mut s);
run(&mut s, command, json!({}));
assert!((caret_x(&mut s) - before) * direction > 0.01, "{command} moves to the next visual stop");
assert!(s.sel.focus.off <= "א".len() || s.sel.focus.off >= "אבגד".len());
}
assert_eq!(s.sel.focus.off, to);
}
}
#[test]
fn arrow_keys_in_mixed_text_visit_each_position() {
// A left-to-right paragraph with a Persian word: Right walks across the screen.
+31 -8
View File
@@ -179,34 +179,57 @@ fn fit_one_page_respects_max_delta() {
#[test]
fn fit_one_page_respects_step_pt() {
let at_11_4 = |lines: usize| {
let mut s = create_multiline_doc(lines);
let set_size = |s: &mut Session, size_pt: f32| {
for b in &mut s.doc.body {
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
p.mark.size = Some(11.4);
p.mark.size = Some(size_pt);
for r in &mut p.runs {
r.props.size = Some(11.4);
r.props.size = Some(size_pt);
}
}
}
s.touch();
s.relayout();
};
let at_size = |lines: usize, size_pt: f32| {
let mut s = create_multiline_doc(lines);
set_size(&mut s, size_pt);
s
};
let mut s = just_spilling(at_11_4);
// Find the most lines that fit on one page at 11.4 pt, spill the last paragraph at 11.1 pt
// so 0.1..0.3 pt reductions are not enough, then restore 11.4 pt so fitting requires 0.4 pt.
let mut lines = 10;
while at_size(lines + 1, 11.4).layout().pages.len() < 2 {
lines += 1;
assert!(lines < 120, "{lines} lines still fit on one page at 11.4 pt");
}
let mut s = at_size(lines, 11.1);
assert_eq!(s.layout().pages.len(), 1, "{lines} lines must fit on one page at 11.1 pt");
spill_last_paragraph(&mut s);
set_size(&mut s, 11.4);
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
assert_fixture_font(&mut s);
// Both calls hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
// Hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
// Default 0.5 pt step generates no candidates <= 0.4 pt, so it must fail.
let doc_backup = s.doc.clone();
let default_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "adjustSpacing": false}));
assert!(default_res.is_err(), "default step 0.5 must skip all candidates when maxDelta is 0.4");
// With stepPt = 0.1 under the same maxDeltaPt = 0.4, a fine-grained step (0.1 to 0.4 pt) succeeds.
// With stepPt = 0.1 and maxDeltaPt = 0.3, the document still spills onto page 2.
s.doc = doc_backup.clone();
s.touch();
let too_small_res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.3, "stepPt": 0.1, "adjustSpacing": false}));
assert!(too_small_res.is_err(), "0.3 pt cap must not recover a document needing 0.4 pt");
// With stepPt = 0.1 under maxDeltaPt = 0.4, the 0.4 pt boundary step (11.4 -> 11.0 pt) succeeds.
s.doc = doc_backup;
s.touch();
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.4, "stepPt": 0.1, "adjustSpacing": false}));
assert!(res.is_ok(), "stepPt=0.1 must generate fine-grained candidates under maxDelta 0.4: {res:?}");
assert!(res.is_ok(), "stepPt=0.1 must reach the 0.4 pt boundary step under maxDelta 0.4: {res:?}");
assert_eq!(s.layout().pages.len(), 1);
assert!(s.status.contains("font: -0.4 pt"), "expected 0.4 pt reduction in status, got: {}", s.status);
}
#[test]
+52
View File
@@ -2471,6 +2471,58 @@ fn left_and_right_keys_step_into_and_out_of_an_equation() {
assert_eq!((editing(&s), s.sel.anchor.clone(), s.sel.focus.clone()), (None, Pos::body(0, 1), Pos::body(0, 1)));
}
#[test]
fn arrow_keys_skip_a_deleted_equation_in_no_markup() {
let mut s = equations_between_a_and_b(1);
let before = Pos::body(0, 1);
let after = Pos::body(0, 1 + wordcraft_doc::para::OBJ.len_utf8());
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.range", json!({"anchor": before, "focus": after}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
let end = Pos::body(0, after.off + 1);
for (from, key, expected) in [(before, "Right", end), (after, "Left", Pos::body(0, 0))] {
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert!(editing(&s).is_none(), "{key} must not open a hidden equation");
assert_eq!(s.sel.focus, expected);
}
}
#[test]
fn arrow_keys_enter_a_visible_equation_across_a_hidden_deletion() {
use wordcraft_doc::math_edit::{MathPos, units};
let equation_width = wordcraft_doc::para::OBJ.len_utf8();
let before = "a".len();
let after = "aé".len();
let end = MathPos::new(Vec::new(), units(&wordcraft_doc::math::parse_linear("x+y")));
for (key, shift_key, equation, from, across, math_pos) in [
("Right", "Shift+Right", after, before, after + equation_width, MathPos::default()),
("Left", "Shift+Left", before, after + equation_width, before, end),
] {
let mut s = typed("aéb");
let from = Pos::body(0, from);
let equation = Pos::body(0, equation);
run(&mut s, "caret.set", json!({"pos": equation}));
run(&mut s, "insert.equation", json!({"linear": "x+y", "edit": false}));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "select.text", json!({"text": "é"}));
run(&mut s, "text.delete", json!({}));
run(&mut s, "review.markup", json!({"value": "noMarkup"}));
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, shift_key);
assert!(editing(&s).is_none(), "{shift_key} extends the selection");
assert_eq!((s.sel.anchor.clone(), s.sel.focus.clone()), (from.clone(), Pos::body(0, across)));
run(&mut s, "caret.set", json!({"pos": from}));
arrow(&mut s, key);
assert_eq!(editing(&s), Some((equation, math_pos)));
}
}
#[test]
fn right_out_of_an_equation_steps_into_the_one_beside_it() {
let e = wordcraft_doc::para::OBJ.len_utf8();
-33
View File
@@ -183,18 +183,6 @@ fn german_date_fields_inherit_the_document_default_language() {
}
}
/// `MMM` and `ddd` use Word's Windows NLS short forms for German: two-letter weekdays (`So`,
/// `Mo`…) and `Mrz` for March, with no trailing full stop (#7146).
#[test]
fn a_german_short_date_field_uses_windows_nls_abbreviations() {
const PICTURE: &str = "ddd, d. MMM yyyy";
let d = open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wed, 1 Jan 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
// The abbreviations at a fixed date, independent of when the test runs.
assert_eq!(wordcraft_engine::cmd::insert::format_date_parts_in(PICTURE, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3), "So, 15. Mrz 2026");
}
/// A `TIME` field whose picture carries German name tokens inherits the language too, so the
/// English result cached in the fixture is replaced with German weekday and month names.
#[test]
@@ -207,27 +195,6 @@ fn a_german_time_field_uses_german_names() {
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland and
/// bare `de` keep `Januar` (`Jan`), as in Windows NLS (#7146). A `de-AT` document reads German
/// through `docDefaults`; the refresh always uses the real clock, so the January names are asked
/// of the same formatter at a fixed January instant.
#[test]
fn austrian_german_documents_use_jaenner() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
let d = open_body_in_lang("de-AT", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-AT")), "an Austrian document reads German");
let january = |lang: &str, picture: &str| wordcraft_engine::cmd::insert::format_date_parts_in(picture, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de-AT", PICTURE), "Donnerstag, 15. Jänner 2026");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
}
/// A minimal Word 97-2003 file whose only paragraph holds a `DATE` field cached as " 2001":
/// FIB, one compressed text piece, and the Clx that points at it.
fn binary_doc_with_stale_date() -> Vec<u8> {
+59
View File
@@ -28,17 +28,76 @@ use wordcraft_doc::Document;
/// (`wordcraft_docx::package::MAX_ENTRIES`); checked before `zip` parses them (#3660).
pub const MAX_ZIP_ENTRIES: u64 = 20_000;
#[cfg(any(test, feature = "test-support"))]
thread_local! {
/// `(skip, repeat, message)`: when `Some`, lets `skip` calls to `to_shared` / `from_shared`
/// run normally, then fails the next call with `message` (and every subsequent call when
/// `repeat` is `true`).
static SHARED_ERROR: std::cell::Cell<Option<(usize, bool, &'static str)>> = const { std::cell::Cell::new(None) };
}
#[cfg(any(test, feature = "test-support"))]
fn take_shared_error() -> Option<String> {
SHARED_ERROR.with(|slot| {
let (skip, repeat, msg) = slot.get()?;
if skip > 0 {
slot.set(Some((skip - 1, repeat, msg)));
None
} else {
if !repeat {
slot.set(None);
}
Some(msg.to_string())
}
})
}
#[cfg(any(test, feature = "test-support"))]
fn with_shared_error_state<T>(state: Option<(usize, bool, &'static str)>, f: impl FnOnce() -> T) -> T {
struct Reset(Option<(usize, bool, &'static str)>);
impl Drop for Reset {
fn drop(&mut self) {
SHARED_ERROR.with(|slot| slot.set(self.0));
}
}
let prev = SHARED_ERROR.with(|slot| slot.replace(state));
let _reset = Reset(prev);
f()
}
/// Simulates a `to_shared` / `from_shared` conversion failure for every call inside `f`.
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
pub fn with_shared_conversion_error<T>(msg: &'static str, f: impl FnOnce() -> T) -> T {
with_shared_error_state(Some((0, true, msg)), f)
}
/// Lets `skip` `to_shared` / `from_shared` conversions run normally, then fails the next one once.
#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
pub fn with_shared_conversion_error_after<T>(skip: usize, msg: &'static str, f: impl FnOnce() -> T) -> T {
with_shared_error_state(Some((skip, false, msg)), f)
}
/// The document as the shared model the format crates read and write.
///
/// A conversion that fails is an error, never an empty document or an empty file: the caller
/// says so instead of writing a file with nothing in it.
pub(crate) fn to_shared(doc: &Document) -> Result<craft_wordmodel::Document, String> {
#[cfg(any(test, feature = "test-support"))]
if let Some(err) = take_shared_error() {
return Err(err);
}
wordcraft_docx::to_shared_model(doc).map_err(|e| e.to_string())
}
/// The shared model as the app's document model. A conversion that fails is an error, never
/// an empty document.
pub(crate) fn from_shared(shared: craft_wordmodel::Document) -> Result<Document, String> {
#[cfg(any(test, feature = "test-support"))]
if let Some(err) = take_shared_error() {
return Err(err);
}
wordcraft_docx::from_shared_model(shared).map_err(|e| e.to_string())
}
+68
View File
@@ -338,6 +338,74 @@ fn a_format_that_cannot_be_read_is_an_error_not_a_blank_document() {
assert!(e.contains("RTF"), "{e}");
}
/// Every HTML, Markdown, LaTeX, RTF and MHT importer and exporter propagates `to_shared` /
/// `from_shared` errors instead of falling back to an empty document or empty string.
#[test]
fn shared_conversion_errors_propagate_through_all_formats_without_empty_fallback() {
let doc = sample();
let page = wordcraft_doc::SectionProps::default();
let mht_bytes = b"MIME-Version: 1.0\r\nContent-Type: multipart/related; boundary=\"b\"\r\n\r\n--b\r\nContent-Type: text/html\r\n\r\n<p>hello</p>\r\n--b--\r\n";
let msg = "simulated shared conversion failure";
let assert_err = |res: Result<String, String>, label: &str| {
let e = res.unwrap_err();
assert!(e.contains(msg), "{label}: {e}");
};
crate::with_shared_conversion_error(msg, || {
assert_err(crate::html::import("<p>hello</p>").map(|_| String::new()), "html::import");
assert_err(crate::html::import_page("<p>hello</p>", &|_| None).map(|_| String::new()), "html::import_page");
assert_err(crate::html::import_with("<p>hello</p>", &|_| None).map(|_| String::new()), "html::import_with");
assert_err(crate::html::import_on("<p>hello</p>", &|_| None, &page).map(|_| String::new()), "html::import_on (section)");
assert_err(crate::html::export(&doc), "html::export");
assert_err(crate::html::export_fragment(&doc), "html::export_fragment");
assert_err(crate::markdown::import("hello").map(|_| String::new()), "markdown::import");
assert_err(crate::markdown::import_on("hello", &page).map(|_| String::new()), "markdown::import_on (section)");
assert_err(crate::markdown::import_on_with_lines("hello", &page).map(|_| String::new()), "markdown::import_on_with_lines (section)");
assert_err(crate::markdown::export(&doc), "markdown::export");
assert_err(crate::latex::import(b"hello").map(|_| String::new()), "latex::import");
assert_err(crate::latex::import_on(b"hello", &page).map(|_| String::new()), "latex::import_on");
assert_err(crate::latex::export(&doc), "latex::export");
assert_err(crate::rtf::import(br"{\rtf1 hello}").map(|_| String::new()), "rtf::import");
assert_err(crate::rtf::export(&doc), "rtf::export");
assert_err(crate::mht::import(mht_bytes).map(|_| String::new()), "mht::import (section)");
assert_err(crate::mht::import_on(mht_bytes, &page).map(|_| String::new()), "mht::import_on (section)");
for (ext, bytes) in [("html", b"<p>hello</p>" as &[u8]), ("md", b"hello"), ("tex", b"hello"), ("rtf", br"{\rtf1 hello}"), ("mht", mht_bytes)]
{
assert_err(import(ext, bytes).unwrap().map(|_| String::new()), &format!("import({ext})"));
assert_err(crate::import_on(ext, bytes, &page).unwrap().map(|_| String::new()), &format!("import_on({ext})"));
}
for ext in ["html", "md", "tex", "rtf"] {
assert_err(export(ext, &doc).unwrap().map(|_| String::new()), &format!("export({ext})"));
assert_err(
crate::export_with(ext, &doc, &crate::ExportOptions { comments: true }).unwrap().map(|_| String::new()),
&format!("export_with({ext})"),
);
}
});
// For `import_on` helpers that first convert `page` via `shared_section`, also verify that
// a `from_shared` failure after `shared_section` succeeds still propagates as an error.
for (label, res) in [
(
"html::import_on (from_shared)",
crate::with_shared_conversion_error_after(1, msg, || crate::html::import_on("<p>hello</p>", &|_| None, &page)),
),
("markdown::import_on (from_shared)", crate::with_shared_conversion_error_after(1, msg, || crate::markdown::import_on("hello", &page))),
(
"markdown::import_on_with_lines (from_shared)",
crate::with_shared_conversion_error_after(1, msg, || crate::markdown::import_on_with_lines("hello", &page).map(|(d, _)| d)),
),
("mht::import_on (from_shared)", crate::with_shared_conversion_error_after(1, msg, || crate::mht::import_on(mht_bytes, &page))),
] {
assert_err(res.map(|_| String::new()), label);
}
}
#[test]
fn odt_round_trip() {
check_round_trip("odt", true);
+18 -9
View File
@@ -160,8 +160,8 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
let layout = table::layout_table(ctx, story, t, path, width, depth + 1);
let (tx, ty) = match t.props.float {
Some(float) => {
let legacy = (ctx.doc.settings.compat_mode < 15).then(|| table::first_cell_left_margin(ctx, t));
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, legacy, float_tables);
let place = FloatPlace { shift: table::float_offset_shift(ctx, t), modern: ctx.doc.settings.compat_mode >= 15 };
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, place, float_tables);
exclusions.push((area, false, None, WrapText::BothSides, true));
float_tables.push(area);
table_areas.push(area);
@@ -525,17 +525,25 @@ pub(crate) struct BoxLayout {
pub(crate) last_top: f32,
}
/// How a floating table placed by an offset stands from it.
#[derive(Clone, Copy)]
struct FloatPlace {
/// How far left of the offset its edge stands ([`table::float_offset_shift`]).
shift: f32,
/// Word 2013 layout (compatibility mode 15).
modern: bool,
}
/// Where floating table `tl` goes in a box `width` wide whose next paragraph starts at `y`, and
/// the area text keeps clear of. Positions relative to the page or its margins need the box's
/// `frame`; without one (a table cell) they're relative to the box. `legacy` is the first cell's
/// left margin before Word 2013 layout, `None` in it.
/// `frame`; without one (a table cell) they're relative to the box.
fn box_float_table_rect(
frame: Option<PageFrame>,
width: f32,
y: f32,
tl: &table::TableLayout,
f: &TableFloat,
legacy: Option<f32>,
place: FloatPlace,
float_tables: &[Rect],
) -> (Rect, Rect) {
let h = tl.rows.iter().map(|r| r.height).sum::<f32>().clamp(0.0, 100_000.0);
@@ -571,8 +579,8 @@ fn box_float_table_rect(
};
// Nor is there an area to align in: the table starts where the text is.
let v_align = if frame.is_none() && matches!(f.v_rel, Anchor::Page | Anchor::Margin) { None } else { f.v_align };
let x = align_in(h_area, f.x, w, PageFrame::h_align(frame.as_ref(), f.h_align)) - if f.h_align.is_none() { legacy.unwrap_or(0.0) } else { 0.0 };
let r = clear_of_float_tables(Rect::new(x, align_in(v_area, y_off, h, v_align), w, h), f, legacy.is_none(), h_area.0, float_tables);
let x = align_in(h_area, f.x, w, PageFrame::h_align(frame.as_ref(), f.h_align)) - if f.h_align.is_none() { place.shift } else { 0.0 };
let r = clear_of_float_tables(Rect::new(x, align_in(v_area, y_off, h, v_align), w, h), f, place.modern, h_area.0 - place.shift, float_tables);
let [dl, dt, dr, db] = f.dist_from_text();
(r, r.inset(-dl, -dt, -dr, -db))
}
@@ -827,8 +835,9 @@ impl Joint {
}
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
/// without its space before, as [`Joint::fit`] lays it out.
/// it, it runs right to left, or it is a text frame placed apart (`frames` and `cell_frame`
/// both hold, sharing no line; in a table cell, only frames anchored to `"text"`): without
/// its space before, as [`Joint::fit`] lays it out.
fn take_up(
self,
ctx: &mut Ctx,
+4
View File
@@ -152,6 +152,10 @@ pub(crate) fn env_hash(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOpt
let outline = (opts.view == ViewMode::Outline).then(|| opts.outline.as_ref().is_some_and(|o| o.plain));
let mut h = std::collections::hash_map::DefaultHasher::new();
styles.hash(&mut h);
// Theme fonts affect East Asian slot resolution (when `font_ea_theme` is set).
doc.settings.major_font.hash(&mut h);
doc.settings.minor_font.hash(&mut h);
doc.passthrough.get("wordcraft:theme.fonts").hash(&mut h);
// The compatibility mode changes paragraph layout too (widow control in table cells).
doc.settings.compat_mode.hash(&mut h);
opts.show_hidden.hash(&mut h);
+44 -5
View File
@@ -483,6 +483,7 @@ fn anchor_floats_but(
ctx.fields.page_format = pb.page_format;
let (col_x, width) = (pb.col_x(), pb.col_w());
let mut rects = HashMap::new();
let mut areas = HashMap::new();
if !pb.web && place {
// (A mark from a page before may be short of the areas this page started with.)
pb.excl.truncate(excl_mark.max(pb.seeded));
@@ -519,20 +520,58 @@ fn anchor_floats_but(
// with it known from the start (#2048).
let above = area.as_ref().filter(|a| text_before && a.0.y < top - 0.5).map(|a| (page, a.clone()));
ctx.floats_above.insert((block, oi), above);
if let Some(area) = area {
match early.and_then(|v| v.iter().position(|(b, k, _)| (*b, *k) == (block, oi))).filter(|k| *k < pb.seeded) {
let slot = if let Some(area) = area {
let b = area.0.bottom();
let k = match early.and_then(|v| v.iter().position(|(b, k, _)| (*b, *k) == (block, oi))).filter(|k| *k < pb.seeded) {
Some(k) => {
if let Some(slot) = pb.excl.get_mut(k) {
*slot = area;
}
k
}
None => pb.excl.push(area),
}
}
None => {
let k = pb.excl.len();
pb.excl.push(area);
k
}
};
Some((k, b))
} else {
None
};
areas.insert(oi, slot);
}
}
let rel = rel_exclusions(&body_wraps(ctx, pb), col_x, y0, before);
let pl = ctx.para_labelled(p, width, None, &rel, before, label.clone());
let lead = pl.lines.first().map_or(0.0, |l| l.top.max(0.0));
if !pb.web && place && lead > 0.0 {
let page = pb.pages.len().saturating_sub(1);
let top = y0 - before;
let text_before = top > pb.top + 0.5 || pb.col > 0;
let frame = PageFrame { sect: pb.sect, margin_top: None, origin: (0.0, 0.0), number: pb.number, mirror: ctx.mirror };
for (oi, o) in p.objects.iter().enumerate() {
let Some((_, _, float)) = floating(o) else { continue };
let Some(&area) = areas.get(&oi) else { continue };
let Some(&r) = rects.get(&oi) else { continue };
if float.y < 0.0 && area.map_or(r.bottom(), |(_, b)| b) < y0 + lead - 0.5 {
// Only down: across it stays where it was placed (`settle_early` may have moved it).
let moved = Rect { y: float_rect(Some(frame), (col_x, width), top + lead, r.w, r.h, float).y, ..r };
// A wrap area moved onto the first line would cover text laid out without it.
if area.is_some_and(|(_, b)| b + (moved.y - r.y) > y0 + lead - 0.5) {
continue;
}
rects.insert(oi, moved);
if let Some((k, _)) = area
&& let Some(slot) = pb.excl.get_mut(k)
{
slot.0.y += moved.y - r.y;
let above = (text_before && slot.0.y < top - 0.5).then(|| (page, slot.clone()));
ctx.floats_above.insert((block, oi), above);
}
}
}
}
(rects, pl, rel)
}
+3 -2
View File
@@ -40,8 +40,9 @@ pub(crate) fn section_side(start: SectionStart, restart: Option<u32>, last: u32,
/// header and footer go on: the page where the section begins. A page's section is the one at its
/// top, so a section that starts continuously part-way down `prev` has no first page of its own:
/// Word shows the earlier section's header there and the section's default one from the next page
/// on, also when its first paragraph begins on `prev` and runs over. `sections` as
/// [`Document::sections`] gives them (each with its last block).
/// on; the case where its first paragraph begins on `prev` and runs over is treated the same way
/// (inferred, not measured separately in Word). `sections` as [`Document::sections`] gives them
/// (each with its last block).
pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool {
if prev.is_some_and(|p| p.section == page.section) {
return false;
+6
View File
@@ -1025,6 +1025,12 @@ impl DocLayout {
let here = para.x_of(li, pos.off)?;
let mut best: Option<(usize, f32)> = None;
for (off, x) in para.line_carets(li) {
// Omitted runs retain byte offsets as zero-width markers. Keep their
// visible edges as candidates without placing the caret inside a run.
let span = para.left_out.partition_point(|range| range.end <= off);
if para.left_out.get(span).is_some_and(|range| range.start < off) {
continue;
}
let Some(x) = x else { continue };
let ahead = if left { x < here - 0.01 } else { x > here + 0.01 };
let d = (x - here).abs();
+9 -7
View File
@@ -346,13 +346,15 @@ impl<'a> Builder<'a> {
(resolved.face, resolved.substituted || !family.eq_ignore_ascii_case(&r.font))
});
let primary_cs = resolved_cs.map(|(face, _)| face);
// Chinese, Japanese and Korean characters use the run's East Asian font (`w:eastAsia`) when
// it, or the font table alternate it is drawn in (#2702), is installed and has them.
let wanted_ea = rc.font_ea.as_deref().filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| {
let family = lookup_family(self.env.doc, f);
let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic);
(f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f))
});
// Chinese, Japanese and Korean characters use the run's East Asian font (`w:eastAsiaTheme`
// over `w:eastAsia`) when it, or the font table alternate it is drawn in (#2702), is
// installed and has them.
let wanted_ea =
super::chars::east_asian_font(self.env.doc, rc).filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| {
let family = lookup_family(self.env.doc, f);
let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic);
(f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f))
});
let primary_ea = wanted_ea.filter(|(_, r, _)| !r.substituted).map(|(_, r, _)| r.face);
// The levels by byte of `text`, from `lbase` on.
let (levels, lbase): (&[u8], usize) = match dir {
+29
View File
@@ -213,6 +213,35 @@ pub fn substitute_face(doc: &Document, font: &str) -> Option<FaceRef> {
(r.substituted || family != font).then_some(r.face)
}
const THEME_FONTS_PASSTHROUGH: &str = "wordcraft:theme.fonts";
/// The East Asian font (`a:ea`) stored for the theme's major or minor font scheme, when the
/// document's theme names a non-empty one (`craft-docx` keeps them in `wordcraft:theme.fonts`).
fn theme_ea_face(doc: &Document, major: bool) -> Option<&str> {
let text = std::str::from_utf8(doc.passthrough.get(THEME_FONTS_PASSTHROUGH)?).ok()?;
let key = if major { "major" } else { "minor" };
text.lines().find_map(|line| {
let mut parts = line.splitn(4, '\t');
let (k, kind, which, face) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
(k == key && kind == "face" && which == "ea" && !face.trim().is_empty()).then_some(face)
})
}
/// The East Asian font effective for a run (`w:eastAsiaTheme` takes precedence over `w:eastAsia`,
/// including an inherited `w:eastAsia`). Returns `None` when none is named or the theme slot
/// points to an East Asian theme font with no single named `a:ea` face.
pub(super) fn east_asian_font<'a>(doc: &'a Document, rc: &'a ResolvedChar) -> Option<&'a str> {
use wordcraft_doc::props::ThemeFont;
match rc.font_ea_theme {
Some(ThemeFont::MajorEastAsia) => theme_ea_face(doc, true),
Some(ThemeFont::MinorEastAsia) => theme_ea_face(doc, false),
Some(ThemeFont::MajorAscii | ThemeFont::MajorHAnsi) => Some(doc.settings.major_font.as_str()).filter(|f| !f.trim().is_empty()),
Some(ThemeFont::MinorAscii | ThemeFont::MinorHAnsi) => Some(doc.settings.minor_font.as_str()).filter(|f| !f.trim().is_empty()),
Some(ThemeFont::MajorBidi | ThemeFont::MinorBidi) => None,
None => rc.font_ea.as_deref().filter(|f| !f.trim().is_empty()),
}
}
/// The face Chinese, Japanese and Korean text is drawn in when its East Asian font (`w:eastAsia`)
/// `font_ea` isn't installed and the run's font is `font`; `None` when `font_ea` is installed. As
/// layout draws it: an East Asian font is looked up by name alone (the roman-font rule of
+2
View File
@@ -70,6 +70,8 @@ pub(super) fn snap_chars(b: &mut Builder, text: &str, grid: &Grid) {
g.dx += shift;
}
c.adv = adv;
// The snapped advance no longer includes the shaped kerning adjustment.
c.kern = 0.0;
}
}
+8 -9
View File
@@ -392,7 +392,8 @@ impl<'e> Breaker<'e> {
/// Returns how it ends.
fn close_line(&mut self, pl: &mut ParaLayout, mut sc: Scan) -> LineEnd {
if sc.end == LineEnd::Para || sc.end == LineEnd::Wrap {
let xc = sc.x;
let kern = if sc.end == LineEnd::Wrap && sc.j > sc.c0 { line_end_kern(pl, sc.j - 1) } else { 0.0 };
let xc = sc.x - kern;
resolve_tab(pl, &mut sc.pending_tab, &mut sc.xs, sc.c0, xc, &mut sc.x);
}
if sc.j >= self.n && sc.end != LineEnd::Wrap && !matches!(sc.end, LineEnd::LineBreak | LineEnd::PageBreak | LineEnd::ColumnBreak) {
@@ -454,8 +455,8 @@ impl<'e> Breaker<'e> {
let hyphen = (sc.end == LineEnd::Wrap && c1 > c0 && pl.hyph_after.binary_search(&((c1 - 1) as u32)).is_ok())
.then(|| pl.clusters.get(c1 - 1).map(|c| hyphen_glyph(pl, c.style, &mut self.hcache)))
.flatten();
let end_x = match (sc.xs.last(), c1.checked_sub(1).and_then(|k| pl.clusters.get(k))) {
(Some(lx), Some(c)) => lx + c.adv + hyphen.map_or(0.0, |h| h.2),
let end_x = match (sc.xs.last(), c1.checked_sub(1).and_then(|k| pl.clusters.get(k).map(|c| (k, c)))) {
(Some(lx), Some((k, c))) => lx + c.adv - line_end_kern(pl, k) + hyphen.map_or(0.0, |h| h.2),
_ => sc.line_start_x,
};
sc.xs.push(end_x);
@@ -951,11 +952,9 @@ impl Scan {
self.x += w;
}
_ => {
// A right tab's room grows from nothing with its text (a tab moved on from the
// line before may still hold the width it had there).
if stop.align == TabAlign::Right
&& let Some(c) = pl.clusters.get_mut(j)
{
// Its room grows from nothing with its text (a tab moved on from the line before
// may still hold the width it had there).
if let Some(c) = pl.clusters.get_mut(j) {
c.adv = 0.0;
}
self.pending_tab = Some((j, stop, self.x));
@@ -1096,7 +1095,7 @@ impl Scan {
self.word_from = if c.kind == ClKind::Space { self.x - c.adv } else { self.x };
} else if self.hyph_ok
&& !pl.clusters.get(j + 1).is_some_and(|n| n.kind == ClKind::Text && n.g1 <= n.g0)
&& self.x + hyphen_glyph(pl, c.style, &mut bk.hcache).2 <= self.right_edge + shrink + 0.01
&& self.x - line_end_kern(pl, j) + hyphen_glyph(pl, c.style, &mut bk.hcache).2 <= self.right_edge + shrink + 0.01
{
self.last_break = Some(j);
}
+5 -4
View File
@@ -306,6 +306,7 @@ impl<'a> Shaped<'a> {
big.font = f.clone();
big.font_cs = f.clone();
big.font_ea = Some(f.clone());
big.font_ea_theme = None;
}
let before = self.b.clusters.len();
self.b.shape(first, 0, &Arc::new(big), None);
@@ -663,9 +664,9 @@ fn shown_text(cx: &Cx) -> Option<String> {
Some(shown)
}
/// Each run's end byte and the installed East Asian font (`w:eastAsia`) it names, `None` when it
/// names none or one that isn't installed. Empty when `wanted` is false or the text is ASCII, which
/// has no East Asian characters to look the fonts up for.
/// Each run's end byte and the installed East Asian font (`w:eastAsiaTheme` over `w:eastAsia`)
/// it resolves to, `None` when none is resolved or it isn't installed. Empty when `wanted` is
/// false or the text is ASCII, which has no East Asian characters to look the fonts up for.
fn installed_east_asian_fonts(cx: &Cx, wanted: bool) -> Vec<(usize, Option<wordcraft_fonts::FaceRef>)> {
if !wanted || cx.p.text.is_ascii() {
return Vec::new();
@@ -673,7 +674,7 @@ fn installed_east_asian_fonts(cx: &Cx, wanted: bool) -> Vec<(usize, Option<wordc
cx.p.run_ranges()
.map(|(range, props)| {
let rc = cx.res.char(props);
let face = rc.font_ea.as_deref().filter(|f| !f.trim().is_empty()).map(|f| wordcraft_fonts::word::resolve(f, rc.bold, rc.italic));
let face = super::chars::east_asian_font(cx.env.doc, &rc).map(|f| wordcraft_fonts::word::resolve(f, rc.bold, rc.italic));
(range.end, face.filter(|r| !r.substituted).map(|r| r.face))
})
.collect()
+29 -10
View File
@@ -333,9 +333,26 @@ pub fn autofit_widths(cols: &[(f32, f32)], avail: f32) -> Vec<f32> {
cols.iter().map(|c| c.0 + (c.1 - c.0) * k).collect()
}
/// The first cell's left margin: how far its text sits inside the table's edge.
pub(crate) fn first_cell_left_margin(ctx: &Ctx, t: &Table) -> f32 {
first_cell_left_margin_in(t, default_margins(t, table_style(ctx, t).as_ref()))
/// How far left of its offset (`w:tblpX`) a floating table placed by one has its edge. Before
/// Word 2013 layout the first cell's text is at the offset, moved by the table's indent; from it
/// the edge is, moved in by half its left border, the indent ignored (measured in Word for
/// Windows).
pub(crate) fn float_offset_shift(ctx: &Ctx, t: &Table) -> f32 {
let style = table_style(ctx, t);
if ctx.doc.settings.compat_mode < 15 {
first_cell_left_margin_in(t, default_margins(t, style.as_ref())) - t.props.indent.unwrap_or(0.0)
} else {
-half_edge_border(t, &table_borders(t, style.as_ref()))
}
}
/// Half the left border of a table's first cell, which Word (from mode 15) moves the table in by:
/// the cell's own border, else its row's `w:tblPrEx`, else the table's (`borders`, with its style's).
fn half_edge_border(t: &Table, borders: &Borders) -> f32 {
let row = t.rows.first();
let own = row.and_then(|r| r.cells.first()).and_then(|c| c.props.borders.and_then(|b| b.left));
let exception = row.and_then(|r| r.props.exceptions.as_ref()).and_then(|e| e.borders).and_then(|b| b.left);
own.or(exception).or(borders.left).filter(Border::is_visible).map_or(0.0, |b| b.width.clamp(0.0, 12.0) / 2.0)
}
fn first_cell_left_margin_in(t: &Table, def: [f32; 4]) -> f32 {
@@ -575,17 +592,15 @@ fn table_frame(ctx: &mut Ctx, t: &Table, avail: f32, depth: usize, style: Option
let margins_def = default_margins(t, style);
let indent = t.props.indent.unwrap_or(0.0);
let tborders = table_borders(t, style);
let first_cell = t.rows.first().and_then(|r| r.cells.first());
// A right-to-left table (`w:bidiVisual`) mirrors: its first column stands at the right, its
// start alignment and indent are measured from the right margin, and each cell's start
// (left) margin and border are on its right.
// (left) border is drawn on its right (cell margins stay on the sides they name).
let rtl = t.props.bidi_visual;
// How far in from the start margin the table's edge sits when it is start-aligned.
let start_offset = if ctx.doc.settings.compat_mode >= 15 {
// The border is centred on the edge, so half of it sits outside: Word moves the table in
// by that half.
let border = first_cell.and_then(|c| c.props.borders.and_then(|b| b.left)).or(tborders.left);
indent + border.filter(Border::is_visible).map_or(0.0, |b| b.width.clamp(0.0, 12.0) / 2.0)
indent + half_edge_border(t, &tborders)
} else {
indent - first_cell_left_margin_in(t, margins_def)
};
@@ -753,9 +768,13 @@ fn layout_table_rows(ctx: &mut Ctx, story: StoryRef, t: &Table, path: &[u32], av
} else if turn.is_turned() {
collapsed = false;
// Turned text: its lines run along the cell's height. An exact row height sets
// their length, and a minimum height does when the lines fit across the column;
// otherwise they get the length the text needs unwrapped and the row grows to fit
// (the second pass lays them out again if the row ends up taller).
// their length, and a minimum height (`AtLeast`, or the combined minimum of a
// vertical merge) does when the lines fit across the column; otherwise they get
// the length the text needs unwrapped and the row grows to fit (the second pass
// lays them out again if the row ends up taller). Checked in Word (#6528): in an
// "At least" row, turned text wraps to the minimum height instead of growing the
// row, and a word longer than that minimum runs past the row (tested at 0.3 cm)
// without growing it.
let snap = (ctx.counters.clone(), ctx.eq_count);
let merged = merged_min_height(t, ri, g);
let preferred = merged.or(row.props.height.filter(|h| h.is_finite() && *h > 0.0)).map(|h| h.clamp(4.0, TURNED_LIMIT));
+7 -5
View File
@@ -207,8 +207,9 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
let mut tl = table::layout_table(ctx, StoryRef::Body, t, &[block as u32], width, 1);
if let Some(f) = t.props.float.filter(|_| !pb.web) {
// Before Word 2013 layout (compatibility mode 15) an offset places the first cell's text,
// so the edge sits a cell margin further out.
let legacy = if ctx.doc.settings.compat_mode < 15 { table::first_cell_left_margin(ctx, t) } else { 0.0 };
// so the edge sits a cell margin further out (and the indent further); from it the edge,
// half its border in.
let legacy = table::float_offset_shift(ctx, t);
let h: f32 = tl.rows.iter().map(|r| r.height).sum();
if h <= pb.uncapped_bottom() - pb.top + 0.01 {
place_floating_table(ctx, pb, &tl, &f, legacy, block, body_top);
@@ -400,11 +401,12 @@ fn place_floating_table(ctx: &mut Ctx, pb: &mut PageBuilder, tl: &table::TableLa
let x = float_table_x(pb, w, f, legacy, ctx.mirror);
let mut obstacles = if f.overlap { Vec::new() } else { header_table_areas(ctx, pb) };
obstacles.extend_from_slice(&pb.float_tables);
// Moved below another, it keeps its distance from the text's edge, half its border in.
let r = clear_of_float_tables(
Rect::new(x, align_in(v_area, f.y, h, f.v_align), w, h),
f,
ctx.doc.settings.compat_mode >= 15,
h_area.0,
h_area.0 - legacy,
&obstacles,
);
// Like Word, a table that doesn't fit below the text before it moves to the next page with
@@ -485,8 +487,8 @@ fn float_table_h_area(pb: &PageBuilder, f: &TableFloat, mirror: bool) -> (f32, f
}
}
/// A floating table's left edge on the page (`legacy`: the first cell's left margin before Word
/// 2013 layout, when an offset places the cell's text).
/// A floating table's left edge on the page (`legacy`: how far left of an offset its edge stands,
/// [`table::float_offset_shift`]).
fn float_table_x(pb: &PageBuilder, w: f32, f: &TableFloat, legacy: f32, mirror: bool) -> f32 {
let align = PageFrame::h_align(Some(&page_frame(pb, mirror)), f.h_align);
let x = align_in(float_table_h_area(pb, f, mirror), f.x, w, align);
+222
View File
@@ -2058,6 +2058,29 @@ fn right_tab_past_the_right_indent_takes_its_number_up_to_the_stop() {
assert!(close > 0, "no entry whose text ends within a digit of the indent");
}
/// A centre tab moved onto the next line with its text starts with no room there, as a right
/// tab does: it doesn't keep the width it had on the line before, so the text is centred on the
/// stop (#8683).
#[test]
fn a_centre_tab_moved_to_the_next_line_centres_its_text_on_the_stop() {
use wordcraft_doc::props::{TabAlign, TabLeader, TabStop};
crate::test_fonts();
for n in 74..=83 {
let text = format!("{}\tWXYZWXWXYZ1.5", "x".repeat(n));
let len = text.chars().count();
let mut d = Document::from_text(&text);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.tabs = Some(vec![TabStop { pos: 460.0, align: TabAlign::Center, leader: TabLeader::None }]);
})
.unwrap();
let l = lay(&d);
let start = l.caret(&Pos::body(0, n + 1)).unwrap().x;
let end = l.caret(&Pos::body(0, len)).unwrap().x;
let mid = (start + end) / 2.0;
assert!((mid - (72.0 + 460.0)).abs() < 0.5, "n={n}: text after the centre tab is centred at {mid}, expected {}", 72.0 + 460.0);
}
}
/// A left tab whose only stop is past the right indent wraps; on the next line it still can't
/// reach that stop, so it takes no room there and its text starts at the indent instead of
/// going to a line of its own.
@@ -3871,6 +3894,48 @@ fn a_text_box_skips_the_min_height_probe_for_turned_text() {
assert!(b.h > 80.0, "and so it runs on past the minimum height: {b:?}");
}
/// A single word longer than an at-least row's minimum height (0.3 cm / ~8.5 pt) runs past
/// the row along its length instead of growing the row, as long as the wrapped pieces fit across
/// the column.
#[test]
fn a_word_longer_than_min_height_does_not_grow_an_at_least_row() {
use wordcraft_doc::props::HeightRule;
crate::test_fonts();
let min_h = 8.5;
for turn in [TextDirection::Up, TextDirection::Down] {
let mut d = Document::from_text("After");
let mut t = Table::new(1, 1, 160.0);
t.props.style = None;
t.rows[0].props.height = Some(min_h);
t.rows[0].props.height_rule = HeightRule::AtLeast;
t.rows[0].cells[0].props.text_direction = turn;
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("WWWW", Default::default()))];
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let (rect, clip) = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, clip, cell: 0, .. } => Some((*rect, *clip)),
_ => None,
})
.unwrap();
assert!((rect.h - min_h).abs() < 0.01, "{turn:?}: cell grew past min height {min_h}: {rect:?}");
assert!(!clip, "{turn:?}: an at-least row does not clip overflowing text");
let extent = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Lines { para, l0, l1, path, .. } if path.0 == [0, 0, 0, 0] => {
Some(para.lines.get(*l0..*l1).unwrap_or(&[]).iter().filter_map(|line| line.xs.last().copied()).fold(0.0f32, f32::max))
}
_ => None,
})
.unwrap();
assert!(extent > min_h, "{turn:?}: word should run past the min height {min_h}, got {extent}");
}
}
#[test]
fn turned_text_wraps_to_merged_rows_height() {
use wordcraft_doc::props::{HeightRule, VMerge};
@@ -19106,6 +19171,72 @@ fn turned_cell_float_keeps_its_along_text_offset() {
}
}
/// #6567: when a wrapping float (such as a page-tall `wrapTopAndBottom` frame) pushes its anchor
/// paragraph's first line to the bottom of the page, sibling paragraph-relative floats with
/// negative vertical offsets are measured from the displaced paragraph line rather than placed
/// above the page from the pre-wrap origin.
#[test]
fn negative_offset_floats_in_a_paragraph_pushed_down_by_a_wrapping_float_stay_on_the_page() {
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
let mut doc = Document::from_text("");
doc.last_section.page_w = 595.3;
doc.last_section.page_h = 841.9;
let mut para = Paragraph::new();
let title = Float {
wrap: Wrap::InFrontOfText,
h_rel: Anchor::Margin,
h_align: Some(FloatAlign::Center),
v_rel: Anchor::Paragraph,
y: -652.55,
..Default::default()
};
let row = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 36.0, y: -460.75, ..Default::default() };
let frame = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: -43.11, ..Default::default() };
para.insert_object(para.len(), rect_shape(378.5, 105.75, title), &Default::default()).unwrap();
para.insert_object(para.len(), rect_shape(194.55, 38.45, row), &Default::default()).unwrap();
para.insert_object(para.len(), rect_shape(556.46, 802.52, frame), &Default::default()).unwrap();
doc.body = vec![wordcraft_doc::para_block(para)];
let l = lay(&doc);
assert_eq!(l.pages.len(), 1);
let placed = shapes(&l.pages[0].items);
assert_eq!(placed.len(), 3, "{placed:?}");
let frame_rect = placed.iter().find(|r| (r.h - 802.52).abs() < 0.1).unwrap();
let title_rect = placed.iter().find(|r| (r.h - 105.75).abs() < 0.1).unwrap();
let row_rect = placed.iter().find(|r| (r.h - 38.45).abs() < 0.1).unwrap();
let line_top = first_line_top(&l.pages[0].items);
assert!((frame_rect.y - (72.0 - 43.11)).abs() < 0.5, "frame stays at the top of the page: {frame_rect:?}");
assert!((title_rect.y - (line_top - 652.55)).abs() < 0.5, "title measured from displaced line {line_top}: {title_rect:?}");
assert!((row_rect.y - (line_top - 460.75)).abs() < 0.5, "row measured from displaced line {line_top}: {row_rect:?}");
assert!(title_rect.y > frame_rect.y && row_rect.bottom() < frame_rect.bottom(), "{placed:?}");
}
/// #6567 review: a wrapping float above its paragraph that would land on the first line when
/// placed from it again isn't moved there: that line was laid out without it in the way.
#[test]
fn a_wrapping_float_isnt_moved_onto_a_first_line_laid_out_without_it() {
crate::test_fonts();
use wordcraft_doc::para::{Anchor, Float, Wrap};
let mut doc = Document::from_text("Words in the first line of the paragraph.");
let frame = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
let square = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: -10.0, ..Default::default() };
doc.insert_object(&Pos::body(0, 0), rect_shape(150.0, 50.0, square), &Default::default()).unwrap();
doc.insert_object(&Pos::body(0, 0), rect_shape(200.0, 100.0, frame), &Default::default()).unwrap();
let l = lay(&doc);
let items = &l.pages[0].items;
let square = shapes(items).into_iter().find(|r| (r.h - 50.0).abs() < 0.1).unwrap();
let (x, y, height) = items
.iter()
.find_map(|i| match i {
Placed::Lines { x, y, para, story: StoryRef::Body, .. } => para.lines.first().map(|l| (*x + l.left, *y, l.height)),
_ => None,
})
.unwrap();
assert!(y > 72.0 + 99.0, "the frame pushes the first line down: {y}");
let overlaps = square.y < y + height && square.bottom() > y && square.x < x + 1.0 && square.right() > x;
assert!(!overlaps, "the float {square:?} covers the first line's text at ({x}, {y})");
}
/// A caption kept with the next paragraph (`keepNext`) before a table goes over with the table
/// when the table's repeated header row and the start of its first row don't fit under it, as in
/// Word, instead of staying alone at the foot of the page: keep with next asked a table for a
@@ -19438,6 +19569,97 @@ fn header_text_covers_the_whole_band_of_centred_and_right_lines() {
}
}
/// A floating table placed by an offset from the margin (measured in Word for Windows): before
/// Word 2013 its first cell's text is at the offset, moved by `w:tblInd`; from it its edge is,
/// moved in by half its left border, and `w:tblInd` doesn't move it.
#[test]
fn a_floating_table_placed_by_an_offset_takes_its_indent_before_word_2013_only() {
crate::test_fonts();
use wordcraft_doc::para::Anchor;
use wordcraft_doc::props::TableFloat;
let text_x = |mode: u32, indent: Option<f32>| {
let mut t = Table::new(1, 2, 300.0);
t.props.fixed = true;
t.props.indent = indent;
t.props.cell_margins = Some([0.0, 5.4, 0.0, 5.4]);
t.props.borders = Some(wordcraft_doc::props::Borders::all(wordcraft_doc::props::Border::single(0.5)));
t.props.float = Some(TableFloat { h_rel: Anchor::Margin, v_rel: Anchor::Paragraph, ..Default::default() });
for c in &mut t.rows[0].cells {
c.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Cell", Default::default()))];
}
let mut d = Document::from_text("Below");
d.settings.compat_mode = mode;
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
lay(&d).pages[0]
.items
.iter()
.find_map(|i| match i {
Placed::Lines { path, x, .. } if path.0 == [0, 0, 0, 0] => Some(*x),
_ => None,
})
.expect("the first cell's text")
};
let margin = 72.0;
assert!((text_x(14, None) - margin).abs() < 0.01, "mode 14: {}", text_x(14, None));
assert!((text_x(14, Some(-5.4)) - (margin - 5.4)).abs() < 0.01, "mode 14, indent: {}", text_x(14, Some(-5.4)));
assert!((text_x(15, None) - (margin + 0.25 + 5.4)).abs() < 0.01, "mode 15: {}", text_x(15, None));
assert!((text_x(15, Some(-5.4)) - (margin + 0.25 + 5.4)).abs() < 0.01, "mode 15, indent: {}", text_x(15, Some(-5.4)));
}
/// From Word 2013 a table moves in by half its first cell's left border, and a first row's
/// `w:tblPrEx` border is that border (measured in Word for Windows): with an 8 pt table border and
/// a 2 pt exception the first cell's text is at 78.38, 1 pt in; without the exception at 81.38.
/// The same inline and floating, and for every row.
#[test]
fn a_first_rows_exception_border_is_the_half_border_a_table_moves_in_by() {
crate::test_fonts();
use wordcraft_doc::para::Anchor;
use wordcraft_doc::props::TableFloat;
let text_x = |float: bool, exception: bool| {
let mut t = Table::new(2, 2, 300.0);
t.props.fixed = true;
t.props.style = None;
t.props.cell_margins = Some([0.0, 5.4, 0.0, 5.4]);
t.props.borders = Some(Borders { left: Some(Border::single(8.0)), ..Default::default() });
if float {
t.props.float = Some(TableFloat { h_rel: Anchor::Margin, v_rel: Anchor::Paragraph, ..Default::default() });
}
if exception {
t.rows[0].props.exceptions = Some(Box::new(wordcraft_doc::props::TableProps {
borders: Some(Borders { left: Some(Border::single(2.0)), ..Default::default() }),
..Default::default()
}));
}
for r in &mut t.rows {
for c in &mut r.cells {
c.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Cell", Default::default()))];
}
}
let mut d = Document::from_text("Below");
d.settings.compat_mode = 15;
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let at = |row: u32| {
l.pages[0]
.items
.iter()
.find_map(|i| match i {
Placed::Lines { path, x, .. } if path.0 == [0, row, 0, 0] => Some(*x),
_ => None,
})
.expect("the first cell's text")
};
(at(0), at(1))
};
for float in [false, true] {
for (exception, want) in [(false, 72.0 + 4.0 + 5.4), (true, 72.0 + 1.0 + 5.4)] {
let (first, second) = text_x(float, exception);
assert!((first - want).abs() < 0.01, "float {float}, exception {exception}: {first}");
assert!((second - want).abs() < 0.01, "float {float}, exception {exception}, row 2: {second}");
}
}
}
#[test]
fn reading_layout_keeps_a_negatively_indented_table_in_the_column() {
crate::test_fonts();
+38
View File
@@ -161,6 +161,44 @@ fn an_east_asian_font_without_ideographs_turns_it_off() {
assert_eq!(gaps(&d), [0.0, q, 0.0, after(&d, 7), q, after(&d, 11), 0.0], "a font that isn't installed");
}
/// A `w:eastAsiaTheme` slot on a style or run takes precedence over an inherited named East Asian
/// font (`w:eastAsia`) without ideographs: Word draws the ideographs in the theme face instead, so
/// it still keeps the automatic space unless the theme slot itself names an installed font without
/// ideographs. Conversely, a named `w:eastAsia` on a run replaces an inherited theme slot.
#[test]
fn east_asian_theme_slot_overrides_inherited_named_font() {
crate::test_fonts();
use wordcraft_doc::props::ThemeFont;
// Base default names an installed font without ideographs (`Source Serif 4`).
// A style or run setting `minorEastAsia` overrides it: with no non-CJK `a:ea` face, spaces stay.
let mut d = Document::from_text("法院94年A字");
Arc::make_mut(&mut d.styles).default_chr.font_ea = Some("Source Serif 4".to_string());
let len = para0(&mut d).text.len();
para0(&mut d).format(0, len, &|c: &mut CharProps| c.font_ea_theme = Some(ThemeFont::MinorEastAsia)).unwrap();
let q = quarter(&d);
assert_eq!(gaps(&d), [0.0, q, 0.0, after(&d, 7), q, after(&d, 11), 0.0], "theme slot overrides inherited font_ea");
// When the theme's `a:ea` face (in `wordcraft:theme.fonts`) itself is an installed font without
// ideographs, the space is suppressed.
let mut themed_no_cjk = d.clone();
themed_no_cjk.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tSource Serif 4\n".to_vec()));
assert!(gaps(&themed_no_cjk).iter().all(|g| *g == 0.0), "theme a:ea without ideographs: {:?}", gaps(&themed_no_cjk));
// A Latin theme slot (`minorHAnsi`) resolves to `settings.minor_font`: if installed and lacking
// ideographs, it also suppresses the space.
let mut latin_slot = d.clone();
latin_slot.settings.minor_font = "Source Serif 4".to_string();
para0(&mut latin_slot).format(0, len, &|c: &mut CharProps| c.font_ea_theme = Some(ThemeFont::MinorHAnsi)).unwrap();
assert!(gaps(&latin_slot).iter().all(|g| *g == 0.0), "Latin theme slot without ideographs: {:?}", gaps(&latin_slot));
// A named `w:eastAsia` without `w:eastAsiaTheme` on a run overrides an inherited theme slot.
let mut overridden = Document::from_text("法院94年A字");
Arc::make_mut(&mut overridden.styles).default_chr.font_ea_theme = Some(ThemeFont::MinorEastAsia);
para0(&mut overridden).format(0, len, &|c: &mut CharProps| c.font_ea = Some("Source Serif 4".to_string())).unwrap();
assert!(gaps(&overridden).iter().all(|g| *g == 0.0), "named font_ea overrides inherited theme slot: {:?}", gaps(&overridden));
}
#[test]
fn a_field_result_is_classed_by_the_text_it_shows() {
crate::test_fonts();
+2 -1
View File
@@ -106,7 +106,8 @@ fn cell_letterhead_pulls_an_outside_picture_to_the_outer_left_edge() {
}
}
/// Confinement follows the particular cell, including asymmetric margins mirrored for RTL.
/// Confinement follows the particular cell, including asymmetric margins and RTL column
/// mirroring (cell margins themselves stay on the sides they name).
#[test]
fn cell_float_outer_edges_include_asymmetric_and_mirrored_margins() {
for rtl in [false, true] {
+37
View File
@@ -3,6 +3,7 @@
#[allow(unused_imports)]
use crate::*;
use wordcraft_doc::Pos;
use wordcraft_doc::props::LineSpacing;
use wordcraft_doc::section::{DocGrid, DocGridType};
@@ -97,3 +98,39 @@ fn character_grid_places_east_asian_text_on_the_pitch() {
}
}
}
#[test]
fn an_exact_character_grid_line_fits_all_its_cells_with_kerning() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let mut grid = with_grid(text, DocGridType::SnapToChars, 0);
let styles = std::sync::Arc::make_mut(&mut grid.styles);
styles.default_chr.font = Some("Inter".into());
styles.default_chr.kern = Some(1.0);
let set_width = |doc: &mut Document, width: f32| {
let indent = doc.last_section.text_width() - width;
doc.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent)).unwrap();
};
// In proportional text the fifth letter still needs its unkerned width at a line break.
let mut plain = grid.clone();
plain.last_section.doc_grid = None;
let wide = lay(&plain);
let para = wide.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let paired: f32 = para.clusters[..5].iter().map(|c| c.adv).sum();
let kern = para.clusters[4].kern;
assert!(kern < -0.02, "the test font must kern the pair across the break");
set_width(&mut plain, paired - kern / 2.0);
assert_eq!(super::body_lines(&lay(&plain), text)[0], "AVAV");
let size = para::Grid::of(&grid, &grid.last_section).font_size;
grid.last_section.doc_grid.as_mut().unwrap().char_space = DocGrid::char_space_for(20.0, size);
let pitch = grid.last_section.grid_char_pitch(size).unwrap();
set_width(&mut grid, 5.0 * pitch);
for kern in [0.0, 1.0] {
std::sync::Arc::make_mut(&mut grid.styles).default_chr.kern = Some(kern);
let got = super::body_lines(&lay(&grid), text);
assert_eq!(got[0], "AVAVA", "kerning threshold {kern}: {got:?}");
}
}
+237 -9
View File
@@ -28,13 +28,13 @@ fn a_word_broken_by_letters_ends_without_its_kerning_pair() {
assert_eq!(got.first().map(String::as_str), Some("AVAVA"), "{got:?}");
}
/// Inter under the family name "Kernx" with its `GPOS` hidden and an old-style `kern` table that
/// kerns "AV" by `units` (and nothing else): a shaper splits such a pair between the two letters,
/// half in the first one's advance and half in the second one's advance and offset.
fn legacy_kern_family(units: i16) -> &'static str {
const FAMILY: &str = "Kernx";
/// Inter under `family` (a 5-byte name) with its `GPOS` hidden and an old-style `kern` table
/// that kerns `(left, right)` by `units` (and nothing else): a shaper splits such a pair between
/// the two glyphs, half in the first one's advance and half in the second one's advance and offset.
fn legacy_kern_family(family: &'static str, left: char, right: char, units: i16) -> &'static str {
assert_eq!(family.len(), "Inter".len());
let inter = wordcraft_fonts::word::resolve("Inter", false, false).face;
let (a, v) = (inter.glyph_for('A') as u16, inter.glyph_for('V') as u16);
let (a, v) = (inter.glyph_for(left) as u16, inter.glyph_for(right) as u16);
let src = inter.data().to_vec();
let u16_at = |d: &[u8], o: usize| u16::from_be_bytes([d[o], d[o + 1]]) as usize;
let u32_at = |d: &[u8], o: usize| u32::from_be_bytes([d[o], d[o + 1], d[o + 2], d[o + 3]]) as usize;
@@ -76,7 +76,7 @@ fn legacy_kern_family(units: i16) -> &'static str {
let name = tables.iter().take_while(|t| &t.0 != b"name").map(|t| t.1.len().div_ceil(4) * 4).sum::<usize>() + 12 + 16 * n;
let len = tables.iter().find(|t| &t.0 == b"name").map_or(0, |t| t.1.len());
let wide = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(wide("Inter"), wide(FAMILY)), (b"Inter".to_vec(), FAMILY.as_bytes().to_vec())] {
for (from, to) in [(wide("Inter"), wide(family)), (b"Inter".to_vec(), family.as_bytes().to_vec())] {
for i in name..name + len - from.len() {
if data[i..i + from.len()] == from[..] {
data[i..i + from.len()].copy_from_slice(&to);
@@ -84,7 +84,7 @@ fn legacy_kern_family(units: i16) -> &'static str {
}
}
wordcraft_fonts::FontDb::global().add_font(data);
FAMILY
family
}
/// A letter ending a line whose kerning pair with the letter before it the shaper split between
@@ -95,7 +95,7 @@ fn legacy_kern_family(units: i16) -> &'static str {
fn a_letter_ending_a_line_keeps_its_pair_with_the_letter_before() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let family = legacy_kern_family(-300);
let family = legacy_kern_family("Kernx", 'A', 'V', -300);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
@@ -158,3 +158,231 @@ fn a_ligatures_kerning_pair_sits_on_its_last_cluster() {
assert_eq!(p3.clusters[1].kern, 0.0);
assert!(p3.clusters[2].kern < -0.2, "last cluster of \"ffi\" carries pair with \"V\": {}", p3.clusters[2].kern);
}
fn first_para(d: &Document) -> Arc<ParaLayout> {
lay(d).pages.into_iter().flat_map(|p| p.items).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap()
}
#[test]
fn a_wrapped_line_end_caret_and_alignment_drop_the_line_end_pair() {
let text = "AVAVAVAVAVAVAVAVAVAV";
let doc = |indent_right: f32, align: Align| {
let mut d = Document::from_text(text);
Arc::make_mut(&mut d.styles).default_chr.kern = Some(1.0);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(align);
})
.unwrap();
d
};
let base = first_para(&doc(0.0, Align::Left));
let kern = base.clusters[4].kern;
assert!(kern < -0.1, "the test font kerns \"AV\": {kern}");
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_last = base.clusters[4].adv - kern;
// Slight slack past the five unkerned letters so right and centre alignments move the line.
let slack = 6.0;
let indent_right = 468.0 - (alone + slack);
let left = first_para(&doc(indent_right, Align::Left));
let l0 = &left.lines[0];
assert_eq!(l0.c1, 5);
assert!((l0.end_x() - alone).abs() < 0.01, "end_x {} should match unkerned {alone}, not {paired}", l0.end_x());
assert!((left.x_of(0, l0.stop).unwrap() - alone).abs() < 0.01);
let right = first_para(&doc(indent_right, Align::Right));
let r0 = &right.lines[0];
assert_eq!(r0.c1, 5);
let r_end = r0.cl_left(4).unwrap() + unkerned_last;
assert!((r_end - r0.right).abs() < 0.01, "right-aligned unkerned end {r_end} should sit at right edge {}", r0.right);
let center = first_para(&doc(indent_right, Align::Center));
let c0 = &center.lines[0];
assert_eq!(c0.c1, 5);
let left_gap = c0.cl_left(0).unwrap() - c0.left;
let right_gap = c0.right - (c0.cl_left(4).unwrap() + unkerned_last);
assert!((left_gap - right_gap).abs() < 0.01, "centred gaps differ: left {left_gap} vs right {right_gap}");
}
#[test]
fn a_positive_kerning_pair_at_line_end_stays_inside_the_right_edge() {
crate::test_fonts();
let text = "AVAVAVAVAVAVAVAVAVAV";
let family = legacy_kern_family("Kernp", 'A', 'V', 300);
let doc = |indent_right: f32, align: Align| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(align);
})
.unwrap();
d
};
let base = first_para(&doc(0.0, Align::Left));
let kern = base.clusters[4].kern;
assert!(kern > 0.5, "the test font positively kerns \"AV\": {kern}");
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_last = base.clusters[4].adv - kern;
let width = (paired + alone) / 2.0;
let indent_right = 468.0 - width;
let left = first_para(&doc(indent_right, Align::Left));
let l0 = &left.lines[0];
assert_eq!(l0.c1, 5);
assert!(l0.end_x() <= l0.right + 0.01, "end_x {} ran past right edge {}", l0.end_x(), l0.right);
assert!((l0.end_x() - alone).abs() < 0.01);
let right = first_para(&doc(indent_right, Align::Right));
let r0 = &right.lines[0];
assert_eq!(r0.c1, 5);
assert!(r0.cl_left(0).unwrap() > 0.01, "right-aligned line failed to shift right");
assert!((r0.cl_left(4).unwrap() + unkerned_last - r0.right).abs() < 0.01);
let center = first_para(&doc(indent_right, Align::Center));
let c0 = &center.lines[0];
assert_eq!(c0.c1, 5);
let left_gap = c0.cl_left(0).unwrap() - c0.left;
let right_gap = c0.right - (c0.cl_left(4).unwrap() + unkerned_last);
assert!(left_gap > 0.01 && (left_gap - right_gap).abs() < 0.01, "centred gaps: left {left_gap} vs right {right_gap}");
}
#[test]
fn a_justified_line_adjusts_spaces_without_the_line_end_pair() {
crate::test_fonts();
// Distributed alignment stretches gaps across clusters directly using `content_end`.
let text = "AVAVAVAVAVAVAVAVAVAV";
for (family, units) in [("Kerdn", -300i16), ("Kerdp", 300i16)] {
let family = legacy_kern_family(family, 'A', 'V', units);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(Align::Distribute);
})
.unwrap();
d
};
let base = first_para(&doc(0.0));
let kern = base.clusters[4].kern;
assert!((kern.signum() as i16) == units.signum(), "{family}: {kern}");
let paired: f32 = base.clusters[..5].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_last = base.clusters[4].adv - kern;
let width = if units < 0 { alone + 4.0 } else { (paired + alone) / 2.0 };
let para = first_para(&doc(468.0 - width));
let l0 = &para.lines[0];
assert_eq!(l0.c1, 5, "{family}: expected wrap after 5th letter");
assert!(l0.cl_left(4).unwrap() > base.clusters[..4].iter().map(|c| c.adv).sum::<f32>() + 0.01);
let end = l0.cl_left(4).unwrap() + unkerned_last;
assert!((end - l0.right).abs() < 0.01, "{family}: distributed end {end} should meet right edge {}", l0.right);
assert!((l0.end_x() - l0.right).abs() < 0.01);
}
// Justified line with spaces breaking mid-word (`word_wrap = false`): both stretching and
// shrinking adjust spaces against the unkerned line end.
let j_text = "a b AVAVAVAVAVAVAVAVAVAV";
for (family, units) in [("Kerjn", -300i16), ("Kerjp", 300i16)] {
let family = legacy_kern_family(family, 'A', 'V', units);
let doc = |indent_right: f32| {
let mut d = Document::from_text(j_text);
d.settings.compat_mode = wordcraft_doc::COMPAT_MODE_CURRENT;
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| {
p.indent_right = Some(indent_right);
p.align = Some(Align::Justify);
p.word_wrap = Some(false);
})
.unwrap();
d
};
let base = first_para(&doc(0.0));
// "a b AVAVA" is clusters 0..9; cluster 8 is 'A', cluster 9 is 'V'.
let kern = base.clusters[8].kern;
assert!((kern.signum() as i16) == units.signum(), "{family}: {kern}");
let paired: f32 = base.clusters[..9].iter().map(|c| c.adv).sum();
let alone = paired - kern;
let unkerned_a = base.clusters[8].adv - kern;
let width = if units < 0 { alone + 4.0 } else { (paired + alone) / 2.0 };
let para = first_para(&doc(468.0 - width));
let l0 = &para.lines[0];
assert_eq!(l0.c1, 9, "{family}: expected wrap after 9th cluster");
let space_w = l0.cl_left(2).unwrap() - l0.cl_left(1).unwrap();
assert!(space_w > base.clusters[1].adv + 0.01, "{family}: spaces should widen, got {space_w} vs {}", base.clusters[1].adv);
let end = l0.cl_left(8).unwrap() + unkerned_a;
assert!((end - l0.right).abs() < 0.01, "{family}: justified end {end} should meet right edge {}", l0.right);
assert!((l0.end_x() - l0.right).abs() < 0.01);
if units < 0 {
let shrunk = first_para(&doc(468.0 - (alone - 0.5)));
let s0 = &shrunk.lines[0];
assert_eq!(s0.c1, 9, "{family}: expected shrunk wrap after 9th cluster");
let s_space = s0.cl_left(2).unwrap() - s0.cl_left(1).unwrap();
assert!(s_space < base.clusters[1].adv - 0.01, "{family}: spaces should shrink, got {s_space} vs {}", base.clusters[1].adv);
let s_end = s0.cl_left(8).unwrap() + unkerned_a;
assert!((s_end - s0.right).abs() < 0.01, "{family}: shrunk end {s_end} should meet right edge {}", s0.right);
}
}
}
#[test]
fn auto_hyphenation_uses_the_unkerned_width_before_a_negative_pair() {
crate::test_fonts();
let text = "word consideration";
let family = legacy_kern_family("Kerhy", 'n', 's', -300);
let doc = |indent_right: f32| {
let mut d = Document::from_text(text);
d.settings.auto_hyphenation = true;
d.settings.hyphenation_zone = 0.0;
let st = Arc::make_mut(&mut d.styles);
st.default_chr.kern = Some(1.0);
st.default_chr.font = Some(family.into());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(0, 0), &|p| p.indent_right = Some(indent_right)).unwrap();
d
};
let base = first_para(&doc(0.0));
let k = *base
.hyph_after
.iter()
.find(|&&k| {
let i = k as usize;
text.get(base.clusters[i].start..base.clusters[i].end) == Some("n")
&& base.clusters.get(i + 1).and_then(|c| text.get(c.start..c.end)) == Some("s")
})
.expect("expected automatic hyphenation point at \"con-sideration\"");
let k = k as usize;
let kern = base.clusters[k].kern;
assert!(kern < -0.5, "the test font kerns \"ns\": {kern}");
let paired_no_hyph: f32 = base.clusters[..=k].iter().map(|c| c.adv).sum();
// Wide enough for "word con-" with room to spare so we can measure the hyphen advance.
let probe = first_para(&doc(468.0 - (paired_no_hyph + 12.0)));
assert_eq!(probe.lines[0].c1, k + 1);
let hyph_w = probe.lines[0].hyphen.expect("probe should hyphenate at \"con-\"").2;
let paired = paired_no_hyph + hyph_w;
let alone = paired - kern;
// Between the kerned and unkerned widths (plus hyphen): "con-" would overrun the margin
// once the "ns" pair is dropped, so the line must fall back to the earlier space.
let mid = first_para(&doc(468.0 - (paired + alone) / 2.0));
let m0 = &mid.lines[0];
assert!(m0.hyphen.is_none(), "hyphenated line {} overran right edge {}", m0.end_x(), m0.right);
assert_eq!(m0.stop, "word ".len(), "expected fallback to space break, got {:?}", &text[..m0.stop]);
// Wide enough for the unkerned letters plus hyphen: the break at "con-" fits inside the margin.
let fit = first_para(&doc(468.0 - (alone + 0.004)));
let f0 = &fit.lines[0];
assert_eq!(f0.c1, k + 1);
assert!(f0.hyphen.is_some());
assert!(f0.end_x() <= f0.right + 0.01, "end_x {} ran past right edge {}", f0.end_x(), f0.right);
assert!((f0.end_x() - alone).abs() < 0.01);
}
+3 -5
View File
@@ -137,12 +137,10 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
}
}
surface.finish();
for (annotation, tag_slot) in annotations {
if opts.tagged
&& let Some((para_idx, child_idx)) = tag_slot
{
for (annotation, tag) in annotations {
if opts.tagged {
let annot_id = kp.add_tagged_annotation(annotation);
ex.attach_link_annotation(para_idx, child_idx, annot_id);
ex.attach_link_annotation(tag, annot_id);
} else {
kp.add_annotation(annotation);
}
+38 -5
View File
@@ -18,6 +18,17 @@ mod objects;
pub(crate) use objects::ObjectLookup;
mod text;
/// Where a link annotation's `OBJR` attaches in the structure tree.
#[derive(Clone, Copy)]
pub(crate) enum LinkTag {
/// Inside an existing `Tag::Link` group at `(para, child)` in `Exporter::tags`, with
/// reading-order position `at` as fallback.
Group { para: usize, child: usize, at: (usize, usize) },
/// Outside any paragraph (for example a header or footer artifact), as its own `Link`
/// structure element placed at reading-order position `at`.
Standalone((usize, usize)),
}
pub(crate) struct LinkRect {
pub(crate) x0: f32,
pub(crate) y0: f32,
@@ -26,6 +37,8 @@ pub(crate) struct LinkRect {
pub(crate) target: String,
/// `(para_idx, child_idx)` in `Exporter::tags` for this link's `Tag::Link` group.
pub(crate) tag: Option<(usize, usize)>,
/// Reading-order position ([`TagEntry::at`]) where this link was drawn.
pub(crate) at: (usize, usize),
}
pub(crate) struct Exporter<'a> {
@@ -230,11 +243,21 @@ impl Exporter<'_> {
}
}
/// Insert a link annotation's `OBJR` identifier as the first child of its `Tag::Link` group.
pub(crate) fn attach_link_annotation(&mut self, para_idx: usize, child_idx: usize, annot_id: Identifier) {
if let Some(Node::Group(g)) = self.tags.get_mut(para_idx).and_then(|e| e.children.get_mut(child_idx)) {
/// Attach a link annotation's `OBJR` identifier to its `Tag::Link` group, or add a standalone
/// `Div -> Link` entry holding just the `OBJR` when the link has no paragraph group (such as
/// a link drawn inside a header or footer artifact).
pub(crate) fn attach_link_annotation(&mut self, tag: LinkTag, annot_id: Identifier) {
if let LinkTag::Group { para, child, .. } = tag
&& let Some(Node::Group(g)) = self.tags.get_mut(para).and_then(|e| e.children.get_mut(child))
{
g.children.insert(0, Node::Leaf(annot_id));
return;
}
let at = match tag {
LinkTag::Group { at, .. } | LinkTag::Standalone(at) => at,
};
let g = TagGroup::with_children(Tag::Link, vec![Node::Leaf(annot_id)]);
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], source: None, at });
}
/// One draw of a paragraph's line, tagged for what it is: text as the paragraph's content
@@ -303,7 +326,17 @@ impl Exporter<'_> {
let dopts = self.opts.display_options();
// What the items share (the authors' colours, the clipped cells) is worked out once per page.
let shown = ItemDisplay::new(self.doc, page);
for it in page.header.iter().chain(page.footer.iter()) {
self.at.1 = 0;
for it in &page.header {
let draws = shown.draws(it, &dopts);
self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| {
for d in &draws {
me.draw(s, d);
}
});
}
self.at.1 = usize::MAX;
for it in &page.footer {
let draws = shown.draws(it, &dopts);
self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| {
for d in &draws {
@@ -312,7 +345,7 @@ impl Exporter<'_> {
});
}
for (i, it) in page.items.iter().enumerate() {
self.at.1 = page.reading.get(i).copied().unwrap_or(i);
self.at.1 = page.reading.get(i).copied().unwrap_or(i).saturating_add(1).min(usize::MAX - 1);
let draws = shown.draws(it, &dopts);
match it {
Placed::Lines { story, path, para, .. } => {
+7 -3
View File
@@ -1,5 +1,5 @@
use super::{
Annotation, ClKind, DocPath, Exporter, Fit, HashMap, LineEnd, LinkAnnotation, Outline, OutlineNode, Placed, Point, StoryRef, Target,
Annotation, ClKind, DocPath, Exporter, Fit, HashMap, LineEnd, LinkAnnotation, LinkTag, Outline, OutlineNode, Placed, Point, StoryRef, Target,
XyzDestination, krilla, write,
};
@@ -62,13 +62,17 @@ impl Exporter<'_> {
}
}
pub(crate) fn annotations(&self, fit: Fit) -> Vec<(Annotation, Option<(usize, usize)>)> {
pub(crate) fn annotations(&self, fit: Fit) -> Vec<(Annotation, LinkTag)> {
let mut v = Vec::new();
for link in &self.links {
let ((x0, y0), (x1, y1)) = (fit.point(link.x0, link.y0), fit.point(link.x1, link.y1));
let Some(rect) = krilla::geom::Rect::from_ltrb(x0, y0, x1, y1) else { continue };
let Some(t) = self.link_target(&link.target) else { continue };
v.push((Annotation::new_link(LinkAnnotation::new(rect, t), Some(link.target.clone())), link.tag));
let tag = match link.tag {
Some((para, child)) => LinkTag::Group { para, child, at: link.at },
None => LinkTag::Standalone(link.at),
};
v.push((Annotation::new_link(LinkAnnotation::new(rect, t), Some(link.target.clone())), tag));
}
v
}
+2 -2
View File
@@ -178,7 +178,7 @@ impl Exporter<'_> {
if self.link_target(link).is_none() {
return;
}
let continues = self.links.last().is_some_and(|prev| self.link_run_continues(prev.tag));
let continues = self.links.last().is_some_and(|prev| prev.at == self.at && self.link_run_continues(prev.tag));
if let Some(prev) = self.links.last_mut()
&& prev.target == link
&& (prev.y0 - y0).abs() < 0.5
@@ -191,7 +191,7 @@ impl Exporter<'_> {
return;
}
if self.links.len() < 10_000 {
self.links.push(super::LinkRect { x0, y0, x1, y1, target: link.to_string(), tag: None });
self.links.push(super::LinkRect { x0, y0, x1, y1, target: link.to_string(), tag: None, at: self.at });
self.last_link = Some(self.links.len() - 1);
}
}
+121
View File
@@ -3883,3 +3883,124 @@ fn separated_link_runs_are_separate_link_elements() {
}
assert_eq!(count(&tree), 2, "each separated link run needs its own Link element");
}
#[test]
fn header_and_footer_link_annotations_are_tagged_on_every_page() {
use hayro_syntax::object::{Array, Dict, Name, Object};
let header_props = CharProps { link: Some("https://header.example.com".into()), ..Default::default() };
let footer_props = CharProps { link: Some("https://footer.example.com".into()), ..Default::default() };
let body_props = CharProps { link: Some("https://body.example.com".into()), ..Default::default() };
let mut d = Document::new();
d.core.title = "Header and footer links".into();
let header_id = d.add_part(wordcraft_doc::PartKind::Header, vec![para_block(Paragraph::with_text("Header site", header_props))]);
let footer_id = d.add_part(wordcraft_doc::PartKind::Footer, vec![para_block(Paragraph::with_text("Footer site", footer_props))]);
d.last_section.headers.default = Some(header_id);
d.last_section.footers.default = Some(footer_id);
let mut p1 = Paragraph::with_text("Visit ", CharProps::default());
p1.insert_text(p1.len(), "Body", &body_props).unwrap();
let mut p2 = Paragraph::with_text("Second page", CharProps::default());
p2.props.page_break_before = Some(true);
d.body = vec![para_block(p1), para_block(p2)];
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
assert_eq!(pdf.pages().len(), 2, "expected two pages");
// Collect every link annotation across both pages and check /StructParent on each.
let mut expected_annots: Vec<(usize, String, i32)> = Vec::new();
for (page_idx, page) in pdf.pages().iter().enumerate() {
let annots = page.raw().get::<Array>(b"Annots").expect("page Annots");
for annot in annots.iter::<Dict>() {
let sp = annot.get::<i32>(b"StructParent").expect("link annotation missing /StructParent");
let id = format!("{:?}", annot.obj_id().expect("indirect annotation"));
expected_annots.push((page_idx, id, sp));
}
}
assert_eq!(expected_annots.len(), 5, "page 1 has header+body+footer links, page 2 has header+footer links");
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
let struct_tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
fn find_links(dict: &Dict, out: &mut Vec<(bool, Option<String>)>) {
if dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link") {
let mut has_mcid = false;
let mut objr = None;
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
match item {
Object::Number(_) => has_mcid = true,
Object::Dict(d) if d.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") => {
objr = d.get::<Dict>(b"Obj").and_then(|o| o.obj_id()).map(|id| format!("{id:?}"));
}
_ => {}
}
}
}
out.push((has_mcid, objr));
}
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
if let Object::Dict(child) = item {
find_links(&child, out);
}
}
} else if let Some(child) = dict.get::<Dict>(b"K") {
find_links(&child, out);
}
}
let mut links = Vec::new();
find_links(&struct_tree, &mut links);
assert_eq!(links.len(), expected_annots.len(), "every link annotation needs a /Link structure element: {links:?}");
for (page_idx, annot_id, _) in &expected_annots {
assert!(
links.iter().any(|(_, objr)| objr.as_deref() == Some(annot_id.as_str())),
"page {page_idx} annotation {annot_id} has no /Link OBJR in StructTreeRoot: {links:?}"
);
}
// The 4 header/footer links stay outside artifact content (OBJR only); the body link also holds its MCID.
assert_eq!(links.iter().filter(|(mcid, _)| !*mcid).count(), 4, "header/footer links hold only OBJR: {links:?}");
assert_eq!(links.iter().filter(|(mcid, _)| *mcid).count(), 1, "body link holds MCID and OBJR: {links:?}");
// Verify /ParentTree maps every annotation's /StructParent to a /Link structure element.
let parent_tree = struct_tree.get::<Dict>(b"ParentTree").expect("ParentTree");
let nums = parent_tree.get::<Array>(b"Nums").expect("ParentTree Nums");
let num_items: Vec<Object> = nums.iter::<Object>().collect();
for (page_idx, annot_id, sp) in &expected_annots {
let mut parent_role = None;
for pair in num_items.as_chunks::<2>().0 {
if let [Object::Number(k), Object::Dict(elem)] = pair
&& k.as_i64() == i64::from(*sp)
{
parent_role = elem.get::<Name>(b"S").map(|s| s.as_str().to_string());
break;
}
}
assert_eq!(
parent_role.as_deref(),
Some("Link"),
"page {page_idx} annotation {annot_id} /StructParent {sp} must point to /Link in /ParentTree"
);
}
// Verify reading order under Document: page 1 header link -> body P -> page 1 footer link -> page 2 header link -> body P -> page 2 footer link.
let mut tops: Vec<Dict> = match struct_tree.get::<Object>(b"K") {
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
Some(Object::Dict(d)) => vec![d],
_ => Vec::new(),
};
while let [only] = tops.as_slice()
&& only.get::<Name>(b"S").is_some_and(|s| s.as_str() == "Document")
{
tops = match only.get::<Object>(b"K") {
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
Some(Object::Dict(d)) => vec![d],
_ => Vec::new(),
};
}
let top_roles: Vec<String> = tops.iter().map(|d| d.get::<Name>(b"S").map(|s| s.as_str().to_string()).unwrap_or_default()).collect();
assert_eq!(top_roles, vec!["Div", "P", "Div", "Div", "P", "Div"], "header link before body, footer link after body");
}
+53 -259
View File
@@ -159,29 +159,13 @@ pub struct RenderOptions {
/// Colour for formatting marks.
pub mark_color: Rgb,
/// Thicken glyphs slightly the way macOS draws text on screen ("font smoothing"), so pages
/// look like they do in other Mac apps: 0 is none, 1 the system's default strength
/// ([`stem_darkening`]), and other values scale it, up to twice (the system's own setting
/// has a lighter and a stronger step). A value that isn't a number is none. For on-screen
/// rasters only: exports stay exact.
pub text_darkening: f32,
/// Put every glyph's baseline on a whole device pixel, for text that is neither rotated nor
/// mirrored. A baseline between two pixel rows spreads the feet of the letters (serifs, the
/// bottoms of stems) over both rows as two grey rows instead of one solid one, which reads as
/// blur. A glyph moves by half a pixel at most and never sideways, so lines break as without
/// it. Hinted text already sits like this. For on-screen rasters only: exports stay exact.
pub baseline_snap: bool,
/// look like they do in other Mac apps. For on-screen rasters only: exports stay exact.
pub text_darkening: bool,
/// Hint text for the screen the way FreeType's `hintslight` does on Linux desktops: glyph
/// baselines sit on whole pixels and their horizontal edges (x-height, cap height) are moved
/// onto the pixel grid, so text looks as crisp as in other apps there. Nothing moves
/// sideways, so lines break as without it. For on-screen rasters only: exports stay exact.
pub hinting: bool,
/// Subpixel (LCD) antialiasing for text, for a screen whose colour stripes run in this order
/// (see [`LcdOrder`]); `None` is greyscale antialiasing. Text gets three times the detail
/// sideways, where slanted and round strokes need it most, at the price of faint colour at
/// its edges, and the page is rasterised three times. Everything but text is drawn as
/// without it. For on-screen rasters only, and only where the raster's pixels are the
/// screen's own: exports stay exact.
pub lcd: Option<LcdOrder>,
/// Dark page (View › Switch Modes): every colour but pictures has its lightness inverted, so
/// white paper turns black and black text white while hues stay the same. Screen only.
pub dark: bool,
@@ -192,20 +176,6 @@ pub struct RenderOptions {
pub read_paper: Option<Rgb>,
}
/// The order of a screen's red, green and blue stripes, left to right, within each pixel.
///
/// With [`RenderOptions::lcd`] set, each colour channel of a pixel takes the text's coverage
/// around its own stripe, a third of a pixel to one side of the pixel's middle or the other,
/// instead of all three taking the coverage of the whole pixel. A pixel's stripes are a pixel
/// wide in all, so each channel still averages over one pixel's width: this is the result of
/// rasterising text at three times the width and averaging three neighbours (the box filter
/// FreeType calls its light LCD filter), with no sharper filter and no fringe reduction.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LcdOrder {
Rgb,
Bgr,
}
/// Default grey for a dark page's paper.
pub const DARK_PAPER: u8 = 0x33;
@@ -297,10 +267,8 @@ impl Default for RenderOptions {
display: DisplayOptions::default(),
paper: Rgb::WHITE,
mark_color: Rgb(0x2B, 0x57, 0x9A),
text_darkening: 0.0,
baseline_snap: false,
text_darkening: false,
hinting: false,
lcd: None,
dark: false,
dark_paper: DARK_PAPER,
read_paper: None,
@@ -328,52 +296,6 @@ fn render_region_capped(doc: &Document, page: &Page, w: u32, h: u32, view: Affin
// Over the cap the whole picture is drawn smaller, not cropped.
let view = if (cw, ch) == (w, h) { view } else { Affine::scale_non_uniform(cw as f64 / w as f64, ch as f64 / h as f64) * view };
let (w16, h16) = (cw as u16, ch as u16);
let drew_text = std::cell::Cell::new(false);
let mut pixels = raster_page(doc, page, (w16, h16), view, opts, Pass { shift: 0.0, drew_text: &drew_text });
// Subpixel text: the page twice more, its text a third of a pixel to each side, for the
// channels whose stripes sit there. A page without text is the same all three times.
if let Some(order) = opts.lcd
&& drew_text.get()
{
let side = |shift: f64| raster_page(doc, page, (w16, h16), view, opts, Pass { shift, drew_text: &drew_text });
let (text_right, text_left) = (side(LCD_SHIFT), side(-LCD_SHIFT));
let (red, blue) = match order {
LcdOrder::Rgb => (&text_right, &text_left),
LcdOrder::Bgr => (&text_left, &text_right),
};
take_lcd_channels(&mut pixels, red, blue);
}
Rendered { width: w16 as u32, height: h16 as u32, pixels }
}
/// How far, in device pixels, the middle of a pixel's first or last colour stripe is from the
/// middle of the pixel.
const LCD_SHIFT: f64 = 1.0 / 3.0;
/// One rasterisation of a page among the one or three that make its raster.
#[derive(Clone, Copy)]
struct Pass<'a> {
/// How far to the right text is drawn from its place, in device pixels (see
/// [`RenderOptions::lcd`]). Nothing else moves.
shift: f64,
/// Set once the pass has drawn text that `shift` moves.
drew_text: &'a std::cell::Cell<bool>,
}
/// The red of `pixels` from `red` and its blue from `blue`, two rasters of the same size
/// (premultiplied RGBA8). Text shifted right puts under each pixel's middle what lay a third of a
/// pixel to its left, where an RGB screen's red stripe is, and so on. The alpha stays, and
/// no channel is left above it.
fn take_lcd_channels(pixels: &mut [u8], red: &[u8], blue: &[u8]) {
for ((px, r), b) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(red.as_chunks::<4>().0).zip(blue.as_chunks::<4>().0) {
px[0] = r[0].min(px[3]);
px[2] = b[2].min(px[3]);
}
}
/// Rasterise a page into `size` pixels (premultiplied RGBA8) with `view` (page points → pixels).
fn raster_page(doc: &Document, page: &Page, size: (u16, u16), view: Affine, opts: &RenderOptions, pass: Pass) -> Vec<u8> {
let (w16, h16) = size;
let mut ctx = context_pool::CONTEXTS.take(w16, h16);
ctx.set_transform(Affine::IDENTITY);
ctx.set_paint(color(opts.paper_of(doc), 1.0));
@@ -392,7 +314,7 @@ fn raster_page(doc: &Document, page: &Page, size: (u16, u16), view: Affine, opts
ctx.push_opacity_layer(alpha);
}
for it in &items {
draw(&mut ctx, doc, it, view, &visible, opts, pass);
draw(&mut ctx, doc, it, view, &visible, opts);
}
if faded {
ctx.pop_layer();
@@ -405,7 +327,7 @@ fn raster_page(doc: &Document, page: &Page, size: (u16, u16), view: Affine, opts
ctx.render(pm, &mut res);
}
context_pool::CONTEXTS.give_back(ctx);
pixels
Rendered { width: w16 as u32, height: h16 as u32, pixels }
}
/// The on-screen colour behind page point (`x`, `y`): the paper (page colour), then any
@@ -573,30 +495,24 @@ fn draw_watermark(ctx: &mut RenderContext, view: Affine, page: &Page, wm: &wordc
/// Does `view` map page points to device pixels without rotation, skew or mirroring, scaling both
/// axes alike? Only then do hinted outlines (made on the pixel grid) line up with the screen.
/// "Alike" allows the two axes a fifth of a percent apart: a page raster made to fill a whole
/// number of pixels each way ([`render_area_to`]) is scaled that little differently across and
/// down (a pixel in some two thousand), and is as upright as any.
fn is_upright(view: Affine) -> bool {
let [a, b, c, d, e, f] = view.as_coeffs();
[a, b, c, d, e, f].iter().all(|v| v.is_finite()) && b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= a * 2e-3
[a, b, c, d, e, f].iter().all(|v| v.is_finite()) && b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= a * 1e-6
}
/// How far, in device pixels, macOS-style font smoothing pushes each side of a glyph outline out
/// sideways at `ppem` device pixels per em. The value is Pathfinder's (MIT/Apache-2.0), which
/// measured it against macOS: 1.21% of the pixel size, capped at 0.3 px, and no darkening past
/// 72 px per em. Pathfinder also grows glyphs up and down (1.25 times as far). We don't: a third
/// of a pixel of grey above and below every letter is what made page text look out of focus
/// beside other Mac apps, whose letters end on a clean pixel row. Stems get thicker, which is
/// the weight the smoothing is for; the tops and feet of the letters stay where the font puts
/// them.
/// at `ppem` device pixels per em. Values from Pathfinder (MIT/Apache-2.0), which measured them
/// against macOS: 1.21% of the pixel size horizontally and 1.25 times that vertically, each
/// capped at 0.3 px, and no darkening past 72 px per em. We stroke the outline, which grows it
/// evenly, so this is the mean of the two.
pub fn stem_darkening(ppem: f64) -> f64 {
const FACTOR: f64 = 0.0121;
const FACTOR: [f64; 2] = [0.0121, 0.0121 * 1.25];
const MAX_PX: f64 = 0.3;
const MAX_PPEM: f64 = 72.0;
if !ppem.is_finite() || ppem <= 0.0 || ppem > MAX_PPEM {
return 0.0;
}
(ppem * FACTOR).min(MAX_PX)
FACTOR.iter().map(|f| (ppem * f).min(MAX_PX)).sum::<f64>() / 2.0
}
/// A wavy line from `(x0, y0)` to `(x1, y1)`; at most 20 000 units long, so a huge extent can't make it endless.
@@ -680,7 +596,6 @@ struct Frame<'a> {
opts: &'a RenderOptions,
view: Affine,
visible: &'a kurbo::Rect,
pass: Pass<'a>,
}
/// The rectangle in kurbo's terms.
@@ -692,12 +607,12 @@ fn kurbo_rect(rect: &wordcraft_geom::Rect) -> kurbo::Rect {
/// `visible` is a culling area in those point coordinates; nested clips intersect it and turns
/// transform it into the child's coordinates. Shape and path strokes apply their stored caps,
/// while ink uses its tool's round ends and joins.
fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visible: &kurbo::Rect, opts: &RenderOptions, pass: Pass) {
let fr = Frame { doc, opts, view, visible, pass };
fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visible: &kurbo::Rect, opts: &RenderOptions) {
let fr = Frame { doc, opts, view, visible };
match it {
Draw::Figure { draws, .. } => {
for d in draws {
draw(ctx, doc, d, view, visible, opts, pass);
draw(ctx, doc, d, view, visible, opts);
}
}
Draw::Fill { .. } => draw_fill(ctx, &fr, it),
@@ -719,7 +634,7 @@ fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visibl
ctx.push_clip_layer(&r.to_path(0.1));
let local = r.intersect(*visible);
for it in items {
draw(ctx, doc, it, view, &local, opts, pass);
draw(ctx, doc, it, view, &local, opts);
}
ctx.pop_layer();
}
@@ -727,14 +642,14 @@ fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visibl
let m = Affine::new(Draw::turn_matrix(*turn, *x, *y).map(f64::from));
let local = m.inverse().transform_rect_bbox(*visible);
for it in items {
draw(ctx, doc, it, view * m, &local, opts, pass);
draw(ctx, doc, it, view * m, &local, opts);
}
}
Draw::Rotated { cx, cy, spin, items } => {
let m = Affine::new(spin.matrix(*cx, *cy).map(f64::from));
let local = m.inverse().transform_rect_bbox(*visible);
for it in items {
draw(ctx, doc, it, view * m, &local, opts, pass);
draw(ctx, doc, it, view * m, &local, opts);
}
}
}
@@ -789,8 +704,7 @@ fn draw_line(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
}
_ => {
let (st, off) = match snap_rule(fr.view, (x0, y0, x1, y1), w) {
// The width is across the rule: in points by the scale that way.
Some((w_px, off)) => (kurbo::Stroke { width: w_px / rule_scale(fr.view, y0 == y1), ..st }, off),
Some((w_px, off)) => (kurbo::Stroke { width: w_px / fr.view.as_coeffs()[0], ..st }, off),
None => (st, (0.0, 0.0)),
};
ctx.set_stroke(st);
@@ -807,13 +721,11 @@ fn snap_rule(view: Affine, (x0, y0, x1, y1): (f64, f64, f64, f64), width: f64) -
if !is_upright(view) {
return None;
}
let [_, _, _, _, tx, ty] = view.as_coeffs();
let [k, _, _, _, tx, ty] = view.as_coeffs();
if y0 == y1 && x0 != x1 {
let k = rule_scale(view, true);
let (w_px, c) = snap_hairline(y0 * k + ty, width * k);
Some((w_px, (0.0, (c - ty) / k - y0)))
} else if x0 == x1 && y0 != y1 {
let k = rule_scale(view, false);
let (w_px, c) = snap_hairline(x0 * k + tx, width * k);
Some((w_px, ((c - tx) / k - x0, 0.0)))
} else {
@@ -821,16 +733,6 @@ fn snap_rule(view: Affine, (x0, y0, x1, y1): (f64, f64, f64, f64), width: f64) -
}
}
/// Device pixels per point across a rule: down the page for a level rule, across it for an
/// upright one. An upright view ([`is_upright`]) may scale the two a little differently (a page
/// raster made to fill a whole number of pixels each way), and a rule's place and width are
/// measured across it: with the other scale, a level rule low on such a page was snapped up to
/// a pixel from where it lies, its edges between pixel rows.
fn rule_scale(view: Affine, level: bool) -> f64 {
let [across, _, _, down, ..] = view.as_coeffs();
if level { down } else { across }
}
/// A line `width_px` wide centred at device coordinate `centre`, moved so both edges fall on whole
/// pixels. Returns the width, made a whole number of pixels (at least one), and the new centre.
fn snap_hairline(centre: f64, width_px: f64) -> (f64, f64) {
@@ -860,25 +762,23 @@ fn draw_glyphs(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
// Scaled letters (`w:w`): each glyph stretched across from its pen position.
let sx = if x_scale.is_finite() && *x_scale > 0.0 { f64::from(*x_scale) } else { 1.0 };
let skew = Affine::scale_non_uniform(sx, 1.0) * skew;
// Synthetic bold strokes the outline, in font units.
// Outline strokes, in font units: synthetic bold, then on-screen stem darkening (a
// stroke grows the outline by half its width on each side). Darkening is skipped for
// translucent text, where the stroke overlapping the fill would show as a darker rim.
let px_per_pt = view.determinant().abs().sqrt();
let outline_stroke = if *synth_bold { face.upem * 0.03 } else { 0.0 };
let darken_px = if opts.text_darkening && *alpha >= 1.0 { stem_darkening(*size as f64 * px_per_pt) } else { 0.0 };
let darken = if darken_px > 0.0 && k * px_per_pt > 0.0 { 2.0 * darken_px / (k * px_per_pt) } else { 0.0 };
let outline_stroke = if *synth_bold { face.upem * 0.03 } else { 0.0 } + darken;
let join = if darken > 0.0 { kurbo::Join::Round } else { kurbo::Join::Miter };
if outline_stroke > 0.0 {
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(kurbo::Join::Miter));
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(join));
}
// Emoji and other colour glyphs (#1269) are drawn from the font's colour data.
let colour = face.has_color_glyphs();
let ppem = *size as f64 * px_per_pt;
// On-screen stem darkening: each outline is widened along its own x axis, in one piece (see
// [`stem_darkening`] and [`widened`]). Skipped for translucent text, as it always was.
let strength = if opts.text_darkening.is_finite() { f64::from(opts.text_darkening).clamp(0.0, 2.0) } else { 0.0 };
let darken_px = if *alpha >= 1.0 { stem_darkening(ppem) * strength } else { 0.0 };
// Hinted outlines are in device pixels, and a snapped baseline is a row of them: only for an
// upright, unmirrored, evenly scaled view (not rotated text boxes), where the pixel grid
// lines up with the glyphs.
let upright = is_upright(view);
let hint_ppem = (opts.hinting && !colour && upright).then_some(ppem as f32);
let snap = opts.baseline_snap && upright;
// Hinted outlines are in device pixels: only for an upright, unmirrored, evenly scaled
// view (not rotated text boxes), where the pixel grid lines up with the glyphs.
let hint_ppem = (opts.hinting && !colour && is_upright(view)).then_some(ppem as f32);
// The outline strokes in device pixels, for the hinted outlines.
let stroke_px = outline_stroke * k * px_per_pt;
let mut hinted_stroke = false;
@@ -895,128 +795,37 @@ fn draw_glyphs(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
ctx.set_paint(color(opts.ink(*c), *alpha));
continue;
}
let pen = view * kurbo::Point::new(gx, gy);
let hinted = hint_ppem.and_then(|p| db.hinted_outline(face, *gid, p));
let hinted_now = hinted.is_some();
let (o, at) = if let Some(o) = hinted {
if outline_stroke > 0.0 && !hinted_stroke {
ctx.set_stroke(kurbo::Stroke::new(stroke_px).with_join(kurbo::Join::Miter));
hinted_stroke = true;
if let Some(o) = hint_ppem.and_then(|p| db.hinted_outline(face, *gid, p)) {
if o.elements().is_empty() {
continue;
}
// The baseline on a whole pixel, as the hinting assumes.
(o, Affine::translate((pen.x, pen.y.round())) * skew)
} else {
if outline_stroke > 0.0 && hinted_stroke {
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(kurbo::Join::Miter));
hinted_stroke = false;
let at = view * kurbo::Point::new(gx, gy);
ctx.set_transform(Affine::translate((at.x, at.y.round())) * skew);
ctx.fill_path(&o);
if outline_stroke > 0.0 {
if !hinted_stroke {
ctx.set_stroke(kurbo::Stroke::new(stroke_px).with_join(join));
hinted_stroke = true;
}
ctx.stroke_path(&o);
}
let at = view * Affine::translate((gx, gy)) * skew * Affine::scale(k);
// The same baseline for text drawn from the font's own outlines.
let lift = if snap && pen.y.is_finite() { pen.y.round() - pen.y } else { 0.0 };
(db.outline(face, *gid), Affine::translate((0.0, lift)) * at)
};
continue;
}
let o = db.outline(face, *gid);
if o.elements().is_empty() {
continue;
}
// This pass's sideways shift, across the screen whichever way the text is turned.
fr.pass.drew_text.set(true);
ctx.set_transform(Affine::translate((fr.pass.shift, 0.0)) * at);
// The darkened outline is the glyph: synthetic bold strokes it too. Stroking the font's own
// outline there would cover the widening (the stroke reaches further than it does) and
// leave such text as light as without darkening.
let wide = (darken_px > 0.0).then(|| widened(&o, darken_px / widen_unit(hinted_now, k * px_per_pt, sx)));
let shape = wide.as_ref().unwrap_or(&o);
ctx.fill_path(shape);
ctx.set_transform(view * Affine::translate((gx, gy)) * skew * Affine::scale(k));
ctx.fill_path(&o);
if outline_stroke > 0.0 {
ctx.stroke_path(shape);
}
}
}
/// How many device pixels one unit of a glyph outline is across the screen, for turning a
/// widening in device pixels into the outline's own units: a hinted outline is in device pixels
/// already and the font's own in font units (`font_px` device pixels each), and both are then
/// stretched `stretch` times across by scaled letters (`w:w`). Without the stretch for hinted
/// outlines, text scaled to 400 % was widened four times too far.
fn widen_unit(hinted: bool, font_px: f64, stretch: f64) -> f64 {
if hinted { stretch } else { font_px * stretch }
}
/// `path` with every edge moved `d` sideways, away from the ink: the shape a glyph makes when it
/// is smeared `d` to the left and `d` to the right, so stems get `2 d` thicker while nothing
/// grows up or down. One outline, filled once, so partly covered pixels are counted once (the
/// outline drawn again beside itself counted them two and three times, which read as bold).
///
/// Each point moves with the edges it joins: by `d` where both face the same side, or one of
/// them is level; not at all at the top or the foot of a curve, where one faces left and the
/// other right. Curve control points move by the same rule along the control polygon. Which side
/// of an edge is ink follows from the direction the outline runs in, read off its signed area,
/// so the holes of letters narrow as their stems widen. An outline with no area, or with
/// numbers that aren't finite, is returned as it is.
fn widened(path: &BezPath, d: f64) -> BezPath {
use kurbo::PathEl;
let els = path.elements();
// The control polygon of each contour, as (first point index, point count).
let mut pts: Vec<kurbo::Point> = Vec::with_capacity(els.len() * 2);
let mut contours: Vec<(usize, usize)> = Vec::new();
let mut start = 0;
for el in els {
match el {
PathEl::MoveTo(p) => {
if pts.len() > start {
contours.push((start, pts.len() - start));
}
start = pts.len();
pts.push(*p);
if hinted_stroke {
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(join));
hinted_stroke = false;
}
PathEl::LineTo(p) => pts.push(*p),
PathEl::QuadTo(c, p) => pts.extend([*c, *p]),
PathEl::CurveTo(c1, c2, p) => pts.extend([*c1, *c2, *p]),
PathEl::ClosePath => {}
ctx.stroke_path(&o);
}
}
if pts.len() > start {
contours.push((start, pts.len() - start));
}
let ring = |first: usize, n: usize, i: usize| pts.get(first + i % n.max(1)).copied().unwrap_or_default();
let area: f64 =
contours.iter().map(|&(first, n)| (0..n).map(|i| ring(first, n, i).to_vec2().cross(ring(first, n, i + 1).to_vec2())).sum::<f64>()).sum();
if !(d.is_finite() && d > 0.0 && area.is_finite() && area != 0.0) {
return path.clone();
}
// Which way the edge from `a` to `b` faces: 1 right, -1 left, 0 for a level edge.
let faces = |a: kurbo::Point, b: kurbo::Point| {
let (run, rise) = ((b.x - a.x).abs(), b.y - a.y);
if rise.abs() <= 1e-6 * (run + rise.abs()) { 0.0 } else { (rise * area).signum() }
};
let mut moved = pts.clone();
for &(first, n) in &contours {
for i in 0..n {
let at = ring(first, n, i);
// The nearest different points before and after: a contour may repeat a point (a
// run of more than a few is left where it is).
let before = (1..n.min(8)).map(|step| ring(first, n, i + n - step)).find(|p| *p != at);
let after = (1..n.min(8)).map(|step| ring(first, n, i + step)).find(|p| *p != at);
let (Some(before), Some(after)) = (before, after) else { continue };
let push = (faces(before, at) + faces(at, after)).clamp(-1.0, 1.0);
if let Some(p) = moved.get_mut(first + i) {
p.x += push * d;
}
}
}
let mut next = moved.into_iter();
let mut take = || next.next().unwrap_or_default();
let mut out = BezPath::with_capacity(els.len());
for el in els {
out.push(match el {
PathEl::MoveTo(_) => PathEl::MoveTo(take()),
PathEl::LineTo(_) => PathEl::LineTo(take()),
PathEl::QuadTo(..) => PathEl::QuadTo(take(), take()),
PathEl::CurveTo(..) => PathEl::CurveTo(take(), take(), take()),
PathEl::ClosePath => PathEl::ClosePath,
});
}
out
}
fn draw_mark(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
@@ -1471,19 +1280,6 @@ pub fn render_area(doc: &Document, page: &Page, area: wordcraft_geom::Rect, scal
render_region(doc, page, pw, ph, view, opts)
}
/// Render the page `area` (points) into exactly `w`×`h` pixels: the area fills the raster, scaled
/// across and down by whatever that takes. For a raster that must be a given number of device
/// pixels each way, where [`render_area`]'s single scale gives the next whole pixel up: a picture
/// one pixel larger than its place on screen is scaled into it, and every glyph resampled.
pub fn render_area_to(doc: &Document, page: &Page, area: wordcraft_geom::Rect, w: u32, h: u32, opts: &RenderOptions) -> Rendered {
let (w, h) = (w.clamp(1, MAX_SIDE), h.clamp(1, MAX_SIDE));
let (sx, sy) = (f64::from(w) / f64::from(area.w), f64::from(h) / f64::from(area.h));
let fine = |v: f64| v.is_finite() && v > 0.0;
let (sx, sy) = if fine(sx) && fine(sy) && area.x.is_finite() && area.y.is_finite() { (sx, sy) } else { (1.0, 1.0) };
let (x, y) = if area.x.is_finite() && area.y.is_finite() { (f64::from(area.x), f64::from(area.y)) } else { (0.0, 0.0) };
render_region(doc, page, w, h, Affine::scale_non_uniform(sx, sy) * Affine::translate((-x, -y)), opts)
}
/// Draw `items` (page points) alone, on nothing, over the page `area` (points) at `scale` px/pt:
/// no paper, no watermark. A dragged object's preview.
pub fn render_items(doc: &Document, items: &[Draw], area: wordcraft_geom::Rect, scale: f32, opts: &RenderOptions) -> Rendered {
@@ -1497,10 +1293,8 @@ pub fn render_items(doc: &Document, items: &[Draw], area: wordcraft_geom::Rect,
* Affine::translate((-x as f64, -y as f64));
let mut ctx = RenderContext::new_with(w16, h16, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() });
let visible = view.inverse().transform_rect_bbox(kurbo::Rect::new(0.0, 0.0, w16 as f64, h16 as f64)).inflate(40.0, 40.0);
// One pass, text in its place: an area raster (a preview, a dragged object) is greyscale.
let drew_text = std::cell::Cell::new(false);
for it in items {
draw(&mut ctx, doc, it, view, &visible, opts, Pass { shift: 0.0, drew_text: &drew_text });
draw(&mut ctx, doc, it, view, &visible, opts);
}
ctx.flush();
let mut pixels = vec![0u8; w16 as usize * h16 as usize * 4];
+3 -358
View File
@@ -265,7 +265,7 @@ fn stem_darkening_follows_the_macos_curve() {
assert_eq!(stem_darkening(f64::NAN), 0.0);
assert_eq!(stem_darkening(-5.0), 0.0);
// Small text grows in proportion to its pixel size...
assert!((stem_darkening(10.0) - 10.0 * 0.0121).abs() < 1e-9);
assert!((stem_darkening(10.0) - 10.0 * 0.0121 * 2.25 / 2.0).abs() < 1e-9);
// ...body text on a Retina screen hits the 0.3 px cap...
assert_eq!(stem_darkening(30.0), 0.3);
assert_eq!(stem_darkening(72.0), 0.3);
@@ -283,29 +283,12 @@ fn text_darkening_adds_ink_on_screen_only() {
let d = Document::from_text("Marketing analytics lead with twelve years of measurement work.");
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let plain = render_page(&d, &l.pages[0], 2.0, &RenderOptions::default());
let dark = render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: 1.0, ..Default::default() });
let dark = render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: true, ..Default::default() });
let (a, b) = (ink(&plain), ink(&dark));
// About 0.3 px more on every edge of an 11 pt line at 2x: clearly more ink, not bold.
assert!(b as f64 > a as f64 * 1.08 && (b as f64) < a as f64 * 1.6, "plain {a}, darkened {b}");
// Off by default: exports and thumbnails are untouched.
assert_eq!(RenderOptions::default().text_darkening, 0.0);
}
#[test]
fn text_darkening_is_a_strength() {
let d = Document::from_text("Marketing analytics lead with twelve years of measurement work.");
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let at = |strength: f32| ink(&render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: strength, ..Default::default() }));
// The system's lighter, default and stronger steps each add ink.
let (none, light, default, strong) = (at(0.0), at(0.5), at(1.0), at(1.5));
assert!(none < light && light < default && default < strong, "{none} {light} {default} {strong}");
assert_eq!(none, ink(&render_page(&d, &l.pages[0], 2.0, &RenderOptions::default())));
// No more than twice the default, and junk is no darkening at all.
assert_eq!(at(2.0), at(50.0));
assert_eq!(at(2.0), at(f32::INFINITY.min(f32::MAX)));
for junk in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0] {
assert_eq!(at(junk), none, "{junk}");
}
assert!(!RenderOptions::default().text_darkening);
}
/// Inked pixels that are only partly covered (grey): an edge between two pixel rows.
@@ -320,315 +303,6 @@ fn ink_columns(img: &Rendered) -> (usize, usize) {
(inked.iter().copied().min().unwrap_or(0), inked.iter().copied().max().unwrap_or(0))
}
/// The first and last pixel rows with any ink.
fn ink_row_span(img: &Rendered) -> (usize, usize) {
let w = img.width as usize;
let inked: Vec<usize> = img.pixels.as_chunks::<4>().0.iter().enumerate().filter(|(_, p)| p[0] < 250).map(|(i, _)| i / w.max(1)).collect();
(inked.iter().copied().min().unwrap_or(0), inked.iter().copied().max().unwrap_or(0))
}
/// One line of flat-footed capitals in a bundled face: no letter dips under the baseline.
fn flat_capitals() -> (Document, wordcraft_layout::DocLayout) {
let mut d = Document::from_text("THE FELT HILT FILE LIFT HEFT TILT");
let styles = std::sync::Arc::make_mut(&mut d.styles);
styles.default_chr.font = Some("Source Sans 3".into());
styles.default_chr.size = Some(12.0);
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
(d, l)
}
#[test]
fn a_snapped_baseline_ends_the_letters_on_a_whole_pixel_row() {
let (d, l) = flat_capitals();
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
// Scales that put the baseline at different places between two pixel rows.
let mut sharper = 0;
for scale in [1.0, 1.25, 1.45, 96.0 / 72.0 * 1.45, 2.0, 2.3] {
let plain = render_page(&d, &l.pages[0], scale, &RenderOptions::default());
let snapped = render_page(&d, &l.pages[0], scale, &snap);
// The row under the letters' feet: all of it white once the baseline is on a pixel
// boundary, where the unsnapped feet leave a grey row or end a row early.
let (_, foot) = ink_row_span(&snapped);
let w = snapped.width as usize;
let foot_row = &snapped.pixels[foot * w * 4..(foot + 1) * w * 4];
let darkest = foot_row.as_chunks::<4>().0.iter().map(|p| p[0]).min().unwrap_or(255);
assert!(darkest < 16, "scale {scale}: the feet fill their last row (darkest pixel {darkest})");
let (g0, g1) = (grey(&plain), grey(&snapped));
assert!(g1 <= g0, "scale {scale}: grey pixels: plain {g0}, snapped {g1}");
sharper += usize::from(g1 < g0);
// The same weight, and nothing moves sideways.
let (a, b) = (ink(&plain), ink(&snapped));
assert!((b as f64 - a as f64).abs() < a as f64 * 0.02, "scale {scale}: ink: plain {a}, snapped {b}");
assert_eq!(ink_columns(&plain), ink_columns(&snapped), "scale {scale}");
// No more than half a pixel up or down.
let ((t0, b0), (t1, b1)) = (ink_row_span(&plain), ink_row_span(&snapped));
assert!(t0.abs_diff(t1) <= 1 && b0.abs_diff(b1) <= 1, "scale {scale}: plain {t0}..{b0}, snapped {t1}..{b1}");
}
assert!(sharper >= 3, "snapping sharpened {sharper} of 6 scales");
// Off by default: exports and thumbnails are untouched.
assert!(!RenderOptions::default().baseline_snap);
}
#[test]
fn rotated_views_keep_their_baselines() {
let (d, l) = flat_capitals();
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
let view = Affine::translate((300.0, -50.0)) * Affine::rotate(0.3) * Affine::scale(1.9);
let plain = render_region(&d, &l.pages[0], 600, 300, view, &RenderOptions::default());
assert!(ink(&plain) > 0);
assert_eq!(plain.pixels, render_region(&d, &l.pages[0], 600, 300, view, &snap).pixels);
}
#[test]
fn darkening_thickens_stems_and_leaves_the_tops_and_feet_of_letters_alone() {
let (d, l) = flat_capitals();
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
let dark = RenderOptions { text_darkening: 1.0, ..snap.clone() };
for scale in [1.0, 1.45, 2.0] {
let plain = render_page(&d, &l.pages[0], scale, &snap);
let darkened = render_page(&d, &l.pages[0], scale, &dark);
// More ink, in the same pixel rows: nothing is added above the letters or under them
// (the stroke this replaces put a third of a pixel of grey on both).
assert!(ink(&darkened) as f64 > ink(&plain) as f64 * 1.05, "scale {scale}");
assert_eq!(ink_row_span(&plain), ink_row_span(&darkened), "scale {scale}");
// Sideways, less than a pixel each way.
let ((l0, r0), (l1, r1)) = (ink_columns(&plain), ink_columns(&darkened));
assert!(l1 <= l0 && l0 - l1 <= 1 && r1 >= r0 && r1 - r0 <= 1, "scale {scale}: plain {l0}..{r0}, darkened {l1}..{r1}");
}
}
#[test]
fn widening_moves_edges_sideways_away_from_the_ink() {
// A 10 x 10 square with a 4 x 4 hole, the hole running the other way round.
let mut ring = kurbo::Rect::new(0.0, 0.0, 10.0, 10.0).to_path(0.1);
ring.move_to((3.0, 3.0));
for p in [(3.0, 7.0), (7.0, 7.0), (7.0, 3.0)] {
ring.line_to(p);
}
ring.close_path();
for path in [ring.clone(), ring.reverse_subpaths()] {
let wide = widened(&path, 0.5);
// The square is 1 wider and the hole 1 narrower; neither is any taller.
let b = wide.bounding_box();
assert_eq!((b.x0, b.x1, b.y0, b.y1), (-0.5, 10.5, 0.0, 10.0));
assert!((wide.area().abs() - (11.0 * 10.0 - 3.0 * 4.0)).abs() < 1e-9, "{}", wide.area());
assert_eq!(wide.elements().len(), path.elements().len());
}
// A round shape: wider, no taller, and its top and bottom points stay put.
let disc = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(1e-3);
let b = widened(&disc, 0.25).bounding_box();
assert!((b.width() - 10.5).abs() < 0.02 && (b.height() - 10.0).abs() < 0.02, "{b:?}");
// Nothing to widen, or nothing to widen by: the path comes back as it was.
let line = BezPath::from_vec(vec![kurbo::PathEl::MoveTo((0.0, 0.0).into()), kurbo::PathEl::LineTo((5.0, 5.0).into())]);
for (path, d) in [(&line, 0.5), (&ring, 0.0), (&ring, -1.0), (&ring, f64::NAN), (&ring, f64::INFINITY), (&BezPath::new(), 0.5)] {
assert_eq!(widened(path, d).elements(), path.elements(), "{d}");
}
// Hostile outlines don't panic: points that aren't numbers, and one point repeated.
let mut odd = BezPath::new();
odd.move_to((f64::NAN, 0.0));
odd.line_to((1.0, f64::INFINITY));
odd.quad_to((2.0, 2.0), (0.0, 0.0));
let _ = widened(&odd, 0.5);
let mut same = BezPath::new();
same.move_to((1.0, 1.0));
for _ in 0..50 {
same.line_to((1.0, 1.0));
}
same.line_to((4.0, 1.0));
same.line_to((4.0, 5.0));
same.close_path();
assert_eq!(widened(&same, 0.5).elements().len(), same.elements().len());
}
/// The sum of one colour channel's distance from white.
fn channel_ink(img: &Rendered, channel: usize) -> u64 {
img.pixels.as_chunks::<4>().0.iter().map(|p| 255 - p[channel] as u64).sum()
}
#[test]
fn lcd_text_takes_each_channel_from_around_its_own_stripe() {
let d = Document::from_text("Nobody has assembled this board yet. Italic and round strokes gain the most.");
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let (w, h) = (700, 200);
let view = Affine::scale(1.25);
let lcd = |order| RenderOptions { lcd: Some(order), ..Default::default() };
let grey = render_region(&d, &l.pages[0], w, h, view, &RenderOptions::default());
let rgb = render_region(&d, &l.pages[0], w, h, view, &lcd(LcdOrder::Rgb));
let bgr = render_region(&d, &l.pages[0], w, h, view, &lcd(LcdOrder::Bgr));
assert!(ink(&grey) > 0);
// The page a third of a pixel to the right and to the left, in greyscale.
let moved = |dx: f64| render_region(&d, &l.pages[0], w, h, Affine::translate((dx, 0.0)) * view, &RenderOptions::default());
let (right, left) = (moved(1.0 / 3.0), moved(-1.0 / 3.0));
let mut coloured = 0;
let rasters = [&grey, &rgb, &bgr, &right, &left].map(|r| r.pixels.as_chunks::<4>().0);
for i in 0..rasters[0].len() {
let [g, c, m, r, l] = rasters.map(|px| px[i]);
// Green sits in the middle of the pixel: it and the alpha are the greyscale raster's.
assert_eq!((c[1], c[3]), (g[1], g[3]));
// Red is what a pixel a third to the left would see, blue a third to the right.
assert_eq!((c[0], c[2]), (r[0], l[2]), "pixel {i}");
// BGR stripes are the mirror image.
assert_eq!((m[0], m[1], m[2], m[3]), (c[2], c[1], c[0], c[3]));
coloured += usize::from(c[0] != c[2]);
}
assert!(coloured > 200, "{coloured} pixels have red and blue apart");
// No colour cast: each channel carries the same ink, to within a hundredth.
let [r, g, b] = [0, 1, 2].map(|c| channel_ink(&rgb, c) as f64);
assert!((r - g).abs() < g * 0.01 && (b - g).abs() < g * 0.01, "{r} {g} {b}");
// Off by default: exports and thumbnails are untouched.
assert_eq!(RenderOptions::default().lcd, None);
}
#[test]
fn lcd_changes_nothing_but_text() {
let lcd = RenderOptions { lcd: Some(LcdOrder::Rgb), ..Default::default() };
// A page with no text: the same raster, from one pass.
let mut blank = Document::from_text("");
blank.settings.page_color = Some(Rgb(0x20, 0x60, 0xA0));
let l = layout(&blank, &mut LayoutCache::new(), &LayoutOptions::default());
assert_eq!(render_page(&blank, &l.pages[0], 0.5, &lcd).pixels, render_page(&blank, &l.pages[0], 0.5, &RenderOptions::default()).pixels);
// A page with text on a page colour: pixels differ only where the text is.
let mut d = Document::from_text("Coloured paper under one line of text.");
d.settings.page_color = Some(Rgb(0xFF, 0xF0, 0xC0));
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let (grey, sub) = (render_page(&d, &l.pages[0], 1.25, &RenderOptions::default()), render_page(&d, &l.pages[0], 1.25, &lcd));
let w = grey.width as usize;
let paper = grey.pixels[..4].to_vec();
let inked: Vec<usize> = grey.pixels.as_chunks::<4>().0.iter().enumerate().filter(|(_, p)| p[..] != paper[..]).map(|(i, _)| i).collect();
let (top, bottom) = (inked.iter().map(|i| i / w).min().unwrap(), inked.iter().map(|i| i / w).max().unwrap());
let (first, last) = (inked.iter().map(|i| i % w).min().unwrap(), inked.iter().map(|i| i % w).max().unwrap());
let mut changed = 0;
for (i, (a, b)) in grey.pixels.as_chunks::<4>().0.iter().zip(sub.pixels.as_chunks::<4>().0).enumerate() {
if a != b {
changed += 1;
let (x, y) = (i % w, i / w);
assert!((top..=bottom).contains(&y) && x + 1 >= first && x <= last + 1, "pixel {x},{y} is outside the text");
}
}
assert!(changed > 50, "{changed}");
}
#[test]
fn lcd_channels_never_exceed_the_alpha() {
// Premultiplied pixels: a colour above its alpha would be brighter than white.
let mut px = vec![10, 20, 30, 40, 200, 200, 200, 255];
take_lcd_channels(&mut px, &[90, 0, 0, 255, 7, 0, 0, 255], &[0, 0, 80, 255, 0, 0, 9, 255]);
assert_eq!(px, [40, 20, 40, 40, 7, 200, 9, 255]);
// Rasters of other sizes leave the rest alone and don't panic.
let mut px = vec![1, 2, 3, 255, 4, 5, 6, 255, 9];
take_lcd_channels(&mut px, &[50, 0, 0, 255], &[]);
assert_eq!(px, [1, 2, 3, 255, 4, 5, 6, 255, 9]);
}
/// The glyph runs of `text` in a bundled face at 12 pt, as the page draws them, each changed by
/// `change`; and the area they are in.
fn glyph_runs(text: &str, change: impl Fn(&mut Draw)) -> (Document, Vec<Draw>, wordcraft_geom::Rect) {
let mut d = Document::from_text(text);
let styles = std::sync::Arc::make_mut(&mut d.styles);
styles.default_chr.font = Some("Source Sans 3".into());
styles.default_chr.size = Some(12.0);
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let page = &l.pages[0];
let mut runs: Vec<Draw> = page_layers(&d, page, &DisplayOptions::default())
.into_iter()
.flat_map(|(_, items)| items)
.filter(|it| matches!(it, Draw::Glyphs { .. }))
.collect();
assert!(!runs.is_empty());
runs.iter_mut().for_each(change);
(d, runs, wordcraft_geom::Rect::new(0.0, 0.0, page.w, 200.0))
}
/// How much is drawn on nothing: the sum of the pixels' opacity.
fn opacity(img: &Rendered) -> u64 {
img.pixels.as_chunks::<4>().0.iter().map(|p| p[3] as u64).sum()
}
#[test]
fn synthetic_bold_is_darkened_too() {
// A face with no bold of its own is made bold by stroking its outlines. The stroke reaches
// further than the darkening does, so it has to stroke the darkened outline: the darkening
// then moves the bold text's edges as far as the regular text's, and adds about as much ink.
let added = |bold: bool, scale: f32| {
let (d, runs, area) = glyph_runs("Bold made by stroking the outline", |run| {
if let Draw::Glyphs { synth_bold, .. } = run {
*synth_bold = bold;
}
});
let dark = RenderOptions { text_darkening: 1.0, ..Default::default() };
let (plain, darkened) =
(opacity(&render_items(&d, &runs, area, scale, &RenderOptions::default())), opacity(&render_items(&d, &runs, area, scale, &dark)));
assert!(plain > 0 && darkened > plain, "bold {bold}: plain {plain}, darkened {darkened}");
(darkened - plain) as f64
};
for scale in [1.0, 2.0] {
let (regular, bold) = (added(false, scale), added(true, scale));
assert!(bold > regular * 0.75, "scale {scale}: ink added: {regular} regular, {bold} bold");
}
}
#[test]
fn stretched_hinted_text_is_darkened_as_far_as_unstretched() {
// One letter, hinted, at its own width and scaled to 400 % (`w:w`): the darkening moves each
// edge the same distance on screen, so it adds about the same ink to both.
let added = |stretch: f32| {
let (d, runs, area) = glyph_runs("H", |run| {
if let Draw::Glyphs { x_scale, .. } = run {
*x_scale = stretch;
}
});
let hint = RenderOptions { hinting: true, ..Default::default() };
let dark = RenderOptions { text_darkening: 1.0, ..hint.clone() };
let (plain, darkened) = (opacity(&render_items(&d, &runs, area, 2.0, &hint)), opacity(&render_items(&d, &runs, area, 2.0, &dark)));
assert!(darkened > plain, "stretch {stretch}: plain {plain}, darkened {darkened}");
(darkened - plain) as f64
};
let (own, stretched) = (added(1.0), added(4.0));
assert!(stretched < own * 1.5 && stretched > own * 0.6, "ink added: {own} unstretched, {stretched} stretched");
// The conversion itself: a widening of `px` device pixels, in outline units, is `px` again
// once the outline is on screen.
for (hinted, font_px, stretch) in [(true, 0.02, 1.0), (true, 0.02, 4.0), (false, 0.02, 1.0), (false, 0.02, 4.0)] {
let on_screen = if hinted { stretch } else { font_px * stretch };
assert!((0.25 / widen_unit(hinted, font_px, stretch) * on_screen - 0.25).abs() < 1e-12, "{hinted} {stretch}");
}
}
#[test]
fn an_area_rendered_to_a_pixel_size_fills_it_and_keeps_its_text_on_the_grid() {
let (d, l) = flat_capitals();
let page = &l.pages[0];
let area = wordcraft_geom::Rect::new(0.0, 0.0, page.w, page.h);
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
// A page 1746.155 × 2469.544 pixels at its scale, made 1746 × 2470: a pixel in two thousand off each way.
let scale = 1746.155 / page.w;
let (w, h) = (1746, (page.h * scale).round() as u32 + 1);
let exact = render_area_to(&d, page, area, w, h, &snap);
assert_eq!((exact.width, exact.height), (w, h));
// One scale gives the next whole pixel up each way: not the size asked for.
let up = render_area(&d, page, area, scale, &snap);
assert_eq!(up.width, 1747);
// The text is as it is at the page's own scale, feet on a whole pixel row: scaled that little differently
// across and down, the page is still upright.
let foot_is_dark = |img: &Rendered| {
let (_, foot) = ink_row_span(img);
let w = img.width as usize;
img.pixels[foot * w * 4..(foot + 1) * w * 4].as_chunks::<4>().0.iter().map(|p| p[0]).min().unwrap_or(255) < 16
};
assert!(foot_is_dark(&exact) && foot_is_dark(&up));
assert!(is_upright(Affine::scale_non_uniform(2.0, 2.002)) && is_upright(Affine::scale_non_uniform(2.933, 2.9334)));
assert!(!is_upright(Affine::scale_non_uniform(2.0, 2.01)));
// Hostile sizes and areas: clamped, never a panic.
for (area, w, h) in [
(wordcraft_geom::Rect::new(0.0, 0.0, 0.0, 0.0), 10, 10),
(wordcraft_geom::Rect::new(f32::NAN, f32::INFINITY, f32::NAN, -5.0), 10, 10),
(area, 0, 0),
(area, u32::MAX, 3),
] {
let img = render_area_to(&d, page, area, w, h, &snap);
assert!(img.width >= 1 && img.height >= 1 && img.pixels.len() == img.width as usize * img.height as usize * 4);
}
}
#[test]
fn hinting_sharpens_screen_text_without_making_it_bolder_or_moving_it() {
let mut d =
@@ -2379,35 +2053,6 @@ fn rules_of_one_width_cover_the_same_whole_pixels_at_every_zoom() {
assert!(snap_rule(Affine::scale(2.0), (0.0, 0.0, 9.0, 4.0), 0.5).is_none());
}
#[test]
fn rules_snap_by_the_scale_across_them_on_a_page_scaled_a_little_differently_each_way() {
// A page raster made to fill a whole number of pixels is scaled a pixel in a thousand or two
// differently across and down. A level rule lies where the scale down the page puts it, and
// an upright one where the scale across does.
for (kx, ky) in [(2.0, 2.002), (2.002, 2.0), (2.933, 2.9334), (1.3333, 1.3329)] {
let view = Affine::new([kx, 0.0, 0.0, ky, 37.3, 12.9]);
assert!(is_upright(view));
for i in 0..40 {
let pos = 10.0 + f64::from(i) * 17.37;
let (w_h, (_, oy)) = snap_rule(view, (5.0, pos, 400.0, pos), 0.5).unwrap();
let (w_v, (ox, _)) = snap_rule(view, (pos, 5.0, pos, 400.0), 0.5).unwrap();
for (w, centre, lies) in [(w_h, (pos + oy) * ky + 12.9, pos * ky + 12.9), (w_v, (pos + ox) * kx + 37.3, pos * kx + 37.3)] {
let edge = centre - w / 2.0;
assert!((edge - edge.round()).abs() < 1e-9, "scales {kx} {ky}: edge {edge} is off the pixel grid");
// Snapped onto the grid from where it lies: never further than its own width and half a pixel.
assert!((centre - lies).abs() <= w / 2.0 + 0.5 + 1e-9, "scales {kx} {ky}: moved {} px", centre - lies);
}
}
}
// The case from review: a level rule at 250 pt, half a point wide, at 2.0 across and 2.002 down, is a pixel
// wide and centred on 500.5 already. It stays there.
let view = Affine::scale_non_uniform(2.0, 2.002);
let (w, (_, oy)) = snap_rule(view, (5.0, 250.0, 400.0, 250.0), 0.5).unwrap();
assert_eq!(w, 1.0);
assert!(((250.0 + oy) * 2.002 - 500.5).abs() < 1e-9, "centre {}", (250.0 + oy) * 2.002);
assert_eq!((rule_scale(view, true), rule_scale(view, false)), (2.002, 2.0));
}
/// The same three pictures that don't draw as in the PDF test: each stays a grey box, and the page's
/// pixels are what they were before strict export existed (#6005).
#[test]
+2 -2
View File
@@ -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 = "d73e274a01408ef433a291a667e6014937d72165" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
wordcraft-geom = { workspace = true, features = ["image"] }
wordcraft-doc = { workspace = true }
wordcraft-fonts = { workspace = true }
@@ -76,7 +76,7 @@ craft-ui-test-kit = { workspace = true }
craft = { workspace = true, features = ["ui-testing"] }
[build-dependencies]
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "d73e274a01408ef433a291a667e6014937d72165", features = ["subset"] }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359", features = ["subset"] }
serde_json = { workspace = true }
toml = "1"
+3 -1
View File
@@ -266,7 +266,9 @@ fn main() {
}
let mem_after_typing = memory_mb();
// Edit/Undo burst: 40 discrete paragraph insertions followed by 40 undos.
// Edit/Undo burst: 40 discrete short-text insertions (" {k}") at the current caret (the first
// table cell when the document has a table, otherwise the target paragraph), each in its own
// undo group, followed by 40 undos.
let mut edit_burst = Vec::new();
let mut undo_burst = Vec::new();
for k in 0..40 {
+1
View File
@@ -133,6 +133,7 @@ impl WordApp {
user_origin: false,
read_aloud_error: None,
autosave_path: None,
autosave_choice: None,
read_from: None,
saves_in_flight: Vec::new(),
fallback_chooser: false,
+4 -2
View File
@@ -438,7 +438,7 @@ impl WordApp {
/// Which file on disk the document is in, after `file.save`, `file.saveAs` or `file.open`.
fn note_file_on_disk(&mut self, id: &str, params: &Value, v: &Value) {
// An explicit save to the document's own file lets AutoSave keep writing there.
// A save makes the file eligible for AutoSave without changing the document's switch choice.
if matches!(id, "file.save" | "file.saveAs")
&& v.get("saved").and_then(Value::as_bool) == Some(true)
&& v.get("path").and_then(Value::as_str).map(std::path::Path::new) == self.session.path.as_deref()
@@ -869,6 +869,8 @@ impl WordApp {
};
return Some(self.answer_save_changes(answer));
}
// The app menu's Quit (⌘Q): asks about each unsaved document, as the Dock's Quit does.
"ui.quit" => json!({"quit": self.quit()}),
"ui.openFileDialog" => {
self.open_dialog();
json!({})
@@ -1302,7 +1304,6 @@ pub(crate) fn works_without_document(id: &str) -> bool {
| "tools.customizeRibbon"
| "view.darkMode"
| "view.paperColor"
| "view.textSmoothing"
| "view.marks"
| "view.ruler"
| "view.numeral"
@@ -1320,6 +1321,7 @@ pub(crate) fn works_without_document(id: &str) -> bool {
| "ui.animations"
| "ui.language"
| "ui.saveChanges"
| "ui.quit"
| "ui.openFileDialog"
| "ui.printCancel"
| "ui.fileBrowser"
+59 -15
View File
@@ -1,7 +1,7 @@
use craft::host::{PickId, Picked};
use craft::platform::open::{DroppedFile, Intake};
use craft::quit::{CloseAnswer, CloseGuard, CloseScope, GuardStep};
use craft::ui::dialog::{DialogId, DialogResult, UnsavedChangesDialog};
use craft::ui::dialog::{DialogId, DialogResult, HostedUnsavedChangesDialog, UnsavedChangesDialog};
use craft::ui::shell::embed::CloseDecision;
use super::{AutoSaveBlock, PromptSave, Value, WordApp, file_dialogs, i18n, json, keeps_everything, panes, printing};
@@ -151,7 +151,7 @@ impl WordApp {
dialog = dialog.reason(reason);
}
// PLAN: assumed `WordApp::dialog_host: DialogHost`, the shown window's
let id = self.dialog_host.open(dialog);
let id = self.dialog_host.open(HostedUnsavedChangesDialog::new(dialog));
if let Some(closing) = self.closing.as_mut() {
closing.prompt = Some(id);
closing.window = self.windows.shown();
@@ -246,7 +246,7 @@ impl WordApp {
let ctx = self.ctx.clone().unwrap_or_default();
if let Some(host) = self.window_dialog_host_mut(window) {
host.cancel_by_id(&ctx, id);
let _ = host.take_by_id::<UnsavedChangesDialog>(id);
let _ = host.take_by_id::<HostedUnsavedChangesDialog>(id);
}
}
@@ -262,7 +262,7 @@ impl WordApp {
/// from `logic`.
pub(crate) fn pump_close_prompt(&mut self) {
let Some((window, id)) = self.closing.as_ref().and_then(|c| c.prompt.map(|id| (c.window, id))) else { return };
let Some(result) = self.window_dialog_host_mut(window).and_then(|host| host.take_by_id::<UnsavedChangesDialog>(id)) else { return };
let Some(result) = self.window_dialog_host_mut(window).and_then(|host| host.take_by_id::<HostedUnsavedChangesDialog>(id)) else { return };
if let Some(ctx) = self.ctx.as_ref() {
crate::dialogs::chrome::forget_nudge(ctx, id);
}
@@ -285,6 +285,16 @@ impl WordApp {
if self.raise_closing().is_some() {
return CloseDecision::Hold;
}
// Nothing is open, so nothing to ask about (also under a windowless root, whose last document window going is
// what asks).
if self.session.documents().is_empty() {
return CloseDecision::Close;
}
// A windowless root has no window of its own: its close is a quit (the OS quit, or the last document window
// going), never one window's close.
if self.ctx.as_ref().is_some_and(craft::ui::runtime::windows::windowless_root) {
return if self.close_requested() { CloseDecision::Close } else { CloseDecision::Hold };
}
if self.closes_a_window() {
// The root window's close button closes that window alone (File › Close in it, which asks
// about unsaved changes first); the framework leaves the root's window open on `Hold`, and
@@ -541,9 +551,27 @@ impl WordApp {
if let Some(result) = self.raise_closing() {
return Ok(result);
}
if self.closes_only_its_window("file.close", params) {
// `save: true` still writes the document, which stays open in the other windows.
if params.get("save").and_then(Value::as_bool) == Some(true)
&& let Some(pending) = self.save_for_close()?
{
return Ok(pending);
}
}
if self.closes_only_its_window("file.close", params) && self.close_window_only() {
return Ok(json!({"closed": true, "window": true}));
}
if params.get("save").and_then(Value::as_bool) == Some(true) {
// A comment still being typed refuses before anything is written.
if let Some(e) = crate::control::close_refused(self, "file.close", params) {
return Err(e.into());
}
// Automation's `save: true`: write the document, then close it. Never a prompt (spec rule 8).
if let Some(pending) = self.save_for_close()? {
return Ok(pending);
}
}
if let Some(e) = crate::control::close_refused(self, "file.close", params) {
return Err(e.into());
}
@@ -578,6 +606,24 @@ impl WordApp {
Ok(json!({"closed": true}))
}
/// `file.close` with `save: true`: save the shown document if it has unsaved work. `Some` is
/// the reply when the save finishes later (the browser's picker). A document with no file
/// to write has nowhere to save without asking, so that is an error, not a prompt.
fn save_for_close(&mut self) -> Result<Option<Value>, String> {
if !self.document_unsaved() {
return Ok(None);
}
if self.session.path.is_none() || self.legacy_word_path() {
return Err("the document has no file to save to: use file.saveAs first, or pass {\"force\": true} to discard it".into());
}
match self.save_for_prompt()? {
PromptSave::Saved => Ok(None),
// lean: only the browser picker saves later and it has no control channel, so the close is not resumed.
PromptSave::Later => Ok(Some(json!({"pending": "save"}))),
PromptSave::NotSaved => Err("the document was not saved, so it stays open".into()),
}
}
/// These paths have readers but no writer, so an interactive save needs another format.
pub(super) fn legacy_word_path(&self) -> bool {
self.session
@@ -662,7 +708,8 @@ impl WordApp {
}
/// Why AutoSave can't cover the document, or `None` when it can: it writes only a file the
/// user saved to in this session, in a format that keeps everything, and never in the browser
/// user saved to in this session or explicitly enabled after opening it from disk. The format
/// must keep everything, and AutoSave never writes in the browser
/// (a page can't write to the user's files; saving there is a download, #176).
pub fn autosave_block(&self) -> Option<AutoSaveBlock> {
if self.browser_saves() {
@@ -673,7 +720,8 @@ impl WordApp {
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
return Some(AutoSaveBlock::Format { name });
}
if !self.saved_here() {
let opened_and_enabled = self.autosave_choice == Some(true) && self.read_from.as_ref() == Some(path);
if !self.saved_here() && !opened_and_enabled {
return Some(AutoSaveBlock::NotSavedHere);
}
None
@@ -681,7 +729,7 @@ impl WordApp {
/// Whether AutoSave covers the document: it is on and nothing blocks it ([`Self::autosave_block`]).
pub fn autosaves(&self) -> bool {
self.autosave && self.autosave_block().is_none()
self.autosave && self.autosave_choice != Some(false) && self.autosave_block().is_none()
}
/// What the AutoSave switch can't lift: [`Self::autosave_block`], less a file read from disk
@@ -701,15 +749,10 @@ impl WordApp {
Some(Value::Bool(on)) => *on,
Some(_) => return Err("`value` must be true or false".into()),
};
if on && self.autosave_block().is_some() {
if let Some(block) = self.autosave_switch_block() {
return Err(block.reason());
}
self.autosave_path = self.session.path.clone();
}
if !on {
self.autosave_path = None;
if on && let Some(block) = self.autosave_switch_block() {
return Err(block.reason());
}
self.autosave_choice = Some(on);
self.autosave = on;
self.session.autosave = on;
Ok(json!({"value": on}))
@@ -723,6 +766,7 @@ impl WordApp {
if let Err(e) = self.session.run("file.save", &json!({})) {
log::warn!("AutoSave failed: {e}");
self.autosave_path = None;
self.autosave_choice = None;
self.status(i18n::fmt(tl!("AutoSave failed: {error}. Save the document to turn AutoSave back on."), &[("error", &e.to_string())]));
}
}
+1 -1
View File
@@ -60,7 +60,7 @@ impl ThumbSource<ThumbKey> for TemplateThumbs {
let Some(page) = layout.pages.first() else { return ThumbRender::Blank };
// The longest side of the page is `request.side` pixels; the store never asks for zero.
let scale = request.side as f32 / page.w.max(page.h).max(1.0);
let image = wordcraft_render::render_page(&session.doc, page, scale, &crate::canvas::thumbnail_render_options());
let image = wordcraft_render::render_page(&session.doc, page, scale, &crate::canvas::screen_render_options());
let pixels = image.to_straight();
ThumbRender::Ready(egui::ColorImage::from_rgba_unmultiplied([image.width as usize, image.height as usize], &pixels))
}
+3 -18
View File
@@ -64,7 +64,7 @@ pub(crate) use links::follow_link;
use links::{field_link, is_followable_link, is_generated_bookmark_link};
pub use navigation::page_to_screen;
use navigation::viewed_page;
pub(crate) use pages::{PageKeys, dark_page, page_doc, page_screen_scale, preview_sel, screen_render_options, thumbnail_render_options};
pub(crate) use pages::{PageKeys, dark_page, page_doc, page_screen_scale, preview_sel, screen_render_options};
use pages::{page_render_options, shown_layout};
use reading::{reading_anchor_page, reading_page_start, web_layout_width};
use story::dims_body;
@@ -111,11 +111,6 @@ pub struct CanvasState {
/// The page asks for the keyboard between this pass and the next ([`CanvasState::focus_page_after_pass`]): always
/// (no ids), or only while focus is still on one of the ids.
focus_after_pass: Option<Vec<egui::Id>>,
/// Where the page view put its pages (page, place in screen points) the last time two passes running put
/// them in the same places: the view at rest. Page pictures are made to fill these places exactly
/// (`source::WordPages`); while the view moves they stay as they were, so a scroll or a zoom under way makes
/// no picture again for a place it is only passing through.
pub(crate) settled_pages: Vec<(usize, Rect)>,
/// How many page pictures the page view kept resident after the last pass (S-L352).
pub(crate) resident_pictures: usize,
/// The caret's glide and blink.
@@ -426,7 +421,6 @@ impl Default for CanvasState {
shown: ShownPages::default(),
focus_pending: true,
focus_after_pass: None,
settled_pages: Vec::new(),
resident_pictures: 0,
glide: crate::caret_glide::CaretGlide::default(),
comments: Default::default(),
@@ -757,8 +751,7 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
let columns = Rect::from_min_max(full.min, pos2(full.max.x, (full.max.y - metrics.nav_bar).max(full.min.y)));
let footer = Rect::from_min_max(pos2(full.min.x, columns.max.y), full.max);
let mut state = std::mem::take(&mut app.canvas.reading);
// Read Mode sizes its columns itself: no view scale to rasterise at.
let source = source::WordPages::new(app, layout, false, None, None);
let source = source::WordPages::new(app, layout, false, None);
let out = ReadingView::new(tl!("Document"), &source, &mut state, paper).zoom(zoom).show_at(ui, columns);
// The page-turn row sits at the bottom right, as in v0.19.1 (the far end, so the bottom left in a right-to-left UI),
// the page view's side margin in from the edge.
@@ -847,7 +840,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
let options =
LayoutOptions { markup: f64::from(markup_width(app)), min_columns: if app.session.view.multi_page { 2 } else { 1 }, ..LayoutOptions::WORD };
let paper = DataColor::new(paper_color(app));
let source = source::WordPages::new(app, layout, dim_body, hidden, Some(scale as f32));
let source = source::WordPages::new(app, layout, dim_body, hidden);
// The describer owns its snapshot, as the source does, so the page view can hold it while the body edits the app.
let described = preview_sel(app).unwrap_or(app.session.sel_ends()).clone();
let describer = crate::a11y::DocumentDescriber::new(source.doc(), layout.clone(), (described.anchor.clone(), described.focus.clone()));
@@ -1040,14 +1033,6 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
// A window's page has the keyboard from its first pass (production's `want_focus` started on), so typing lands
// without a click; a modal dialog keeps the keyboard until it closes.
let view_rect = body_view.map_or(body_rect, |v| v.rect);
// The same places two passes running: the view is at rest, and these are the places pictures are made for.
let placed = |pages: &[PlacedPage]| pages.iter().map(|p| (p.page, p.rect)).collect::<Vec<_>>();
let now = placed(&out.pages);
if now == placed(&app.canvas.shown.pages) && now != app.canvas.settled_pages {
app.canvas.settled_pages = now;
// The pictures of the places just settled are made on the next pass.
ui.ctx().request_repaint();
}
app.canvas.shown =
ShownPages { rect: body_rect, pages: out.pages.clone(), laid: laid_rects(&out), view: view_rect, canvas: Some(out.canvas.response.id) };
if app.canvas.focus_pending && !app.modal_open() {
+25 -13
View File
@@ -30,7 +30,7 @@ struct BalloonItems {
}
/// Comment balloons in the markup area right of each page, joined to their anchors, with each comment's replies in
/// its card. Clicking a card selects it, like Word: its text becomes editable in place, with Reply, Resolve and
/// its card. Clicking a card selects it, like Word: a double click makes its text editable in place, with Reply, Resolve and
/// Delete (the same commands as the Comments pane).
pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::PageViewOutput, layout: &DocLayout) {
app.canvas.balloon_rects.clear();
@@ -63,6 +63,26 @@ pub(crate) fn balloons(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui::P
for edit in shown.edits {
apply(app, &cards, edit);
}
open_edit_on_double_click(app, ui);
}
/// A double click on the selected card's own text opens its comment for editing, as craft's comments pane does. A click
/// that lands in a field or on a button (Reply, Resolve, the menu) is not one.
// lean: mouse only; a keyboard path (Enter/F2 on the selected card) is a follow-up.
fn open_edit_on_double_click(app: &mut WordApp, ui: &Ui) {
let Some(id) = app.canvas.selected_balloon() else { return };
if app.canvas.comments.editing.is_some() || ui.ctx().egui_wants_keyboard_input() {
return;
}
let at = ui.input(|i| i.pointer.button_double_clicked(egui::PointerButton::Primary).then(|| i.pointer.interact_pos())).flatten();
let Some(at) = at else { return };
let on_card = app.canvas.balloon_rects.iter().any(|(i, r)| *i == id && r.contains(at));
if !on_card || !crate::app::command_board::command_enabled(app, "review.editComment") {
return;
}
let Some(c) = app.session.doc.comments.get(&id) else { return };
let text = app.session.doc.plain_text(StoryRef::Part(c.part));
app.canvas.comments.edit(thread_id(id), 0, text);
}
/// Applies what a card reported through the commands the Comments pane uses.
@@ -243,25 +263,17 @@ fn write_back(app: &mut WordApp, id: u32) {
let _ = crate::panes::commit_reply(app, id);
}
/// Makes comment `id` the selected card with its own text open for editing, writing back the draft of the one edited
/// before. The card selects itself on a click; this opens its edit so the field has the keyboard.
/// Makes comment `id` the selected card, writing back the draft of the one edited before. As in Word, selecting a card
/// puts no message into edit (that hides its Reply); an edit starts on a double click on the selected card.
fn focus_balloon(app: &mut WordApp, id: u32) {
let before = app.canvas.comments.editing.as_ref().and_then(|(t, ..)| app_id(*t)).filter(|b| *b != id);
if let Some(before) = before {
write_back(app, before);
}
// Where comments can't change (a read-only document) the card is selected with no edit open: nothing is typed.
let editable = crate::app::command_board::command_enabled(app, "review.editComment");
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);
if comments.editing.as_ref().is_none_or(|(t, ..)| *t != thread) {
comments.editing = text.map(|t| (thread, 0, t));
}
app.canvas.comments.selected = craft::behavior::Selection::single(thread_id(id));
}
/// Select a comment's balloon (its text gets the keyboard), writing back any edit in the one selected before.
/// Select a comment's balloon (no edit opens), writing back any edit in the one selected before.
pub fn select_balloon(app: &mut WordApp, id: u32) {
if app.canvas.selected_balloon() == Some(id) {
return;
+10 -110
View File
@@ -1,7 +1,5 @@
use std::fmt::Write as _;
use craft::ui::primitives::textures::MAX_TEXTURE;
use super::{DocLayout, Hash, Hasher, Page, Placed, Pos, Rect, WordApp, json};
/// Streams `Debug` formatting directly into a [`Hasher`] without intermediate `String` allocations.
@@ -22,9 +20,6 @@ impl std::fmt::Write for HashFmt<'_> {
// revision that the pages' pictures key on directly.
pub(super) fn view_key(app: &WordApp, dim_body: bool, hidden: Option<&Pos>) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
// A page drawn under the system's earlier text settings, or the user's earlier smoothing choice, must not pass
// for one drawn under these.
(crate::screen_text::current().key(), app.session.prefs.text_smoothing).hash(&mut h);
let v = &app.session.view;
(v.marks, app.session.prefs.marks, v.show_markup, v.dark_mode, wordcraft_render::DARK_PAPER, v.hide_ink, v.draw.replay).hash(&mut h);
(v.read_mode, v.read_page_color, app.session.prefs.paper_color).hash(&mut h);
@@ -185,9 +180,6 @@ pub(crate) fn dark_page(app: &WordApp) -> bool {
/// Render options for this view's page rasters: marks, markup, dark page, header/body dimming.
pub(super) fn page_render_options(app: &WordApp, dim_body: bool) -> wordcraft_render::RenderOptions {
let mut opts = screen_render_options();
// Pages, and only pages, follow the system's own text settings once they are known ([`crate::screen_text`]);
// `view_key` has them, so a change redraws the pages.
crate::screen_text::current().apply(&mut opts);
opts.display.marks = app.session.view.marks;
opts.display.always = app.session.prefs.marks;
opts.display.placeholders = true;
@@ -216,107 +208,15 @@ pub(super) fn page_render_options(app: &WordApp, dim_body: bool) -> wordcraft_re
opts
}
/// Subpixel (LCD) text for the page rasters of a screen with `ppp` device pixels per point, as File › Options ›
/// General › Screen text smoothing says. "Use system setting" draws it where the system asks for it
/// ([`crate::screen_text`]) and the screen is below two device pixels per point: on a denser screen the stripes are
/// too fine to gain from, and a page has four times the pixels to rasterise three times. "Subpixel (LCD)" draws it
/// on any screen, in the system's stripe order, RGB when it names none (macOS never does).
pub(super) fn lcd_for(
choice: wordcraft_engine::cmd::view::TextSmoothing,
asked: Option<crate::screen_text::SubpixelOrder>,
stripes: Option<crate::screen_text::SubpixelOrder>,
ppp: f32,
) -> Option<wordcraft_render::LcdOrder> {
use crate::screen_text::SubpixelOrder;
use wordcraft_engine::cmd::view::TextSmoothing;
use wordcraft_render::LcdOrder;
let order = |stripes: SubpixelOrder| match stripes {
SubpixelOrder::Rgb => LcdOrder::Rgb,
SubpixelOrder::Bgr => LcdOrder::Bgr,
};
match choice {
TextSmoothing::Grayscale => None,
// The user's own choice, in the order of their screen even where the system has smoothing off (a BGR panel
// with ClearType off must not get RGB edges).
TextSmoothing::Subpixel => Some(asked.or(stripes).map(order).unwrap_or(LcdOrder::Rgb)),
// Written so a density that isn't a number is greyscale too.
TextSmoothing::System => asked.map(order).filter(|_| ppp < 2.0),
}
}
/// The scale (pixels per document point) to rasterise a page picture at, and whether that is the screen's own.
///
/// The page view asks for a picture by its longest side in pixels, `side`, rounded up to a multiple of `step`, and
/// scales what it gets to the page's place on screen. Rasterised at `side`, a page is up to `step` pixels larger
/// than it shows and every glyph is resampled on the way to the screen, which undoes baselines put on whole pixels
/// and makes subpixel text wrong (each colour's edge off its stripe). `native` is the view's own scale, device
/// pixels per document point, when it is known: where it accounts for the side asked for (the page's `longest`
/// side, in points, at that scale rounds up to `side`), the picture is rasterised at exactly that scale, one raster
/// pixel per device pixel. Otherwise (another view's request, a fit zoom not settled yet, a part of a page shown
/// reduced) it is rasterised at the side asked for, as before, and is not the screen's own.
pub(super) fn raster_scale(side: u32, step: u32, longest: f32, native: Option<f32>) -> (f32, bool) {
let largest = MAX_TEXTURE as f32;
// `side / longest * longest` can come out a hair over `side`, which rounds up to a pixel too many for a texture.
let mut asked = side as f32 / longest;
if side <= MAX_TEXTURE && (longest * asked).ceil() > largest {
asked = asked.next_down().next_down();
}
let fits = |scale: f32| {
let pixels = longest * scale;
scale.is_finite() && scale > 0.0 && pixels.is_finite() && pixels <= side as f32 + 0.5 && pixels > side as f32 - step as f32 - 0.5
// A pixel over the largest texture and the store halves the whole picture.
&& pixels.ceil() <= largest
};
match native.filter(|scale| longest.is_finite() && longest > 0.0 && step > 0 && fits(*scale)) {
Some(scale) => (scale, true),
None => (asked, false),
}
}
/// The size in device pixels of the place on screen a page's picture is drawn in, when a picture of about
/// `expected` pixels (its size at the view's scale) is that place's own.
///
/// The page view draws a picture as its painter does every picture: the place (`page`, in screen points, or the
/// part `region` of it, in fractions) is rounded to whole pixels, and the picture is fitted inside it by its own
/// proportions. A picture of exactly the rounded place's size is drawn one pixel for one. Any other is scaled:
/// rasterised a whole pixel up each way, as a single scale gives, a 2016 × 2851 pixel place gets a 2017 × 2852
/// picture squeezed by a twentieth of a percent, and the text slides off the pixel grid and back down the page.
/// The rounded size depends on where the place starts, so it comes from where the view last put the page, not
/// from the page's size. `None` where the place is not within a pixel and a half of `expected` each way: a
/// place left over from another zoom, or numbers that aren't.
pub(super) fn picture_pixels(page: egui::Rect, region: Option<egui::Rect>, ppp: f32, expected: (f32, f32)) -> Option<(u32, u32)> {
let place = match region {
Some(part) => {
let at = |f: egui::Pos2| egui::pos2(page.min.x + f.x * page.width(), page.min.y + f.y * page.height());
egui::Rect::from_min_max(at(part.min), at(part.max))
}
None => page,
};
let side = |lo: f32, hi: f32, expected: f32| {
let pixels = (hi * ppp).round() - (lo * ppp).round();
(pixels.is_finite() && expected.is_finite() && pixels >= 1.0 && (pixels - expected).abs() <= 1.5).then_some(pixels as u32)
};
Some((side(place.min.x, place.max.x, expected.0)?, side(place.min.y, place.max.y, expected.1)?))
}
/// Render options for rasters shown on screen other than the pages themselves (style and font previews, a dragged
/// object), so their text looks as it does in the platform's other apps (exports never change): on macOS it is
/// darkened the way the system draws it; on Linux and the BSDs it is hinted lightly, as FreeType's `hintslight`
/// draws it there (not darkened: hinted text already has FreeType's weight, and darkening made it look semi-bold).
/// Baselines sit on whole device pixels (hinting does that; unhinted text is moved there). These are fixed per
/// platform: such rasters are cached without the system's text settings in their keys, so they must not follow
/// them. Pages do ([`page_render_options`]).
/// Render options for page rasters shown on screen, so a page looks as text does in the
/// platform's other apps (exports never change): on macOS, text is darkened the way the system
/// draws it; on Linux and the BSDs it is hinted lightly, as FreeType's `hintslight` draws it
/// there (not darkened: hinted text already has FreeType's weight, and darkening made it
/// look semi-bold).
pub(crate) fn screen_render_options() -> wordcraft_render::RenderOptions {
let mut opts = wordcraft_render::RenderOptions { baseline_snap: true, ..Default::default() };
crate::screen_text::ScreenText::PLATFORM.apply(&mut opts);
opts
}
/// Render options for the template thumbnails of File › New: the platform's text, as [`screen_render_options`],
/// without the baseline snapping. A thumbnail is a page shrunk to a tile, drawn as it was before pages were
/// sharpened.
pub(crate) fn thumbnail_render_options() -> wordcraft_render::RenderOptions {
let mut opts = wordcraft_render::RenderOptions::default();
crate::screen_text::ScreenText::PLATFORM.apply(&mut opts);
opts
wordcraft_render::RenderOptions {
text_darkening: cfg!(target_os = "macos"),
hinting: cfg!(all(unix, not(target_os = "macos"))),
..Default::default()
}
}
+10 -24
View File
@@ -60,19 +60,10 @@ pub(crate) fn page_rulers(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui
.map(|cg| cg.gaps.iter().map(|&(l, r)| if rtl { (col_end - r, col_end - l) } else { (l - col_x, r - col_x) }).collect())
.unwrap_or_default();
let row_cells = caret_row(app, layout, pi);
let borders_page: Vec<f32> =
row_cells.first().map(|f| std::iter::once(f.x).chain(row_cells.iter().map(|b| b.right())).collect()).unwrap_or_default();
// While a column marker is dragged the markers show where the preview puts their borders (the ruler draws them
// where it is told), so the grabbed marker follows the pointer and the ones right of it move along.
let caret_row_idx = app.session.sel.focus.path.cell().map(|(_, r, _)| r);
let row = crate::table_resize::ruler_row(app, layout, pi);
// Both the ruler markers and Alt widths use the preview of the caret row's actual grid lines.
let mods = crate::table_resize::mods_now(ui.ctx());
let borders: Vec<f32> = borders_page
.iter()
.enumerate()
.map(|(line, &x)| to_start(crate::table_resize::caret_drag(app, pi).and_then(|d| d.ruler_line_x(mods, caret_row_idx, line)).unwrap_or(x)))
.collect();
let row_y = row_cells.first().map_or(0.0, |b| b.y + b.h / 2.0);
let borders: Vec<f32> = row.as_ref().map(|r| r.positions(app, pi, mods).into_iter().map(to_start).collect()).unwrap_or_default();
let bottoms = row_bottoms(app, layout, pi);
let rows: Vec<f32> = bottoms.iter().map(|(_, b)| b.bottom()).collect();
// A section whose columns `column_drag` refuses shows its gaps without grips.
@@ -159,10 +150,13 @@ pub(crate) fn page_rulers(app: &mut WordApp, ui: &mut Ui, out: &craft::pages::ui
}
}
if let Some(d) = output.ruler.column {
let at = borders_page.get(d.border.index).map(|&x| (x, row_y));
let to = (to_page(d.border.position), row_y);
table_drag(app, layout, pi, BorderDrag { phase: d.phase, edge: Edge::Column(d.border.index), at, to, mods: d.mods });
if let Some(d) = output.ruler.column
&& let Some(row) = &row
&& let Some(&(line, x)) = row.borders.get(d.border.index)
{
let at = Some((x, row.y));
let to = (to_page(d.border.position), row.y);
table_drag(app, layout, pi, BorderDrag { phase: d.phase, edge: Edge::Column(line), at, to, mods: d.mods });
}
if let Some(d) = output.row {
let at = bottoms.get(d.index).map(|(_, b)| (b.x + b.w / 2.0, b.bottom()));
@@ -382,14 +376,6 @@ pub(crate) fn text_area(app: &WordApp, layout: &DocLayout, page: usize) -> Optio
Some((b.x + left, (b.w - left - right).max(0.0)))
}
/// The caret row's cells on `page`, left to right.
fn caret_row(app: &WordApp, layout: &DocLayout, page: usize) -> Vec<wordcraft_geom::Rect> {
let Some((_, r, _)) = app.session.sel.focus.path.cell() else { return Vec::new() };
let mut row: Vec<wordcraft_geom::Rect> = cells(app, layout, page).into_iter().filter(|(row, ..)| *row == r).map(|(.., b)| b).collect();
row.sort_by(|a, b| a.x.total_cmp(&b.x));
row
}
/// Each row of the caret's table on `page` with the cell its bottom is taken from: its shortest box, as a vertically
/// merged cell's box spans all its rows, and of those the leftmost.
fn row_bottoms(app: &WordApp, layout: &DocLayout, page: usize) -> Vec<(usize, wordcraft_geom::Rect)> {
+17 -90
View File
@@ -8,12 +8,12 @@ use std::sync::Arc;
use craft::behavior::kurbo::Size;
use craft::pages::ui::PageSource;
use craft::ui::primitives::textures::{LoadedPicture, MAX_TEXTURE, Revision, ThumbRender, ThumbRequest, ThumbSource};
use craft::ui::primitives::textures::{LoadedPicture, Revision, ThumbRender, ThumbRequest, ThumbSource};
use wordcraft_doc::{Document, Pos};
use wordcraft_layout::DocLayout;
use super::WordApp;
use super::pages::{PageKeys, lcd_for, page_render_options, page_shows, picture_pixels, raster_scale, view_key};
use super::pages::{PageKeys, page_render_options, page_shows, view_key};
/// A page dimension (points) safe to lay out: finite, at least 1 pt, at most `cap`.
fn dim(v: f32, cap: f32) -> f64 {
@@ -30,38 +30,13 @@ pub(super) struct WordPages {
options: wordcraft_render::RenderOptions,
/// The page a drag took an object off, and the object: rendered without it.
hidden: Option<(usize, Pos)>,
/// Screen points per document point in the view these pages show in, when it is one whose pages are drawn at
/// that scale (the page view); `None` where the view sizes its pages itself (Read Mode's columns). With the
/// screen's density it gives the scale at which a picture is the screen's own ([`raster_scale`]).
view_scale: Option<f32>,
/// Where the page view put each page (page, its place in screen points) the last time the view was at rest;
/// empty for a view that sizes its pages itself. A picture is made exactly as many pixels each way as its
/// place is ([`picture_pixels`]).
placed: Vec<(usize, egui::Rect)>,
/// File › Options › General › Screen text smoothing, and what the system says of the screen's text.
smoothing: wordcraft_engine::cmd::view::TextSmoothing,
screen_text: crate::screen_text::ScreenText,
}
/// The page view asks for pictures whose longest side is a multiple of this many pixels
/// (`ThumbRequest::side`).
const SIDE_STEP: u32 = 16;
impl WordPages {
/// The source of `layout` for this pass. The page fingerprints move out of the app for the pass; give them back
/// with [`WordPages::into_keys`].
/// `view_scale` is the view's screen points per document point where its pages are drawn at exactly that scale,
/// so that their pictures can be rasterised one pixel per device pixel.
pub(super) fn new(app: &mut WordApp, layout: &Arc<DocLayout>, dim_body: bool, hidden: Option<(usize, Pos)>, view_scale: Option<f32>) -> Self {
let view_scale = view_scale.filter(|scale| scale.is_finite() && *scale > 0.0);
let placed = if view_scale.is_some() { app.canvas.settled_pages.clone() } else { Vec::new() };
let view = {
// A picture rasterised for another zoom is not this zoom's, even where the side asked for is the same.
let mut h = DefaultHasher::new();
(view_key(app, dim_body, hidden.as_ref().map(|(_, p)| p)), view_scale.map(f32::to_bits)).hash(&mut h);
h.finish()
};
let (smoothing, screen_text) = (app.session.prefs.text_smoothing, crate::screen_text::current());
pub(super) fn new(app: &mut WordApp, layout: &Arc<DocLayout>, dim_body: bool, hidden: Option<(usize, Pos)>) -> Self {
let view = view_key(app, dim_body, hidden.as_ref().map(|(_, p)| p));
let options = page_render_options(app, dim_body);
let doc = if let Some((_, preview, _, _)) = &app.canvas.table_preview_layout {
Arc::new(preview.clone())
@@ -76,8 +51,7 @@ impl WordPages {
}
}
};
let keys = RefCell::new(std::mem::take(&mut app.canvas.page_keys));
WordPages { doc, layout: layout.clone(), keys, view, options, hidden, view_scale, placed, smoothing, screen_text }
WordPages { doc, layout: layout.clone(), keys: RefCell::new(std::mem::take(&mut app.canvas.page_keys)), view, options, hidden }
}
/// The pass's document snapshot, shared with the accessibility describer so the pass holds one copy.
@@ -91,26 +65,16 @@ impl WordPages {
}
}
/// What a request for a page's picture is rasterised as.
pub(super) struct RasterPlan {
/// The whole page, or only `area` of it.
pub(super) whole: bool,
/// The part of the page to rasterise, in document points.
pub(super) area: wordcraft_geom::Rect,
/// Pixels per document point.
pub(super) scale: f32,
/// The picture's size in pixels where it is made to fill its place on screen exactly; `None` for one made at
/// `scale`, a whole pixel up each way.
pub(super) pixels: Option<(u32, u32)>,
pub(super) options: wordcraft_render::RenderOptions,
}
impl ThumbSource<usize> for WordPages {
fn revision(&self, page: &usize, _request: &ThumbRequest) -> Revision {
let mut h = DefaultHasher::new();
page_shows(&mut self.keys.borrow_mut(), &self.layout, *page, self.view).hash(&mut h);
Revision::new(h.finish())
}
impl WordPages {
/// What of page `index` a picture for `request` shows and how large it is made: whether it is the whole page,
/// the area in document points, the pixels per point, whether that is the screen's own scale, and the picture's
/// size in pixels where it is made to fill its place exactly. `None` for a page the layout doesn't have.
fn geometry(&self, index: usize, request: &ThumbRequest) -> Option<(bool, wordcraft_geom::Rect, f32, bool, Option<(u32, u32)>)> {
let p = self.layout.pages.get(index)?;
fn render(&self, page: &usize, request: &ThumbRequest) -> ThumbRender {
let index = *page;
let Some(p) = self.layout.pages.get(index) else { return ThumbRender::Blank };
let (pw, ph) = (dim(p.w, 1e5) as f32, dim(p.h, 1e6) as f32);
let whole = request.region.is_none();
let (x0, y0, x1, y1) = match request.region {
@@ -120,51 +84,14 @@ impl WordPages {
let area = wordcraft_geom::Rect::new(x0 * pw, y0 * ph, ((x1 - x0) * pw).max(0.01), ((y1 - y0) * ph).max(0.01));
let longest = area.w.max(area.h);
let cap = wordcraft_render::MAX_SIDE as f32 / longest;
// At the screen's own scale where the view's zoom accounts for the side asked for, so no glyph is resampled
// on its way to the screen; else at the side asked for.
let (scale, own) = raster_scale(request.side, SIDE_STEP, longest, self.view_scale.map(|s| s * request.pixels_per_point));
let own = own && scale <= cap;
let scale = request.side as f32 / longest;
let scale = if scale.is_finite() { scale.clamp(0.01, cap.max(0.01)) } else { 1.0 };
// Exactly as many pixels each way as the picture's place on screen has, where that is known and is this
// scale's: a pixel more and the page view scales the picture into its place.
let place = self.placed.iter().find(|(page, _)| *page == index).map(|(_, rect)| *rect);
let pixels = place
.filter(|_| own)
.and_then(|place| picture_pixels(place, request.region, request.pixels_per_point, (area.w * scale, area.h * scale)))
// A place can round to a pixel more than the largest texture, and a larger picture is halved.
.filter(|(w, h)| *w.max(h) <= MAX_TEXTURE);
Some((whole, area, scale, own, pixels))
}
/// How page `index` is rasterised for `request`; `None` for a page the layout doesn't have.
pub(super) fn plan(&self, index: usize, request: &ThumbRequest) -> Option<RasterPlan> {
let (whole, area, scale, own, pixels) = self.geometry(index, request)?;
let (doc, layout) = (Arc::clone(&self.doc), Arc::clone(&self.layout));
let mut options = self.options.clone();
options.display.hide_object = self.hidden.as_ref().filter(|(hidden, _)| *hidden == index).map(|(_, pos)| pos.clone());
// Subpixel text only on a picture that is the screen's own: scaled, each colour's edge would miss its stripe.
options.lcd = lcd_for(self.smoothing, self.screen_text.subpixel, self.screen_text.stripes, request.pixels_per_point).filter(|_| own);
Some(RasterPlan { whole, area, scale, pixels, options })
}
}
impl ThumbSource<usize> for WordPages {
fn revision(&self, page: &usize, request: &ThumbRequest) -> Revision {
let mut h = DefaultHasher::new();
page_shows(&mut self.keys.borrow_mut(), &self.layout, *page, self.view).hash(&mut h);
// A picture made for another place's pixel size is not this place's.
self.geometry(*page, request).and_then(|(.., pixels)| pixels).hash(&mut h);
Revision::new(h.finish())
}
fn render(&self, page: &usize, request: &ThumbRequest) -> ThumbRender {
let index = *page;
let Some(RasterPlan { whole, area, scale, pixels, options }) = self.plan(index, request) else { return ThumbRender::Blank };
let (doc, layout) = (Arc::clone(&self.doc), Arc::clone(&self.layout));
ThumbRender::Later(Box::new(move |_cancel| {
let Some(page) = layout.pages.get(index) else { return Ok(LoadedPicture::Blank) };
let img = if let Some((w, h)) = pixels {
wordcraft_render::render_area_to(&doc, page, area, w, h, &options)
} else if whole {
let img = if whole {
wordcraft_render::render_page(&doc, page, scale, &options)
} else {
wordcraft_render::render_area(&doc, page, area, scale, &options)
+21 -300
View File
@@ -793,6 +793,24 @@ fn the_text_pointer_stays_off_the_grey_around_the_page() {
assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "press and move in one frame keep the text pointer");
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.step();
// A Ctrl/⌘ press in the grey area is ignored: no unit selection starts and the pointer stays an arrow.
let ctrl = egui::Modifiers::COMMAND;
h.event(egui::Event::PointerMoved(beside));
h.step();
h.event(egui::Event::ModifiersChanged(ctrl));
h.event(egui::Event::PointerButton { pos: beside, button: egui::PointerButton::Primary, pressed: true, modifiers: ctrl });
h.step();
assert!(h.state().canvas.unit_drag.is_none(), "a Ctrl/⌘ press in the grey area does not start a unit selection");
assert!(!h.state().canvas.dragging, "a Ctrl/⌘ press in the grey area does not start a drag");
assert!(h.state().session.sel.is_collapsed(), "a Ctrl/⌘ press in the grey area does not select text");
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow during a Ctrl/⌘ press in the grey area");
h.event(egui::Event::PointerMoved(further_beside));
h.step();
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "arrow during a Ctrl/⌘ drag in the grey area");
h.event(egui::Event::PointerButton { pos: further_beside, button: egui::PointerButton::Primary, pressed: false, modifiers: ctrl });
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
h.step();
}
/// #4410: with the Format Painter armed, a double-click on a word paints that word, and the
@@ -2291,209 +2309,6 @@ fn the_view_key_changes_when_a_drag_takes_an_object_off_the_page() {
assert_eq!(hidden, view_key(&app, false, Some(&object)), "the same drag keeps the key: no re-render every frame");
}
#[test]
fn only_pages_follow_the_systems_text_settings() {
use crate::screen_text::ScreenText;
// Previews and thumbnails are cached without the system's settings in their keys: they are
// drawn the platform's fixed way. Thumbnails are not baseline-snapped either.
let (screen, thumb) = (screen_render_options(), thumbnail_render_options());
for opts in [&screen, &thumb] {
assert_eq!((opts.text_darkening, opts.hinting, opts.lcd), (ScreenText::PLATFORM.darkening, ScreenText::PLATFORM.hinting, None));
}
assert!(screen.baseline_snap && !thumb.baseline_snap);
// A page takes the same until the app has asked the system (tests never do).
let a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let page = page_render_options(&a, false);
assert_eq!((page.text_darkening, page.hinting, page.baseline_snap), (screen.text_darkening, screen.hinting, true));
}
#[test]
fn subpixel_text_follows_the_choice_the_system_and_the_screen() {
use super::pages::lcd_for;
use crate::screen_text::SubpixelOrder::{Bgr, Rgb};
use wordcraft_engine::cmd::view::TextSmoothing::{Grayscale, Subpixel, System};
use wordcraft_render::LcdOrder;
// Use system setting: where the system asks for it, in its order, below 2x only.
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), 1.0), Some(LcdOrder::Rgb));
assert_eq!(lcd_for(System, Some(Bgr), Some(Bgr), 1.5), Some(LcdOrder::Bgr));
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), 2.0), None, "a high-density screen");
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), f32::NAN), None);
assert_eq!(lcd_for(System, None, None, 1.0), None, "the system asks for greyscale, or says nothing");
assert_eq!(lcd_for(System, None, Some(Bgr), 1.0), None, "a known stripe order is not a request");
// The user's own choice wins on any screen; RGB when the system names no order.
assert_eq!(lcd_for(Subpixel, None, None, 2.0), Some(LcdOrder::Rgb));
assert_eq!(lcd_for(Subpixel, Some(Bgr), Some(Bgr), 3.0), Some(LcdOrder::Bgr));
// A BGR panel whose system has smoothing off (ClearType off on Windows, greyscale on a
// Linux desktop) still gets BGR edges, not RGB ones.
assert_eq!(lcd_for(Subpixel, None, Some(Bgr), 1.0), Some(LcdOrder::Bgr));
let cleartype_off = crate::screen_text::ScreenText::from_windows(Some("0"), Some(2), Some(0));
assert_eq!(lcd_for(Subpixel, cleartype_off.subpixel, cleartype_off.stripes, 1.0), Some(LcdOrder::Bgr));
assert_eq!(lcd_for(System, cleartype_off.subpixel, cleartype_off.stripes, 1.0), None);
for (asked, stripes) in [(None, None), (Some(Rgb), Some(Rgb)), (None, Some(Bgr))] {
assert_eq!(lcd_for(Grayscale, asked, stripes, 1.0), None);
}
}
#[test]
fn a_page_picture_is_rasterised_at_the_screens_own_scale_where_the_view_accounts_for_it() {
use super::pages::raster_scale;
// An A4 page (841.89 pt) at 100 % on a 2x screen: 2245.04 device pixels, asked for as 2256 (the next multiple
// of 16). At 2256 every glyph would be shrunk by half a percent on its way to the screen.
let longest = 841.89_f32;
let native = 96.0 / 72.0 * 2.0;
assert_eq!(raster_scale(2256, 16, longest, Some(native)), (native, true));
assert_eq!(raster_scale(2256, 16, longest, None), (2256.0 / longest, false), "a view with no scale of its own");
// US Letter (792 pt) at the same zoom is 2112 pixels, a multiple of 16: the same either way.
let (scale, own) = raster_scale(2112, 16, 792.0, Some(native));
assert!(own && (scale - 2112.0 / 792.0).abs() < 1e-6);
// A side the view's scale doesn't account for: another zoom's request, a side lowered to the largest texture,
// a part of the page shown reduced. Rasterised as asked for, and not the screen's own.
for side in [2240, 2272, 1024, 16] {
assert_eq!(raster_scale(side, 16, longest, Some(native)), (side as f32 / longest, false), "{side}");
}
// Numbers that aren't: as asked for.
for (longest, native, step) in
[(longest, f32::NAN, 16), (longest, f32::INFINITY, 16), (longest, -1.0, 16), (longest, 0.0, 16), (longest, native, 0)]
{
assert!(!raster_scale(2256, step, longest, Some(native)).1, "{longest} {native} {step}");
}
assert!(!raster_scale(2256, 16, f32::NAN, Some(native)).1 && !raster_scale(2256, 16, 0.0, Some(native)).1);
}
/// A page a fraction of a pixel longer than the largest texture is made no larger than it: a picture one pixel over
/// is halved on upload, and the page stays blurry at rest.
#[test]
fn a_page_picture_never_outgrows_the_largest_texture() {
use super::source::WordPages;
use craft::ui::primitives::textures::{MAX_TEXTURE, ThumbRequest};
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let layout = a.session.layout();
let (w, h) = (layout.pages[0].w, layout.pages[0].h);
let longest = w.max(h);
for over in [-0.6, -0.1, 0.0, 0.1, 0.3, 0.5] {
for y in [0.0, 0.3, 0.49, 0.6] {
let scale = (MAX_TEXTURE as f32 + over) / longest;
a.canvas.settled_pages = vec![(0, Rect::from_min_size(egui::pos2(10.0, y), egui::vec2(w * scale, h * scale)))];
let pages = WordPages::new(&mut a, &layout, false, None, Some(scale));
let plan = pages.plan(0, &ThumbRequest::for_cell(longest * scale, 1.0)).unwrap();
let side = plan.pixels.map_or((longest * plan.scale).ceil() as u32, |(w, h)| w.max(h));
assert!(side <= MAX_TEXTURE, "{over} at {y}: {side}");
assert!(side + 2 >= MAX_TEXTURE, "not reduced either: {over} at {y}: {side}");
if over < -0.5 {
assert!(plan.pixels.is_some(), "a page below the limit keeps its own pixels: {over} at {y}");
}
}
}
}
#[test]
fn a_page_picture_is_made_as_many_pixels_as_its_place_on_screen() {
use super::pages::picture_pixels;
use egui::{pos2, vec2};
// An A4 page at 110 % on a 2x screen, centred in a window: 1746.155 × 2469.544 pixels starting at 642.923.
// Its place rounds to 643..2389 across and 356..2826 down.
let page = Rect::from_min_size(pos2(321.4615, 178.0), vec2(873.0775, 1234.772));
let expected = (1746.155, 2469.544);
assert_eq!(picture_pixels(page, None, 2.0, expected), Some((1746, 2470)));
// The same page half a pixel further right ends on the next pixel and starts on the same one: 1747 across.
assert_eq!(picture_pixels(page.translate(vec2(0.25, 0.0)), None, 2.0, expected), Some((1747, 2470)));
// The upper half of it, as the page view asks for a part: the part's own place, rounded the same way.
let half = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 0.5));
assert_eq!(picture_pixels(page, Some(half), 2.0, (1746.155, 1234.772)), Some((1746, 1235)));
// A place left from another zoom, or a part shown reduced, is not this picture's: no size.
assert_eq!(picture_pixels(page, None, 2.0, (1587.4, 2245.0)), None);
assert_eq!(picture_pixels(page, Some(half), 2.0, (873.0, 617.0)), None);
// Numbers that aren't.
for (page, ppp, expected) in [
(Rect::from_min_size(pos2(f32::NAN, 0.0), vec2(800.0, 1100.0)), 2.0, expected),
(Rect::from_min_size(pos2(0.0, 0.0), vec2(f32::INFINITY, 1100.0)), 2.0, expected),
(page, f32::NAN, expected),
(page, 0.0, expected),
(page, 2.0, (f32::NAN, 2469.5)),
(Rect::NOTHING, 2.0, expected),
] {
assert_eq!(picture_pixels(page, None, ppp, expected), None, "{page:?} {ppp} {expected:?}");
}
}
#[test]
fn page_pictures_fill_the_place_the_view_last_rested_at() {
use super::source::WordPages;
use craft::ui::primitives::textures::{ThumbRequest, ThumbSource};
use egui::{pos2, vec2};
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let layout = a.session.layout();
let (pw, ph) = (layout.pages[0].w, layout.pages[0].h);
let view_scale = 96.0 / 72.0 * 1.1;
let request = ThumbRequest::for_cell(pw.max(ph) * view_scale, 2.0);
// Before the view has rested anywhere: one scale, a whole pixel up each way.
let fresh = WordPages::new(&mut a, &layout, false, None, Some(view_scale));
let plan = fresh.plan(0, &request).unwrap();
assert_eq!((plan.pixels, plan.scale), (None, view_scale * 2.0));
let fresh_revision = fresh.revision(&0, &request);
a.canvas.page_keys = fresh.into_keys();
// At rest, a third of a pixel into a pixel: the picture is its place's size, and another picture than before.
let place = Rect::from_min_size(pos2(321.4615, 178.0), vec2(pw * view_scale, ph * view_scale));
a.canvas.settled_pages = vec![(0, place)];
let rested = WordPages::new(&mut a, &layout, false, None, Some(view_scale));
let plan = rested.plan(0, &request).unwrap();
let (w, h) = plan.pixels.expect("a place to fill");
assert_eq!(w as f32, (place.max.x * 2.0).round() - (place.min.x * 2.0).round());
assert_eq!(h as f32, (place.max.y * 2.0).round() - (place.min.y * 2.0).round());
assert_ne!(rested.revision(&0, &request), fresh_revision);
assert!(rested.plan(1, &request).is_none_or(|plan| plan.pixels.is_none()), "a page with no place");
a.canvas.page_keys = rested.into_keys();
// A place from another zoom is not this zoom's; Read Mode's columns use none.
let zoomed = WordPages::new(&mut a, &layout, false, None, Some(view_scale * 1.3));
assert_eq!(zoomed.plan(0, &ThumbRequest::for_cell(pw.max(ph) * view_scale * 1.3, 2.0)).unwrap().pixels, None);
a.canvas.page_keys = zoomed.into_keys();
let reading = WordPages::new(&mut a, &layout, false, None, None);
assert_eq!(reading.plan(0, &request).unwrap().pixels, None);
a.canvas.page_keys = reading.into_keys();
}
#[test]
fn page_pictures_take_subpixel_text_only_at_the_screens_own_scale() {
use super::source::WordPages;
use craft::ui::primitives::textures::{ThumbRequest, ThumbSource};
use wordcraft_render::LcdOrder;
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let layout = a.session.layout();
let longest = layout.pages[0].w.max(layout.pages[0].h);
let view_scale = 96.0 / 72.0 * 1.1;
let request = |ppp: f32| ThumbRequest::for_cell(longest * view_scale, ppp);
let pages = |a: &mut WordApp, scale: Option<f32>| WordPages::new(a, &layout, false, None, scale);
// Greyscale until chosen (tests never ask the system), at the screen's own scale.
let grey = pages(&mut a, Some(view_scale));
let plan = grey.plan(0, &request(2.0)).unwrap();
assert_eq!((plan.scale, plan.options.lcd), (view_scale * 2.0, None));
assert!(plan.options.baseline_snap);
let grey_revision = grey.revision(&0, &request(2.0));
a.canvas.page_keys = grey.into_keys();
// The user's choice, a command: subpixel text on the picture that is the screen's own...
a.run("view.textSmoothing", json!({"value": "subpixel"})).unwrap();
let sub = pages(&mut a, Some(view_scale));
assert_eq!(sub.plan(0, &request(2.0)).unwrap().options.lcd, Some(LcdOrder::Rgb));
assert_eq!(sub.plan(0, &request(1.0)).unwrap().options.lcd, Some(LcdOrder::Rgb));
assert_ne!(sub.revision(&0, &request(2.0)), grey_revision, "a page drawn the other way is another picture");
let sub_revision = sub.revision(&0, &request(2.0));
// ...and not on one that will be scaled: a request the view's zoom doesn't account for, a part shown reduced.
let other = ThumbRequest::for_cell(longest * view_scale * 1.3, 2.0);
let plan = sub.plan(0, &other).unwrap();
assert_eq!((plan.scale, plan.options.lcd), (other.side as f32 / longest, None));
a.canvas.page_keys = sub.into_keys();
// Read Mode's columns size their pages themselves: as asked for, greyscale.
let reading = pages(&mut a, None);
let plan = reading.plan(0, &request(2.0)).unwrap();
assert_eq!((plan.scale, plan.options.lcd), (request(2.0).side as f32 / longest, None));
a.canvas.page_keys = reading.into_keys();
// Another zoom is another picture, even where the side asked for is the same.
let nudged = pages(&mut a, Some(view_scale * 1.0005));
assert_eq!(ThumbRequest::for_cell(longest * view_scale * 1.0005, 2.0).side, request(2.0).side);
assert_ne!(nudged.revision(&0, &request(2.0)), sub_revision);
assert!(nudged.plan(99, &request(2.0)).is_none());
}
#[test]
fn screen_paper_color_changes_raster_and_cache_without_changing_export_paper() {
use wordcraft_doc::props::Rgb;
@@ -2955,18 +2770,18 @@ fn the_caret_blinks_only_while_the_window_is_active() {
fn word_pages_reuses_doc_snapshot_across_unchanged_frames_and_invalidates_on_edit() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("hello")), Default::default());
let layout = app.session.layout();
let first = super::source::WordPages::new(&mut app, &layout, false, None, None);
let first = super::source::WordPages::new(&mut app, &layout, false, None);
let doc1 = first.doc();
app.canvas.page_keys = first.into_keys();
let second = super::source::WordPages::new(&mut app, &layout, false, None, None);
let second = super::source::WordPages::new(&mut app, &layout, false, None);
let doc2 = second.doc();
app.canvas.page_keys = second.into_keys();
assert!(std::sync::Arc::ptr_eq(&doc1, &doc2), "unchanged frame reuses cached Arc<Document> snapshot");
app.run("text.insert", json!({"text": " world"})).unwrap();
let layout2 = app.session.layout();
let third = super::source::WordPages::new(&mut app, &layout2, false, None, None);
let third = super::source::WordPages::new(&mut app, &layout2, false, None);
let doc3 = third.doc();
app.canvas.page_keys = third.into_keys();
assert!(!std::sync::Arc::ptr_eq(&doc1, &doc3), "editing document invalidates cached snapshot");
@@ -3084,97 +2899,3 @@ fn shift_clicking_a_picture_does_not_scroll_the_view() {
assert!(picked.contains(&first) && picked.contains(&second), "both pictures are selected: {picked:?} {:?} at {at:?}", h.state().session.sel);
assert_eq!(h.state().canvas.view.offset, before, "the view stayed where it was");
}
/// The pictures drawn in the last pass that are at least 300 texels wide (a page's, not an icon's or the font
/// atlas's glyphs): how many device pixels each is drawn across and down, and how many texels it shows.
fn drawn_pictures(
shapes: &[egui::epaint::ClippedShape],
sizes: &std::collections::HashMap<egui::TextureId, [usize; 2]>,
ppp: f32,
) -> Vec<([f32; 2], [f32; 2])> {
fn walk(shape: &egui::Shape, found: &mut Vec<(egui::TextureId, Rect, Rect)>) {
match shape {
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, found)),
egui::Shape::Mesh(mesh) if mesh.texture_id != egui::TextureId::default() => {
let (mut at, mut uv) = (Rect::NOTHING, Rect::NOTHING);
for v in &mesh.vertices {
at.extend_with(v.pos);
uv.extend_with(v.uv);
}
found.push((mesh.texture_id, at, uv));
}
egui::Shape::Rect(rect) => {
if let Some(brush) = &rect.brush
&& brush.fill_texture_id != egui::TextureId::default()
{
found.push((brush.fill_texture_id, rect.rect, brush.uv));
}
}
_ => {}
}
}
let mut found = Vec::new();
shapes.iter().for_each(|clipped| walk(&clipped.shape, &mut found));
found
.into_iter()
.filter_map(|(id, at, uv)| {
let size = sizes.get(&id).filter(|size| size[0] >= 300)?;
let texels = [uv.width() * size[0] as f32, uv.height() * size[1] as f32];
(texels[0] >= 300.0).then_some(([at.width() * ppp, at.height() * ppp], texels))
})
.collect()
}
/// The page view scales a picture into its place, so a page's picture has to be exactly as many pixels each way
/// as that place: a pixel more (what one scale and rounding up give) squeezes it by a twentieth of a percent and
/// the text slides off the pixel grid and back down the page, which reads as blur. Run through the real page view
/// and its picture store, at several zooms and screen densities, on the passes a renderer would draw.
#[test]
fn a_page_at_rest_is_drawn_one_texel_per_device_pixel() {
for ppp in [1.0_f32, 2.0] {
let ctx = crate::test_harness::context();
crate::test_harness::cjk_stand_in(&ctx);
ctx.set_pixels_per_point(ppp);
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
app.run("document.setText", json!({"text": "The quick brown fox jumps over the lazy dog."})).unwrap();
app.run("layout.size", json!({"name": "A4"})).unwrap();
let mut sizes = std::collections::HashMap::new();
for (step, zoom) in [100, 110, 137].into_iter().enumerate() {
app.run("view.zoom", json!({"value": zoom})).unwrap();
// Until the view has come to rest and the worker has made the picture for where it rests.
let mut seen = Vec::new();
let exact = |pictures: &[([f32; 2], [f32; 2])]| {
!pictures.is_empty()
&& pictures.iter().all(|(drawn, texels)| (drawn[0] - texels[0]).abs() < 0.01 && (drawn[1] - texels[1]).abs() < 0.01)
};
for frame in 0..600 {
let mut input = egui::RawInput {
screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1500.0, 950.0))),
time: Some(step as f64 * 100.0 + frame as f64 * 0.05),
max_texture_side: Some(8192),
..Default::default()
};
if let Some(viewport) = input.viewports.get_mut(&egui::ViewportId::ROOT) {
viewport.native_pixels_per_point = Some(ppp);
}
craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out));
let mut out = ctx.run_ui(input, |ui| {
crate::test_harness::logic(ui.ctx(), &mut app);
app.ui(ui);
});
for (id, deltas) in &out.textures_delta.set {
for delta in deltas.iter().filter(|delta| delta.pos.is_none()) {
sizes.insert(*id, delta.image.size());
}
}
seen = drawn_pictures(&out.shapes, &sizes, ppp);
out.textures_delta.clear();
if frame > 3 && exact(&seen) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(exact(&seen), "{zoom} % at {ppp}x: (pixels drawn, texels shown) {seen:?}");
}
}
}
+44 -13
View File
@@ -46,6 +46,20 @@ fn click_at(h: &mut H, at: Pos2) {
steps(h, 3);
}
/// A primary double click at `at`: two clicks a few frames apart, inside egui's double click delay.
fn double_click_at(h: &mut H, at: Pos2) {
// Let the click before it age out, or the pair would count as a triple click.
steps(h, 40);
h.event(egui::Event::PointerMoved(at));
for _ in 0..2 {
h.event(button(at, egui::PointerButton::Primary, true));
h.app_frame();
h.event(button(at, egui::PointerButton::Primary, false));
h.app_frame();
}
steps(h, 3);
}
/// A primary drag from `from` to `to` in six moves.
fn drag_between(h: &mut H, from: Pos2, to: Pos2) {
h.event(egui::Event::PointerMoved(from));
@@ -195,7 +209,7 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
let step = 4.5_f32;
let near = |stops: &[(f32, TabAlign)], want: f32| stops.len() == 1 && stops[0].1 == TabAlign::Center && (stops[0].0 - want).abs() <= step;
// Lets the double-click time pass before the next press.
let settle = |h: &mut H| steps(h, 30);
let settle = |h: &mut H| steps(h, 40);
let stops = |h: &H| {
let s = &h.state().session;
let para = s.doc.para_at(&s.sel.focus).expect("a paragraph");
@@ -253,19 +267,27 @@ fn comment_harness() -> (H, u32) {
a.run("select.text", json!({"text": "text"})).unwrap();
let id = a.run("review.newComment", json!({"text": "Original"})).unwrap()["id"].as_u64().unwrap() as u32;
a.run("view.commentsPane", json!({"value": false})).unwrap();
(window(a), id)
(window_dt(a, Some(1.0 / 60.0)), id)
}
/// Click comment `id`'s balloon (from no selected balloon): the card is selected and its own
/// edit has the keyboard in its field.
/// Click comment `id`'s balloon (from no selected balloon): the card is selected with no edit open (as in Word), then
/// a double click opens its message for editing, and takes the keyboard in its field.
fn click_balloon(h: &mut H, id: u32) {
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
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));
assert_eq!(h.state().canvas.selected_balloon(), Some(id), "the click selected the balloon");
// The selected card opens its own edit, a framework text field, which takes the keyboard by a click in it
// (none opens where comments can't change).
select_balloon_card(h, id);
open_edit(h, id);
}
/// Double-clicks comment `id`'s card to open message 0 for editing, unless a draft is already open (a refused one
/// is kept), and clicks into its field. Nothing opens where comments can't change.
fn open_edit(h: &mut H, id: u32) {
if crate::app::command_board::command_enabled(h.state(), "review.editComment") {
if h.state().canvas.comments.editing.is_none() {
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
double_click_at(h, card.left_top() + vec2(30.0, 8.0));
assert!(h.state().canvas.comments.editing.is_some(), "a double click on the card opens its edit");
}
steps(h, 2);
}
use egui::accesskit::Role;
let field = h
.query_by_role_and_label(Role::MultilineTextInput, "Edit")
@@ -277,6 +299,15 @@ fn click_balloon(h: &mut H, id: u32) {
}
}
/// Clicks comment `id`'s card (from no selected balloon): it is selected with no edit open, so Reply shows.
fn select_balloon_card(h: &mut H, id: u32) {
h.state_mut().canvas.comments.selected = craft::behavior::Selection::default();
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));
assert_eq!(h.state().canvas.selected_balloon(), Some(id), "the click selected the balloon");
}
/// Types `text` into the field that has the keyboard.
fn type_in(h: &mut H, text: &str) {
h.event(egui::Event::Text(text.into()));
@@ -327,7 +358,7 @@ fn an_empty_comment_balloon_deletes() {
}
let id = a.run("review.newComment", json!({})).unwrap()["id"].as_u64().unwrap() as u32;
a.run("view.commentsPane", json!({"value": false})).unwrap();
let mut h = window(a);
let mut h = window_dt(a, Some(1.0 / 60.0));
click_balloon(&mut h, id);
let resolve = h.get_by_label("Resolve").rect().center();
click_at(&mut h, resolve);
@@ -382,7 +413,7 @@ fn a_refused_comment_edit_keeps_the_draft() {
#[test]
fn replying_to_a_comment_from_its_balloon_posts_the_reply() {
let (mut h, id) = comment_harness();
click_balloon(&mut h, id);
select_balloon_card(&mut h, id);
h.get_by_label("Reply").click();
steps(&mut h, 3);
type_in(&mut h, "A reply");
+2 -5
View File
@@ -51,11 +51,8 @@ pub(crate) fn help_entries(app: &WordApp) -> Vec<HelpEntry> {
.iter()
.filter(|c| !crate::dialogs::NOT_IN_SEARCH.contains(&c.id))
.map(|c| {
let command = if c.id == "view.paperColor" || c.id == "view.textSmoothing" {
CommandRef::with_params("file.options", json!({"pane": "general"}))
} else {
CommandRef::new(c.id)
};
let command =
if c.id == "view.paperColor" { CommandRef::with_params("file.options", json!({"pane": "general"})) } else { CommandRef::new(c.id) };
let entry = HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string());
match crate::app::command_board::location_path(c.location) {
Some(path) => entry.with_path(path.into_iter().map(|part| tl!(part).to_string())),
+1 -1
View File
@@ -4,7 +4,7 @@
//! - `engine.execute {command, params, doc?}`: run any command (engine or `ui.*`)
//! - `engine.commands {search?}`: engine and app print commands with enablement and parameters
//! - `document.inspect`: document structure; `ui.inspect`: UI state, canvas geometry, perf
//! - `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.capsLock`:
//! - `ui.click`, `ui.move`, `ui.drag`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.capsLock`:
//! real input in screen points (or document points with `coordinates`), delivered by the
//! control library
//! - `ui.clickText {page, x, y}`: click at a page position (points from the page's top-left)
+36 -3
View File
@@ -5,7 +5,7 @@ use craft::automation::control::{ControlRequest, Reply};
use craft::automation::dialogs;
use craft::automation::synthetic::input_method;
use craft::ui::runtime::commands::{ClipItem, ClipboardHandle};
use craft::ui::runtime::windows::{WindowAction, WindowHost};
use craft::ui::runtime::windows::{WindowAction, WindowHost, windowless_root};
use serde_json::{Value, json};
use super::screenshots::render_png;
@@ -81,6 +81,13 @@ pub(crate) fn close_refused(app: &WordApp, id: &str, params: &Value) -> Option<&
// The document the command closes: `file.close` the shown one, `file.closeDocument` the one
// its `id` names (the active one by default) (#3274).
let target = match id {
// `save: true` is saved, then closed, by `file.close` itself (spec rule 8); a comment
// still being typed is not saved by that, so it still refuses.
"file.close" if params.get("save").and_then(Value::as_bool) == Some(true) => {
let force = params.get("force").and_then(Value::as_bool) == Some(true);
let target = app.session.document_id();
return (!force && app.document_has_comment_drafts(target)).then_some(COMMENT_UNSAVED);
}
"file.close" => app.session.document_id(),
"file.closeDocument" => match params.get("id") {
None | Some(Value::Null) => app.session.document_id(),
@@ -89,7 +96,8 @@ pub(crate) fn close_refused(app: &WordApp, id: &str, params: &Value) -> Option<&
},
_ => return None,
};
close_refused_for(app, target, params)
let refusal = close_refused_for(app, target, params);
if id == "file.close" && refusal == Some(UNSAVED) { Some(UNSAVED_CLOSE) } else { refusal }
}
/// The refusal for closing the document `target` with unsaved work in it: the same work the
@@ -109,6 +117,9 @@ fn close_refused_for(app: &WordApp, target: u64, params: &Value) -> Option<&'sta
}
const UNSAVED: &str = "the document has unsaved changes: save it first, or pass {\"force\": true} to discard them and close";
/// `file.close` also takes `save` (spec rule 8).
const UNSAVED_CLOSE: &str =
"unsaved changes: pass save or force ({\"save\": true} writes the document, then closes; {\"force\": true} closes without saving)";
const COMMENT_UNSAVED: &str = "a comment is still being edited: finish it first, or pass {\"force\": true} to discard it";
/// Quitting closes every open document, so unsaved work needs the same explicit `force` as
@@ -180,6 +191,10 @@ fn handle_in(app: &mut WordApp, doc: u64, method: &str, p: &Value) -> Reply {
// Close, with the same guard as the window's: unsaved changes need `force`.
if id == "file.close" {
if let Some(e) = close_refused_for(app, doc, &params) {
// lean: `save` writes the shown document only; a background one needs file.save after making it active.
if params.get("save").and_then(Value::as_bool) == Some(true) {
return err(format!("{e} (`save` applies to the shown document only: make this one active first, or save it, then close)"));
}
return err(e);
}
return match app.session.close_document(doc) {
@@ -406,7 +421,25 @@ fn handle_request(app: &mut WordApp, ctx: &egui::Context, req: &ControlRequest)
ok(json!({}))
}
// Close the active window through the same guard as its OS close button.
"ui.closeWindow" => ok(json!({"requested": WindowHost::of(ctx).act(app.active_viewport(), WindowAction::Close)})),
// `window` names another window by its key; none means the active one (spec rule 8).
"ui.closeWindow" => {
let viewport = match p.get("window").filter(|w| !w.is_null()) {
None => app.active_viewport(),
Some(w) => match w.as_u64().and_then(|key| app.window_viewport(key)) {
Some(v) => v,
None => return err("`window` is not an open window: use a key from ui.inspect windows (`current`, `others[].id`)"),
},
};
// Spec rule 4: a close while a Save prompt is up only raises that prompt, so nothing was requested.
if app.raise_closing().is_some() {
return ok(json!({"requested": false, "reason": "a Save prompt is already open: answer it first"}));
}
// A windowless root is no window: closing it would end the app, not close a window.
if viewport == egui::ViewportId::ROOT && windowless_root(ctx) {
return err("no document window is open");
}
ok(json!({"requested": WindowHost::of(ctx).act(viewport, WindowAction::Close)}))
}
"ui.clipboard" => clipboard(ctx, p),
"ui.replayAt" => {
let Some(at) = p.get("at").and_then(Value::as_f64) else { return err("missing `at`") };
+4 -1
View File
@@ -368,7 +368,7 @@ fn a_script_opens_the_dialog_a_launcher_command_asks_for() {
/// Every method the Methods table of `docs/control-protocol.md` lists is one the control channel answers: none falls
/// through to the commands as an unknown id. The input methods moved to the framework's names in #7101, and the table
/// kept `ui.press`, `ui.drag` and `ui.text`.
/// kept `ui.press` and `ui.text` (while `ui.drag` moved to `{from, to}`).
#[test]
fn every_method_the_protocol_doc_lists_is_answered() {
let doc = include_str!("../../../../docs/control-protocol.md");
@@ -383,10 +383,13 @@ fn every_method_the_protocol_doc_lists_is_answered() {
.map(|name| name.trim_matches('`'))
.collect();
assert!(methods.contains(&"engine.execute"), "the Methods table: {methods:?}");
assert!(methods.contains(&"ui.drag"), "the Methods table: {methods:?}");
let ctx = installed();
for method in methods {
let r = call(&mut app(), &ctx, method, json!({}));
let unknown = wordcraft_engine::CmdError::Unknown(method.to_string()).to_string();
assert_ne!(r["error"].as_str(), Some(unknown.as_str()), "the doc lists `{method}`, which the control channel doesn't answer");
}
let (req, _rx) = ControlRequest::new("ui.drag", json!({"from": {"x": 10.0, "y": 10.0}, "to": {"x": 20.0, "y": 20.0}}));
assert!(matches!(control::handle(&mut app(), &ctx, &req), Reply::AfterInput));
}
+4 -1
View File
@@ -18,8 +18,9 @@ use crate::{WordApp, panes};
/// What the window keeps for an open document while another one is shown.
#[derive(Default)]
pub(crate) struct Parked {
/// [`WordApp`]'s `autosave_path`: the file AutoSave writes this document to.
/// [`WordApp`]'s `autosave_path`: the file this document was explicitly saved to.
autosave_path: Option<std::path::PathBuf>,
autosave_choice: Option<bool>,
/// [`WordApp`]'s `read_from`: the file on disk this document was read from or saved to.
read_from: Option<std::path::PathBuf>,
/// The comment panel's selection and the comment and reply text typed in this document and not
@@ -106,6 +107,7 @@ impl WordApp {
}
let leaving = Parked {
autosave_path: self.autosave_path.take(),
autosave_choice: self.autosave_choice.take(),
read_from: self.read_from.take(),
comments: std::mem::take(&mut self.canvas.comments),
};
@@ -116,6 +118,7 @@ impl WordApp {
let seen = back.is_some();
let back = back.unwrap_or_default();
self.autosave_path = back.autosave_path;
self.autosave_choice = back.autosave_choice;
self.read_from = back.read_from;
self.canvas.comments = back.comments;
let session = &self.session;
+2
View File
@@ -379,7 +379,9 @@ impl WordApp {
}
AfterSave::AutoSave => {
if saved {
self.autosave_choice = None;
self.autosave = true;
self.session.autosave = true;
} else if let Some(Err(error)) = &result {
self.fail_save_as(error);
}
+13
View File
@@ -167,6 +167,19 @@ fn imported_word_close_waits_for_save_as_and_keeps_failed_or_cancelled_drafts()
let _ = std::fs::remove_dir_all(dir);
}
/// Spec rules 5 and 6: cancelling the Save As a quit's Save opened cancels the quit.
#[test]
fn cancelling_save_as_cancels_the_quit() {
let (mut a, files) = async_app();
a.run("text.insert", json!({"text": "Draft"})).unwrap();
assert!(!a.quit());
assert_eq!(a.run("ui.saveChanges", json!({"answer": "save"})).unwrap()["pending"], "saveAs");
answer(&files, None);
assert_eq!(a.poll_file_dialog().unwrap().unwrap()["done"], false);
assert!(a.closing.is_none() && !a.quit_requested && a.session.dirty, "nothing closes, nothing is lost");
assert!(!a.quit(), "the next quit asks again");
}
/// A late Save As answer belongs to the imported document that opened the picker: once that
/// document is closed, it writes nothing.
#[test]
+2 -3
View File
@@ -599,9 +599,8 @@ fn closing_the_backstage_ends_its_keytips() {
assert!(h.state().keytips_active, "keytips active in Backstage");
// What the back chevron does.
h.state_mut().ui.backstage = false;
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
h.state_mut().run("ui.backstage", serde_json::json!({"value": false})).unwrap();
h.state_mut().canvas.focus_page_after_pass();
crate::test_harness::frames(&mut h, 2);
assert!(!h.state().keytips_active, "the badges end with the Backstage");
h.input_mut().events.extend([key(egui::Key::C), egui::Event::Text("c".into())]);
+4 -4
View File
@@ -68,7 +68,6 @@ pub mod read_aloud;
mod restrict_pane;
pub mod ribbon;
mod save_types;
pub mod screen_text;
pub mod scroll;
pub use scroll::ScrollSpeed;
pub mod desktop_theme; // owed by ribbon batch 2 (S-L348)
@@ -506,10 +505,11 @@ pub struct WordApp {
/// Read Aloud: the start of the sentence the caret was last moved to, and the last error shown.
pub(crate) read_aloud_at: Option<wordcraft_engine::doc::Pos>,
pub(crate) read_aloud_error: Option<String>,
/// The file the document was last explicitly saved to in this session; AutoSave writes only
/// there. A file that was merely opened isn't rewritten until the user saves it: saving drops
/// whatever WordCraft can't represent (content controls, charts, macros…).
/// The file the document was last explicitly saved to in this session.
autosave_path: Option<std::path::PathBuf>,
/// The document's explicit AutoSave switch choice. None follows the shared preference
/// once the document has been saved here.
autosave_choice: Option<bool>,
/// The file on disk the document was read from or saved to. A document opened from bytes
/// (`file.open` with `data`) only names a file, so the AutoSave switch can't cover it.
read_from: Option<std::path::PathBuf>,
+4 -11
View File
@@ -125,8 +125,6 @@ struct Strings {
region_id: String,
paper: Vec<(String, String)>,
paper_id: String,
smoothing: Vec<(String, String)>,
smoothing_id: String,
numerals: Vec<(String, String)>,
numeral_id: String,
proofing_language: String,
@@ -173,8 +171,6 @@ impl Strings {
let paper = PaperColor::ALL.iter().map(|c| (id_of(c), tl!(c.label()).to_string())).collect();
let paper_id = id_of(&app.session.prefs.paper_color);
let smoothing = wordcraft_engine::cmd::view::TextSmoothing::ALL.iter().map(|c| (id_of(c), tl!(c.label()).to_string())).collect();
let smoothing_id = id_of(&app.session.prefs.text_smoothing);
let numerals = [NumeralMode::Arabic, NumeralMode::Hindi, NumeralMode::Context, NumeralMode::System]
.iter()
.map(|m| (id_of(m), tl!(m.label()).to_string()))
@@ -201,8 +197,6 @@ impl Strings {
region_id,
paper,
paper_id,
smoothing,
smoothing_id,
numerals,
numeral_id,
proofing_language,
@@ -252,7 +246,6 @@ impl<'a> OptionsModel<'a> {
("general.theme", Choice(ui.theme.code().to_string())),
("general.interfaceSize", Choice(size)),
("general.paperColor", Choice(id_of(&prefs.paper_color))),
("general.textSmoothing", Choice(id_of(&prefs.text_smoothing))),
("general.miniToolbar", Bool(ui.mini_toolbar)),
("general.darkPage", Bool(view.dark_mode)),
("general.showCommunity", Bool(ui.show_discord)),
@@ -344,9 +337,6 @@ impl PreferencesModel for OptionsModel<'_> {
RowSpec::new("general.paperColor", tl!("Screen paper color:"), RowKind::choice(&s.paper_id, owned(&s.paper))).help(tl!(
"Screen only. Document backgrounds, printing and exports keep their colours. Dark page and explicit Read Mode colours take precedence."
)),
RowSpec::new("general.textSmoothing", tl!("Screen text smoothing:"), RowKind::choice(&s.smoothing_id, owned(&s.smoothing))).help(tl!(
"Screen only. Subpixel smoothing makes the edges of page text finer sideways, with faint colour in them, and takes longer to draw. Printing and exports are unchanged."
)),
b("general.miniToolbar", tl!("Show the mini toolbar when text is selected"), app.ui.mini_toolbar),
b("general.darkPage", tl!("Dark page (white text on black)"), app.session.view.dark_mode)
.help(tl!("Show documents with their colours inverted, like View › Switch Modes. Saving, printing and PDFs are unchanged.")),
@@ -643,7 +633,6 @@ impl PreferencesModel for OptionsModel<'_> {
Err(_) => self.run("ui.interfaceSize", json!({"value": "auto"})),
},
("general.paperColor", Choice(c)) => self.run("view.paperColor", json!({"value": c})),
("general.textSmoothing", Choice(c)) => self.run("view.textSmoothing", json!({"value": c})),
("general.miniToolbar", Bool(v)) => self.app.ui.mini_toolbar = v,
("general.showCommunity", Bool(v)) => self.app.ui.show_discord = v,
("general.fontDownloadNotice", Bool(v)) => self.app.ui.font_download_notice = v,
@@ -677,6 +666,10 @@ impl PreferencesModel for OptionsModel<'_> {
if self.app.autosave_block() != Some(crate::AutoSaveBlock::Browser) {
self.app.autosave = v;
self.app.session.autosave = v;
// The Options row explicitly enables AutoSave for the active saved document.
if v && self.app.saved_here() {
self.app.autosave_choice = None;
}
}
}
("save.removePersonalInfo", Bool(v)) => self.run("file.privacyOptions", json!({"removePersonalInfo": v})),
+27 -17
View File
@@ -179,6 +179,33 @@ fn options_panes_open_and_change_settings() {
}
}
#[test]
fn autosave_option_enables_saved_files_without_authorizing_open_only_files() {
let dir = std::env::temp_dir().join(format!("wc-ui-autosave-option-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("saved.docx");
let path = path.to_string_lossy();
let mut a = app();
a.run("text.insert", json!({"text": "Saved for the AutoSave test."})).unwrap();
a.run("file.save", json!({"path": path})).unwrap();
a.run("file.autosave", json!({"value": false})).unwrap();
assert!(!a.autosaves());
let enable = |m: &mut OptionsModel<'_>| m.set("save.autosave", PrefValue::Bool(true));
with_model(&mut a, true, enable);
assert!(a.autosaves(), "Options re-enables an explicitly saved file");
let mut opened = app();
opened.run("file.open", json!({"path": path})).unwrap();
with_model(&mut opened, true, enable);
assert!(!opened.autosaves(), "Options must not grant permission to write an opened file");
opened.run("file.autosave", json!({"value": true})).unwrap();
assert!(opened.autosaves(), "the document's switch may explicitly grant permission");
opened.run("file.autosave", json!({"value": false})).unwrap();
with_model(&mut opened, true, enable);
assert!(!opened.autosaves(), "Options must not restore a withdrawn grant for an opened file");
let _ = std::fs::remove_dir_all(&dir);
}
/// One table over the Choice rows and the document's privacy options.
#[test]
fn save_privacy_checkboxes_set_the_privacy_options() {
@@ -301,23 +328,6 @@ fn length_units_follow_the_interface_language() {
assert_eq!(unit_suffix(Unit::Millimeters), " mm", "English keeps the English names");
}
#[test]
fn screen_text_smoothing_options_round_trip_and_work_without_a_document() {
use wordcraft_engine::cmd::view::TextSmoothing;
let mut a = app();
a.start_screen();
a.run("view.textSmoothing", json!({"value":"grayscale"})).unwrap();
let saved = serde_json::to_vec(&a.prefs()).unwrap();
let mut b = app();
b.apply_prefs(serde_json::from_slice::<Prefs>(&saved).unwrap());
assert_eq!(b.session.prefs.text_smoothing, TextSmoothing::Grayscale);
with_model(&mut b, true, |m| m.set("general.textSmoothing", PrefValue::Choice("subpixel".into())));
assert_eq!(b.session.prefs.text_smoothing, TextSmoothing::Subpixel);
// A value the option doesn't have changes nothing.
with_model(&mut b, true, |m| m.set("general.textSmoothing", PrefValue::Choice("lcd".into())));
assert_eq!(b.session.prefs.text_smoothing, TextSmoothing::Subpixel);
}
#[test]
fn screen_paper_color_options_round_trip_and_work_without_a_document() {
use wordcraft_engine::cmd::view::PaperColor;
-38
View File
@@ -1150,44 +1150,6 @@ fn unimplemented_stub_ribbon_buttons_are_disabled() {
.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());
if expected_label == "Dictate" {
fn push_icon_rects(shape: &egui::Shape, clip: egui::Rect, btn_rect: egui::Rect, out: &mut Vec<egui::Rect>) {
match shape {
egui::Shape::Vec(items) => {
for item in items {
push_icon_rects(item, clip, btn_rect, out);
}
}
egui::Shape::Text(_) | egui::Shape::Noop => {}
other => {
let r = other.visual_bounding_rect().intersect(clip);
if r.is_positive()
&& btn_rect.expand(1.0).contains_rect(r)
&& r.width() < btn_rect.width() * 0.9
&& r.height() < btn_rect.height() * 0.9
{
out.push(r);
}
}
}
}
let btn_rect = button.rect();
let mut icon_rects = Vec::new();
for c in &h.output().shapes {
push_icon_rects(&c.shape, c.clip_rect, btn_rect, &mut icon_rects);
}
let icon_rect = icon_rects
.into_iter()
.reduce(|a, b| a.union(b))
.unwrap_or_else(|| panic!("Dictate button ({btn_rect:?}) must paint a bounded icon shape"));
assert!(
icon_rect.width() >= 16.0 && icon_rect.height() >= 16.0,
"Dictate ribbon icon must render at >= 16 pt, got {}x{} ({icon_rect:?})",
icon_rect.width(),
icon_rect.height()
);
assert!((icon_rect.width() - icon_rect.height()).abs() <= 2.0, "Dictate icon should be square: {icon_rect:?}");
}
}
}
-294
View File
@@ -1,294 +0,0 @@
//! How the desktop draws text, so pages look like the text in the platform's other apps.
//!
//! Each system keeps the user's choice somewhere else, and says different things:
//!
//! - macOS: the `AppleFontSmoothing` default, the strength of its font smoothing (0 to 3).
//! - Windows: `FontSmoothing`, `FontSmoothingType` and `FontSmoothingOrientation` under
//! `HKCU\Control Panel\Desktop`: smoothing on or off, ClearType or greyscale, RGB or BGR stripes.
//! - Linux and the BSDs: the desktop's antialiasing, hinting and subpixel order, as GNOME
//! (`org.gnome.desktop.interface`) or KDE Plasma (`kdeglobals`) keeps them.
//!
//! This module turns those values into one [`ScreenText`] and keeps the latest one for the page rasters to read.
//! It never asks the system itself, and for now nothing does: the app reads the system through craft-libs'
//! `platform::appearance`, which reports theme, contrast and reduced motion and no text settings yet. Until a
//! reader there hands an answer to [`set_system`] (and always in tests and headless screenshots)
//! [`ScreenText::PLATFORM`] stands, so pages are drawn each platform's fixed way. The constructors below are what
//! that reader's values go through.
use std::sync::Mutex;
/// The order of a screen's colour stripes, left to right.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SubpixelOrder {
Rgb,
Bgr,
}
/// How page text is drawn on screen.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScreenText {
/// The strength of macOS-style font smoothing (glyphs thickened sideways): 0 is none, 1 the
/// system's default. See `wordcraft_render::RenderOptions::text_darkening`.
pub darkening: f32,
/// Light hinting, as FreeType's `hintslight` draws text.
pub hinting: bool,
/// The system asks for subpixel (LCD) antialiasing, in this stripe order; `None` when it asks
/// for greyscale antialiasing or says nothing.
pub subpixel: Option<SubpixelOrder>,
/// The screen's stripe order, where the system names one, whether or not it asks for
/// subpixel antialiasing: a user who chooses subpixel text themselves gets it in the order
/// of their screen. `None` when the system names no side-by-side order.
pub stripes: Option<SubpixelOrder>,
}
impl ScreenText {
/// What each platform's apps do when the user has changed nothing, and what pages are drawn
/// with until the system has been asked: macOS smooths (thickens) text and never hints it;
/// Linux and the BSDs hint lightly; Windows gets neither. All greyscale: a subpixel order is
/// only ever taken from the system.
pub const PLATFORM: ScreenText = ScreenText {
darkening: if cfg!(target_os = "macos") { 1.0 } else { 0.0 },
hinting: cfg!(all(unix, not(target_os = "macos"))),
subpixel: None,
stripes: None,
};
/// macOS, from the `AppleFontSmoothing` default (`None` when it isn't set). 0 turns the
/// smoothing off; 1, 2 and 3 are light, medium and strong, and unset is medium. The three
/// strengths as half, one and one and a half times our darkening are our own choice: Apple
/// publishes no numbers for them. macOS has no hinting and no subpixel antialiasing to ask
/// for (it dropped the latter in 10.14).
pub fn from_macos(font_smoothing: Option<i64>) -> Self {
let darkening = match font_smoothing {
Some(level) if level <= 0 => 0.0,
Some(1) => 0.5,
Some(2) | None => 1.0,
Some(_) => 1.5,
};
ScreenText { darkening, hinting: false, subpixel: None, stripes: None }
}
/// Windows, from the values under `HKCU\Control Panel\Desktop` (`None` for one that isn't
/// there): `FontSmoothing` is the text "2" when edges are smoothed and "0" when not,
/// `FontSmoothingType` is 2 for ClearType (1 is greyscale), `FontSmoothingOrientation` is 1
/// for RGB stripes and 0 for BGR. ClearType gives subpixel edges, RGB unless the system
/// says BGR; the stripe order itself is kept even with ClearType off. Text with smoothing off is still drawn antialiased, in greyscale: this
/// rasteriser has no aliased text.
pub fn from_windows(smoothing: Option<&str>, kind: Option<u32>, orientation: Option<u32>) -> Self {
let smoothed = smoothing.map(str::trim) != Some("0");
// The orientation is the screen's, and is kept whatever the smoothing is set to.
let stripes = match orientation {
Some(0) => Some(SubpixelOrder::Bgr),
Some(1) => Some(SubpixelOrder::Rgb),
_ => None,
};
let subpixel = (smoothed && kind == Some(2)).then_some(stripes.unwrap_or(SubpixelOrder::Rgb));
ScreenText { darkening: 0.0, hinting: false, subpixel, stripes }
}
/// GNOME (and the desktops that keep its settings), from `org.gnome.desktop.interface`:
/// `font-antialiasing` is `none`, `grayscale` or `rgba`; `font-hinting` is `none`, `slight`,
/// `medium` or `full`; `font-rgba-order` is `rgba`, `rgb`, `bgr`, `vrgb` or `vbgr`. `None`
/// when the desktop has none of the three. Any hinting but `none` is our one light hinting.
/// Stripes that run across the screen (`vrgb`, `vbgr`) get greyscale edges: only side by
/// side stripes are drawn.
pub fn from_gnome(antialiasing: Option<&str>, hinting: Option<&str>, rgba_order: Option<&str>) -> Option<Self> {
if antialiasing.is_none() && hinting.is_none() && rgba_order.is_none() {
return None;
}
let order = match rgba_order.map(str::trim) {
Some("bgr") => Some(SubpixelOrder::Bgr),
Some("vrgb" | "vbgr") => None,
// `rgba` is the schema's first value and its default; it and no answer mean RGB.
_ => Some(SubpixelOrder::Rgb),
};
let subpixel = if antialiasing.map(str::trim) == Some("rgba") { order } else { None };
// The order the desktop names, kept when it asks for greyscale.
let stripes = order.filter(|_| rgba_order.is_some());
Some(ScreenText { darkening: 0.0, hinting: hinting.map(str::trim) != Some("none"), subpixel, stripes })
}
/// KDE Plasma, from the `[General]` group of `kdeglobals`: `XftAntialias` is `true` or
/// `false`; `XftHintStyle` is `hintnone`, `hintslight`, `hintmedium` or `hintfull`;
/// `XftSubPixel` is `none`, `rgb`, `bgr`, `vrgb` or `vbgr`. `None` when it has none of the
/// three (Plasma writes them only once the user has changed the font settings).
pub fn from_kde(antialias: Option<&str>, hint_style: Option<&str>, sub_pixel: Option<&str>) -> Option<Self> {
if antialias.is_none() && hint_style.is_none() && sub_pixel.is_none() {
return None;
}
let antialiased = !matches!(antialias.map(|v| v.trim().to_ascii_lowercase()).as_deref(), Some("false" | "0"));
let order = match sub_pixel.map(str::trim) {
Some("rgb") => Some(SubpixelOrder::Rgb),
Some("bgr") => Some(SubpixelOrder::Bgr),
_ => None,
};
Some(ScreenText {
darkening: 0.0,
hinting: hint_style.map(str::trim) != Some("hintnone"),
subpixel: order.filter(|_| antialiased),
stripes: order,
})
}
/// The same settings with numbers a raster can take: a darkening that isn't a number, or is
/// negative, is none, and the strongest is twice the default.
pub fn sanitized(self) -> Self {
let darkening = if self.darkening.is_finite() { self.darkening.clamp(0.0, 2.0) } else { 0.0 };
ScreenText { darkening, ..self }
}
/// Put these settings into a page raster's options.
pub fn apply(self, opts: &mut wordcraft_render::RenderOptions) {
let text = self.sanitized();
opts.text_darkening = text.darkening;
opts.hinting = text.hinting;
}
/// A value to hash into a page's cache key: a page drawn under other settings is another
/// raster.
pub fn key(self) -> (u32, bool, Option<SubpixelOrder>, Option<SubpixelOrder>) {
let text = self.sanitized();
(text.darkening.to_bits(), text.hinting, text.subpixel, text.stripes)
}
}
/// What the system said last; `None` until the app has asked, and when the system said nothing.
static SYSTEM: Mutex<Option<ScreenText>> = Mutex::new(None);
/// How page text is drawn now: the system's settings once they are known ([`set_system`]), else
/// [`ScreenText::PLATFORM`].
pub fn current() -> ScreenText {
SYSTEM.lock().unwrap_or_else(std::sync::PoisonError::into_inner).unwrap_or(ScreenText::PLATFORM)
}
/// Record the system's answer (`None`: it has none, so the platform's own way stands). Returns
/// whether that changes how text is drawn, so the caller can ask for a repaint.
pub fn set_system(answer: Option<ScreenText>) -> bool {
let answer = answer.map(ScreenText::sanitized);
let before = current();
*SYSTEM.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = answer;
current() != before
}
#[cfg(test)]
mod tests {
use super::{ScreenText, SubpixelOrder};
#[test]
fn the_platform_default_is_what_was_built_in() {
let p = ScreenText::PLATFORM;
assert_eq!(p.darkening > 0.0, cfg!(target_os = "macos"));
assert_eq!(p.hinting, cfg!(all(unix, not(target_os = "macos"))));
assert_eq!((p.subpixel, p.stripes), (None, None), "a stripe order only ever comes from the system");
// Tests and headless screenshots never ask the system, so this is what they draw with.
assert_eq!(super::current(), p);
}
#[test]
fn macos_font_smoothing_sets_the_darkening() {
let strength = |level| ScreenText::from_macos(level).darkening;
assert_eq!(strength(None), 1.0, "unset is the system's medium");
assert_eq!((strength(Some(0)), strength(Some(1)), strength(Some(2)), strength(Some(3))), (0.0, 0.5, 1.0, 1.5));
// Values Apple doesn't define: below the range is off, above it the strongest.
assert_eq!((strength(Some(-4)), strength(Some(i64::MIN)), strength(Some(9)), strength(Some(i64::MAX))), (0.0, 0.0, 1.5, 1.5));
let text = ScreenText::from_macos(None);
assert!(!text.hinting && text.subpixel.is_none());
}
#[test]
fn windows_cleartype_gives_subpixel_edges_in_the_screens_order() {
let order = |smoothing, kind, orientation| ScreenText::from_windows(smoothing, kind, orientation).subpixel;
assert_eq!(order(Some("2"), Some(2), Some(1)), Some(SubpixelOrder::Rgb));
assert_eq!(order(Some("2"), Some(2), Some(0)), Some(SubpixelOrder::Bgr));
assert_eq!(order(Some("2"), Some(2), None), Some(SubpixelOrder::Rgb), "no orientation: RGB, as nearly every panel is");
assert_eq!(order(None, Some(2), Some(1)), Some(SubpixelOrder::Rgb), "no on/off value: on, as Windows starts");
// Greyscale smoothing, smoothing off, and a machine that says nothing.
assert_eq!(order(Some("2"), Some(1), Some(1)), None);
assert_eq!(order(Some("0"), Some(2), Some(1)), None);
assert_eq!(order(Some(" 0 "), Some(2), Some(1)), None);
assert_eq!(order(None, None, None), None);
assert_eq!(order(Some("junk"), Some(u32::MAX), Some(u32::MAX)), None);
let text = ScreenText::from_windows(Some("2"), Some(2), Some(1));
assert!(!text.hinting && text.darkening == 0.0);
// The screen's stripe order survives ClearType being off or greyscale, for a user who
// chooses subpixel text themselves; no orientation value is no known order.
let stripes = |smoothing, kind, orientation| ScreenText::from_windows(smoothing, kind, orientation).stripes;
assert_eq!(stripes(Some("0"), Some(2), Some(0)), Some(SubpixelOrder::Bgr));
assert_eq!(stripes(Some("2"), Some(1), Some(0)), Some(SubpixelOrder::Bgr));
assert_eq!(stripes(Some("0"), None, Some(1)), Some(SubpixelOrder::Rgb));
assert_eq!(stripes(Some("2"), Some(2), None), None);
assert_eq!(stripes(Some("2"), Some(2), Some(7)), None);
}
#[test]
fn gnome_settings_set_hinting_and_subpixel_edges() {
assert_eq!(ScreenText::from_gnome(None, None, None), None, "a desktop without these settings says nothing");
let text = |a, h, o| ScreenText::from_gnome(a, h, o).unwrap();
// GNOME's own defaults: greyscale, slight hinting.
assert_eq!(
text(Some("grayscale"), Some("slight"), Some("rgb")),
ScreenText { darkening: 0.0, hinting: true, subpixel: None, stripes: Some(SubpixelOrder::Rgb) }
);
assert_eq!(text(Some("rgba"), Some("slight"), Some("rgb")).subpixel, Some(SubpixelOrder::Rgb));
assert_eq!(text(Some("rgba"), Some("slight"), Some("rgba")).subpixel, Some(SubpixelOrder::Rgb));
assert_eq!(text(Some("rgba"), Some("slight"), Some("bgr")).subpixel, Some(SubpixelOrder::Bgr));
assert_eq!(text(Some("rgba"), None, None).subpixel, Some(SubpixelOrder::Rgb));
// Stripes across the screen, and no antialiasing: greyscale edges.
assert_eq!(text(Some("rgba"), Some("slight"), Some("vrgb")).subpixel, None);
assert_eq!(text(Some("rgba"), Some("slight"), Some("vbgr")).subpixel, None);
assert_eq!(text(Some("none"), Some("slight"), Some("rgb")).subpixel, None);
// Hinting: off only when the desktop says none.
assert!(!text(Some("grayscale"), Some("none"), None).hinting);
for style in ["slight", "medium", "full", "something new"] {
assert!(text(None, Some(style), None).hinting, "{style}");
}
assert!(text(Some("grayscale"), None, None).hinting);
// The stripe order is kept when the desktop asks for greyscale or no antialiasing.
assert_eq!(text(Some("grayscale"), None, Some("bgr")).stripes, Some(SubpixelOrder::Bgr));
assert_eq!(text(Some("none"), None, Some("rgb")).stripes, Some(SubpixelOrder::Rgb));
assert_eq!(text(Some("rgba"), None, None).stripes, None, "no order named");
assert_eq!(text(Some("grayscale"), None, Some("vbgr")).stripes, None);
}
#[test]
fn kde_settings_set_hinting_and_subpixel_edges() {
assert_eq!(ScreenText::from_kde(None, None, None), None, "Plasma writes nothing until the font settings change");
let text = |a, h, s| ScreenText::from_kde(a, h, s).unwrap();
assert_eq!(
text(Some("true"), Some("hintslight"), Some("rgb")),
ScreenText { darkening: 0.0, hinting: true, subpixel: Some(SubpixelOrder::Rgb), stripes: Some(SubpixelOrder::Rgb) }
);
assert_eq!(text(Some("true"), Some("hintslight"), Some("bgr")).subpixel, Some(SubpixelOrder::Bgr));
assert_eq!(text(None, None, Some("rgb")).subpixel, Some(SubpixelOrder::Rgb));
for none in ["none", "vrgb", "vbgr", "junk"] {
assert_eq!(text(Some("true"), None, Some(none)).subpixel, None, "{none}");
}
assert_eq!(text(Some("false"), None, Some("rgb")).subpixel, None, "antialiasing off");
assert_eq!(text(Some(" False "), None, Some("rgb")).subpixel, None);
assert!(!text(None, Some("hintnone"), None).hinting);
assert!(text(None, Some("hintfull"), None).hinting && text(Some("true"), None, None).hinting);
// The stripe order is kept with antialiasing off.
assert_eq!(text(Some("false"), None, Some("bgr")).stripes, Some(SubpixelOrder::Bgr));
assert_eq!(text(Some("true"), None, Some("none")).stripes, None);
}
#[test]
fn settings_go_into_the_page_options_as_numbers_a_raster_can_take() {
let mut opts = wordcraft_render::RenderOptions::default();
ScreenText { darkening: 1.5, hinting: true, subpixel: None, stripes: None }.apply(&mut opts);
assert_eq!((opts.text_darkening, opts.hinting), (1.5, true));
for (given, taken) in [(f32::NAN, 0.0), (f32::INFINITY, 0.0), (-3.0, 0.0), (40.0, 2.0), (0.5, 0.5)] {
let text = ScreenText { darkening: given, hinting: false, subpixel: None, stripes: None };
text.apply(&mut opts);
assert_eq!((opts.text_darkening, opts.hinting), (taken, false), "{given}");
assert_eq!(text.key(), ScreenText { darkening: taken, ..text }.key());
}
// Each setting changes the cache key.
let base = ScreenText { darkening: 1.0, hinting: false, subpixel: None, stripes: None };
assert_ne!(base.key(), ScreenText { darkening: 0.5, ..base }.key());
assert_ne!(base.key(), ScreenText { hinting: true, ..base }.key());
assert_ne!(base.key(), ScreenText { subpixel: Some(SubpixelOrder::Rgb), ..base }.key());
assert_ne!(base.key(), ScreenText { stripes: Some(SubpixelOrder::Bgr), ..base }.key());
assert_ne!(ScreenText { subpixel: Some(SubpixelOrder::Bgr), ..base }.key(), ScreenText { subpixel: Some(SubpixelOrder::Rgb), ..base }.key());
}
}
+55 -37
View File
@@ -78,25 +78,13 @@ impl ResizeDrag {
}
}
/// Where grid line `line` (the table's left edge is 0) stands on the page while a ruler drag of a column border is
/// in progress, with the keys `mods` held; `None` when no such drag runs. The ruler's markers follow it: the
/// framework ruler draws each marker where the app says its border is.
pub(crate) fn ruler_line_x(&self, mods: Mods, row: Option<usize>, line: usize) -> Option<f32> {
if !matches!(self.target.edge, Edge::Column(_)) {
return None;
}
let plan = self.plan(mods);
let row = row.or_else(|| plan.cells.first().map(|(r, _)| *r));
Some(self.target.planned_x(&plan, row, line))
}
/// Whether the pointer has moved from where it went down.
fn moved(&self) -> bool {
(self.to.0 - self.from.0).abs() >= 0.5 || (self.to.1 - self.from.1).abs() >= 0.5
}
}
pub(crate) fn caret_drag(app: &WordApp, page: usize) -> Option<&ResizeDrag> {
fn caret_drag(app: &WordApp, page: usize) -> Option<&ResizeDrag> {
let caret = app.session.sel.focus.path.cell().map(|(tp, _, _)| tp);
app.canvas
.table_resize
@@ -110,35 +98,65 @@ pub(crate) fn measuring(app: &WordApp, ctx: &egui::Context, page: usize) -> bool
ctx.input(|i| i.modifiers.alt) && caret_drag(app, page).is_some_and(|d| matches!(d.target.edge, Edge::Column(_)))
}
/// The visible borders of the caret row, in page order, with their drawn grid-line numbers.
pub(crate) struct RulerRow {
row: usize,
pub(crate) borders: Vec<(usize, f32)>,
pub(crate) y: f32,
}
impl RulerRow {
/// The same borders with the active column drag's preview applied.
pub(crate) fn positions(&self, app: &WordApp, page: usize, mods: Mods) -> Vec<f32> {
let preview = caret_drag(app, page).filter(|d| matches!(d.target.edge, Edge::Column(_))).map(|d| (d, d.plan(mods)));
self.borders
.iter()
.map(|&(line, x)| match &preview {
Some((drag, plan)) if line < drag.target.cols.len() => drag.target.planned_x(plan, Some(self.row), line),
_ => x,
})
.collect()
}
}
pub(crate) fn ruler_row(app: &WordApp, layout: &DocLayout, page: usize) -> Option<RulerRow> {
let focus = &app.session.sel.focus;
let (path, row, _) = focus.path.cell()?;
let table = app.session.doc.table(focus.story, &path)?;
let page = layout.pages.get(page)?;
let model_row = table.rows.get(row)?;
// Index by model cell so a page can draw only part of the row or draw cells out of order.
let mut grid_spans = Vec::with_capacity(model_row.cells.len());
let mut start = model_row.first_grid();
for cell in &model_row.cells {
let end = start.saturating_add(cell.span());
grid_spans.push((start, end));
start = end;
}
let rtl_columns = table.props.bidi_visual.then(|| table.cols());
let mut drawn = Vec::new();
for item in &page.items {
let wordcraft_layout::Placed::Cell { rect, table: drawn_table, row: r, cell, story, .. } = item else { continue };
if *story != focus.story || *drawn_table != path || *r != row {
continue;
}
let Some(&(start, end)) = grid_spans.get(*cell) else { continue };
let (left, right) = rtl_columns.map_or((start, end), |n| (n.saturating_sub(end), n.saturating_sub(start)));
drawn.push((*rect, left, right));
}
drawn.sort_by(|a, b| a.0.x.total_cmp(&b.0.x));
let &(first, left, _) = drawn.first()?;
let borders = std::iter::once((left, first.x)).chain(drawn.iter().map(|(rect, _, right)| (*right, rect.right()))).collect();
Some(RulerRow { row, borders, y: first.y + first.h / 2.0 })
}
/// The column widths of the caret table row during an Alt drag.
pub(crate) fn widths(app: &WordApp, ctx: &egui::Context, layout: &DocLayout, page: usize) -> Vec<(f32, f32)> {
if !measuring(app, ctx, page) {
return Vec::new();
}
let story = app.session.sel.focus.story;
let caret = app.session.sel.focus.path.cell().map(|(tp, r, _)| (tp, r));
let Some((tp, r)) = caret else { return Vec::new() };
let mut row: Vec<wordcraft_geom::Rect> = layout.pages.get(page).map_or(Vec::new(), |p| {
p.items
.iter()
.filter_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, table, row, story: cell_story, .. } if *cell_story == story && *table == tp && *row == r => {
Some(*rect)
}
_ => None,
})
.collect()
});
row.sort_by(|a, b| a.x.total_cmp(&b.x));
let Some(first) = row.first() else { return Vec::new() };
let borders_page: Vec<f32> = std::iter::once(first.x).chain(row.iter().map(|b| b.right())).collect();
let mods = mods_now(ctx);
let borders: Vec<f32> = borders_page
.iter()
.enumerate()
.map(|(line, &x)| caret_drag(app, page).and_then(|d| d.ruler_line_x(mods, Some(r), line)).unwrap_or(x))
.collect();
borders.windows(2).map(|w| ((w[0] + w[1]) / 2.0, w[1] - w[0])).collect()
let Some(row) = ruler_row(app, layout, page) else { return Vec::new() };
row.positions(app, page, mods_now(ctx)).windows(2).map(|w| ((w[0] + w[1]) / 2.0, w[1] - w[0])).collect()
}
/// Page y of the bottom of `tg`'s row `row` with `plan` applied (rows above it that change move
+61
View File
@@ -426,6 +426,67 @@ fn alt_column_widths_are_in_the_regions_unit() {
h.app_frame();
}
/// A lower-row canvas drag previews the caret row's own borders and Alt widths before
/// committing the same resize. A merged cell spans the dragged line, hiding that line.
#[test]
fn canvas_column_drag_keeps_ruler_feedback_on_caret_row_grid_lines() {
for merged in [false, true] {
let mut h = table_window();
if merged {
for c in 0..2 {
let b = cell(&mut h, 0, c);
h.state_mut().run("caret.set", json!({"page": 0, "x": b.x + b.w / 2.0, "y": b.y + b.h / 2.0, "extend": c != 0})).unwrap();
}
h.state_mut().run("table.merge", json!({})).unwrap();
}
let first = cell(&mut h, 0, 0);
h.state_mut().run("caret.set", json!({"page": 0, "x": first.x + first.w / 2.0, "y": first.y + first.h / 2.0})).unwrap();
steps(&mut h, 2);
let count = if merged { 2 } else { 3 };
let mut borders = vec![first.x];
borders.extend((0..count).map(|c| cell(&mut h, 0, c).right()));
let (left, right) = (cell(&mut h, 1, 0), cell(&mut h, 1, 1));
let y = left.y + left.h / 2.0;
let start = screen(&mut h, left.right(), y);
let end = screen(&mut h, left.right() + 18.0, y);
let depth = h.state().session.undo_depth();
h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT));
h.event(egui::Event::PointerMoved(start));
steps(&mut h, 2);
button(&h, start, true);
for (pointer, delta) in [(start, 0.0), (end, 18.0)] {
h.event(egui::Event::PointerMoved(pointer));
steps(&mut h, 2);
assert!(h.state().canvas.table_resize.is_some());
assert_eq!(h.state().session.sel.focus.path.cell().map(|(_, row, _)| row), Some(0));
assert_eq!(h.state().session.undo_depth(), depth);
let expected = |i: usize| borders[i] + if !merged && i == 1 { delta } else { 0.0 };
for i in 0..borders.len() {
let at = screen(&mut h, expected(i), first.y);
let mark = ruler_marker(&h, "Table Column Width", at).center();
assert!((mark.x - at.x).abs() < 1.0, "merged={merged}, delta={delta}, border {i}: {mark:?} vs {at:?}");
}
let layout = h.state_mut().session.layout();
let widths = super::widths(h.state(), &h.ctx, &layout, 0);
assert_eq!(widths.len(), count);
for (i, &(mid, width)) in widths.iter().enumerate() {
assert!((mid - (expected(i) + expected(i + 1)) / 2.0).abs() < 0.5, "{widths:?}");
assert!((width - (expected(i + 1) - expected(i))).abs() < 0.5, "{widths:?}");
}
}
button(&h, end, false);
steps(&mut h, 3);
assert_eq!(h.state().session.undo_depth(), depth + 1);
assert!((cell(&mut h, 1, 0).w - (left.w + 18.0)).abs() < 0.5);
assert!((cell(&mut h, 1, 1).w - (right.w - 18.0)).abs() < 0.5);
if merged {
assert!((cell(&mut h, 0, 0).w - first.w).abs() < 0.5);
}
}
}
/// Alt while a column border is dragged reports each column's width on the ruler, as it is
/// going to be (#7586).
#[test]
+35 -14
View File
@@ -397,8 +397,7 @@ fn hyperlink_shortcut_focuses_address_and_preserves_document() {
let mut a = app();
a.run("text.insert", json!({"text": "Keep this text"})).unwrap();
a.run("select.text", json!({"text": "Keep this text"})).unwrap();
let mut h = harness(a);
h.run_steps(2);
let mut h = crate::test_harness::builder().with_size(egui::vec2(600.0, 400.0)).build_eframe(|_| a);
for (event, expected) in [
(egui::Event::Paste("https://example.com".into()), "https://example.com"),
@@ -407,7 +406,7 @@ fn hyperlink_shortcut_focuses_address_and_preserves_document() {
press(&mut h, egui::Key::K, egui::Modifiers::COMMAND);
assert!(h.state().dialog_host.open_dialogs().iter().any(|d| d.key.as_deref() == Some("link")), "Link dialog open");
h.event(event);
h.run_steps(2);
h.step();
let address = h.get_by_label("Address:").value().unwrap_or_default();
assert_eq!(address, expected, "input replaces the initial address");
let display = h.get_by_label("Text to display:").value().unwrap_or_default();
@@ -1539,7 +1538,11 @@ fn prompt_message(a: &WordApp) -> Option<String> {
fn prompt(a: &WordApp) -> Option<&'static str> {
// The close operation is the app's, the question is the drawn window's: a prompt asked in the window of a document
// that another window replaced is no longer the question this window asks.
if a.closing.as_ref().and_then(|c| c.prompt).is_some_and(|id| a.dialog_host.get_by_id::<craft::ui::dialog::UnsavedChangesDialog>(id).is_some()) {
if a.closing
.as_ref()
.and_then(|c| c.prompt)
.is_some_and(|id| a.dialog_host.get_by_id::<craft::ui::dialog::HostedUnsavedChangesDialog>(id).is_some())
{
return Some("saveChanges");
}
let (key, _) = open_dialog(a)?;
@@ -3218,10 +3221,8 @@ fn autosave_is_blocked_with_a_reason_for_files_it_cannot_keep() {
assert!(why.contains("notes.md") && why.contains(".docx"), "{why}");
let err = a.run("file.autosave", json!({"value": true})).unwrap_err();
assert_eq!(err, why, "scripts are told why");
assert!(a.run("file.autosave", json!({"value": false})).is_ok(), "turning it off always works");
a.autosave = true;
// Save As .docx (what the greyed switch offers) lifts the block.
// Without an explicit opt-out, saving a supported copy makes it eligible for AutoSave.
let docx = dir.join("notes.docx");
a.run("file.saveAs", json!({"path": docx.to_string_lossy()})).unwrap();
assert_eq!(a.autosave_block(), None);
@@ -3231,6 +3232,18 @@ fn autosave_is_blocked_with_a_reason_for_files_it_cannot_keep() {
assert!(!a.session.dirty, "AutoSave wrote the .docx");
assert_eq!(a.run("file.autosave", json!({})).unwrap(), json!({"value": false}), "toggling turns it off");
assert!(!a.autosaves());
// Turning it off while blocked is also a user choice. Save As lifts the format block,
// but it takes the document switch to enable AutoSave again.
let mut opted_out = app();
opted_out.run("file.open", json!({"path": md.to_string_lossy()})).unwrap();
assert_eq!(opted_out.run("file.autosave", json!({"value": false})).unwrap(), json!({"value": false}));
let copy = dir.join("opted-out.docx");
opted_out.run("file.saveAs", json!({"path": copy.to_string_lossy()})).unwrap();
assert_eq!(opted_out.autosave_block(), None);
assert!(!opted_out.autosaves(), "Save As must preserve the explicit opt-out");
opted_out.run("file.autosave", json!({"value": true})).unwrap();
assert!(opted_out.autosaves(), "the document switch explicitly enables AutoSave");
let _ = std::fs::remove_dir_all(&dir);
}
@@ -3311,9 +3324,9 @@ fn the_autosave_switch_refuses_a_document_opened_from_bytes() {
}
/// AutoSave turned off in one document stays off there when another document turns it on: the
/// preference is shared, but each document's go-ahead is its own.
/// preference is shared, but a manual Save must keep the document's switch choice.
#[test]
fn autosave_turned_off_stays_off_when_another_document_turns_it_on() {
fn manual_save_preserves_a_documents_autosave_opt_out() {
let dir = scratch("autosave-two");
let (first_path, second_path) = (dir.join("first.docx"), dir.join("second.docx"));
let mut c = typed();
@@ -3321,8 +3334,7 @@ fn autosave_turned_off_stays_off_when_another_document_turns_it_on() {
let mut a = typed();
a.run("file.save", json!({"path": first_path.to_string_lossy()})).unwrap();
let first = a.session.document_id();
let saved = std::fs::read(&first_path).unwrap();
assert!(a.autosaves());
assert!(a.autosaves(), "saving normally enables the default");
a.run("file.autosave", json!({"value": false})).unwrap();
a.run("file.open", json!({"path": second_path.to_string_lossy()})).unwrap();
assert_ne!(a.session.document_id(), first, "the second file opens beside the first");
@@ -3330,13 +3342,22 @@ fn autosave_turned_off_stays_off_when_another_document_turns_it_on() {
assert!(a.autosaves());
a.show_document(first).unwrap();
assert!(!a.autosaves(), "the first document's switch is still off");
a.run("text.insert", json!({"text": "Later "})).unwrap();
a.run("text.insert", json!({"text": "Manual save. "})).unwrap();
a.run("file.save", json!({})).unwrap();
assert!(!a.session.dirty, "manual Save still writes");
assert!(!a.autosaves(), "manual Save must not turn the switch back on");
let saved = std::fs::read(&first_path).unwrap();
a.run("text.insert", json!({"text": "Later edit. "})).unwrap();
a.autosave_tick(monotonic_ms() + 10_000.0);
assert!(a.session.dirty);
assert_eq!(std::fs::read(&first_path).unwrap(), saved, "the first file is untouched");
// Turned back on, it covers the file it was saved to without another save.
assert_eq!(std::fs::read(&first_path).unwrap(), saved, "the later edit must not reach the file");
// Turned back on, it covers the file it was saved to without another manual save.
a.run("file.autosave", json!({"value": true})).unwrap();
assert!(a.autosaves());
a.autosave_tick(monotonic_ms() + 20_000.0);
assert!(!a.session.dirty);
let reloaded = wordcraft_engine::io::open_path(&first_path).unwrap();
assert!(reloaded.plain_text(wordcraft_doc::StoryRef::Body).contains("Later edit."));
let _ = std::fs::remove_dir_all(&dir);
}
+72 -35
View File
@@ -1,11 +1,7 @@
use std::path::Path;
use std::sync::Arc;
use craft::font_manager::Catalog;
use craft::font_manager::craft_font_catalog::{FontEnv, Limits, Os, Source};
use craft::font_manager::picker::FontPickerSettings;
use craft::font_manager::craft_font_catalog::{Limits, Source};
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Bind, Props as _, Show as _};
use craft::ui::contract::{Props as _, Show as _};
use egui::accesskit::Role;
use egui::{Key, vec2};
use egui_kittest::kittest::{By, NodeT, Queryable};
@@ -16,12 +12,20 @@ use crate::{Services, WordApp};
fn ensure_catalog_ready() {
let catalog = Catalog::global();
let count = catalog.families().iter().filter(|f| !f.starts_with('.')).count();
if count < 2 {
for bytes in [
include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").as_slice(),
include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf").as_slice(),
] {
catalog.scan_in_background();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !catalog.is_ready() && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(catalog.is_ready(), "font catalog finished scanning");
let families = catalog.families();
for (family, bytes) in [
("Inter", include_bytes!("../../../../assets/fonts/Inter-Regular.ttf").as_slice()),
("JetBrains Mono", include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf").as_slice()),
("Source Serif 4", include_bytes!("../../../../assets/fonts/SourceSerif4-Regular.ttf").as_slice()),
] {
if !families.iter().any(|f| f == family) {
let _ = catalog.add_bytes(bytes.to_vec(), Source::Bundled, &Limits::default());
}
}
@@ -227,24 +231,21 @@ fn drawn_buttons_fade_in_on_hover_and_darken_while_pressed() {
assert_eq!(fill_after, None, "Save button must clear hover fill after unhovering");
}
/// #7317: typing in WordCraft's `font_picker` updates the popup list on the same frame as the
/// keystroke, shows the Recently Used Fonts section again when cleared, and narrows immediately
/// on subsequent typing.
/// #7317 / #8447: typing in WordCraft's `font_box` updates the popup list on the same frame as
/// the keystroke, shows the Recently Used Fonts section (and WordCraft's `Add Font…` action row)
/// again when cleared, and narrows immediately on subsequent typing.
#[test]
fn the_typed_list_shows_on_the_frame_of_the_keystroke() {
const RECENT: &str = "Source Serif 4";
let env = FontEnv { os: Os::None, ..Default::default() };
let catalog = Arc::new(Catalog::new(env).with_font_service(false));
catalog.set_app_dirs(vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts")]);
catalog.rescan();
assert!(catalog.families().iter().any(|f| f == "Inter"), "fixed catalog loaded assets/fonts");
ensure_catalog_ready();
let mut settings = FontPickerSettings::default();
settings.recent = vec![RECENT.to_string()];
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample")), Services::default());
app.ui.language = "en".into();
app.ui.font_picker.recent = vec![RECENT.to_string()];
let mut family = String::new();
let mut h = crate::test_harness::builder().with_size(vec2(400.0, 900.0)).build_ui(move |ui| {
let _ = super::font_picker("Font", Bind::bound(&mut family), &catalog, Bind::bound(&mut settings), &[], None).show(ui);
let _ = super::font_box(ui, &mut app, "Font", &mut family);
});
h.run_steps(2);
@@ -266,13 +267,13 @@ fn the_typed_list_shows_on_the_frame_of_the_keystroke() {
let frames: [(Vec<egui::Event>, &[&str], &[&str], bool); 7] = [
// Typing an unmatched query clears the list; one Backspace restores recents + all fonts on that frame.
(vec![egui::Event::Text("x".into())], &[], &[RECENT, "Inter", "JetBrains Mono"], false),
(erase(), &[RECENT, "Inter", "JetBrains Mono"], &[], true),
(vec![egui::Event::Text("!".into())], &[], &[RECENT, "Inter", "JetBrains Mono"], false),
(erase(), &[RECENT], &[], true),
// Typing narrows immediately on the keystroke frame and excludes non-matching families.
(vec![egui::Event::Text("jet".into())], &["JetBrains Mono"], &["Inter", RECENT], false),
(erase(), &["JetBrains Mono"], &["Inter"], false),
(erase(), &["JetBrains Mono"], &["Inter"], false),
(erase(), &[RECENT, "Inter", "JetBrains Mono"], &[], true),
(erase(), &[RECENT], &[], true),
(vec![egui::Event::Text("int".into())], &["Inter"], &["JetBrains Mono"], false),
];
@@ -301,15 +302,51 @@ fn the_typed_list_shows_on_the_frame_of_the_keystroke() {
assert!(texts.iter().all(|t| t != label), "keystroke {n}: expected {label:?} to be filtered out on the frame, got texts: {texts:?}");
}
if restores_recents {
let recent_y = h.get_by_label("Recently Used Fonts").rect().min.y;
let all_y = h.get_by_label("All Fonts").rect().min.y;
assert!(
h.query_all_by_role_and_label(Role::TreeItem, RECENT).any(|row| {
let y = row.rect().min.y;
recent_y < y && y < all_y
}),
"keystroke {n}: expected {RECENT:?} between Recently Used Fonts and All Fonts on the clearing frame"
);
let jetbrains_y = h.query_all_by_role_and_label(Role::TreeItem, "JetBrains Mono").map(|row| row.rect().min.y).next();
if let (Some(recent_heading), Some(all_heading)) = (h.query_by_label("Recently Used Fonts"), h.query_by_label("All Fonts")) {
let recent_y = recent_heading.rect().min.y;
let all_y = all_heading.rect().min.y;
assert!(
h.query_all_by_role_and_label(Role::TreeItem, RECENT).any(|row| {
let y = row.rect().min.y;
recent_y < y && y < all_y
}),
"keystroke {n}: expected {RECENT:?} between Recently Used Fonts and All Fonts on the clearing frame"
);
} else if let Some(jb_y) = jetbrains_y {
// When system fonts push `JetBrains Mono` down the catalog and `List` keeps that
// prior lead in view on clear, the restored recent row still sits above `All Fonts`.
assert!(
h.query_all_by_role_and_label(Role::TreeItem, RECENT).any(|row| row.rect().min.y < jb_y),
"keystroke {n}: expected restored recent {RECENT:?} above JetBrains Mono on the clearing frame"
);
} else {
panic!("keystroke {n}: expected Recently Used Fonts and All Fonts headings on the clearing frame");
}
}
}
// Clearing `"int"` restores the full list with WordCraft's `Add Font…` action row at the end.
for _ in 0..3 {
send(&mut h, erase());
}
let list_center = h.get_by_role_and_label(Role::ListBox, "Fonts").rect().center();
h.event(egui::Event::PointerMoved(list_center));
for _ in 0..20 {
if h.query_by_role_and_label(Role::TreeItem, "Add Font…").is_some() {
break;
}
h.event(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Page,
delta: vec2(0.0, -20.0),
phase: egui::TouchPhase::Move,
modifiers: egui::Modifiers::NONE,
source: egui::MouseWheelSource::Unknown,
});
h.step();
}
assert!(
h.query_by_role_and_label(Role::TreeItem, "Add Font…").is_some(),
"expected WordCraft's Add Font… action row at the end of font_box's cleared list"
);
}
+1
View File
@@ -186,6 +186,7 @@ impl WordApp {
clipboard_published: _,
// Per document: the shown document's, swapped with `parked` on a document switch.
autosave_path: _,
autosave_choice: _,
read_from: _,
parked: _,
// Per window.
+113 -22
View File
@@ -30,7 +30,8 @@
use craft::ui::contract::{BodyCx, Props as _, ShowContainer as _, SizeLimits};
// PLAN: assumed `craft::ui::runtime::env::WindowKey` is the facade path of ui-contract's `runtime/env/shell.rs` `WindowKey`.
use craft::ui::runtime::env::WindowKey;
use craft::ui::runtime::windows::{WindowAction, WindowHost};
use craft::ui::runtime::memory::SaveKey;
use craft::ui::runtime::windows::{WindowAction, WindowHost, windowless_root};
use craft::ui::shell::DocumentWindow;
use craft::ui::style::StyleCx;
use craft::window::{Document, WindowId, WindowList, WindowMenu};
@@ -112,6 +113,13 @@ 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 window that takes and keeps the saved place (windowless root only: the root has no OS
/// window, so the first document window does). It stays this window: one that later becomes the
/// root entry must not jump to the saved place.
// lean: once it closes no window saves its place; hand the key over (save-only) if users miss it.
main_window: Option<WindowId>,
/// Documents whose window could not open: they get no new window, or every frame would retry.
failed_open: Vec<u64>,
}
impl Windows {
@@ -119,7 +127,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,
main_window: None,
failed_open: Vec::new(),
}
}
/// Whether documents get native windows of their own.
@@ -192,7 +209,7 @@ impl Windows {
/// The viewport window `id` draws in, while its OS window is open: the root's for the root
/// entry, else the one the window host names for the window's container.
fn viewport_of(&self, ctx: &egui::Context, id: WindowId) -> Option<ViewportId> {
if id == self.root {
if id == self.root && !windowless_root(ctx) {
return Some(ViewportId::ROOT);
}
WindowHost::of(ctx).viewport_of(window_container_id(id))
@@ -212,11 +229,20 @@ impl WordApp {
/// The egui viewport of the active window, the one focused last: control input,
/// `ui.screenshot` and `ui.resize` are its. The root viewport when the windows don't have
/// viewports of their own (the web app, embedded viewports) or the window has none yet.
/// viewports of their own (the web app, embedded viewports). With a windowless root it is always a
/// document viewport (the root has no window to draw, screenshot or take input), the first open one
/// when the active window has none yet; the root only before any document window exists.
pub fn active_viewport(&self) -> ViewportId {
let Some(ctx) = self.ctx.as_ref().filter(|ctx| self.windows.native && WindowHost::of(ctx).opens_windows()) else { return ViewportId::ROOT };
let id = self.windows.list.active().unwrap_or(self.windows.shown);
self.windows.viewport_of(ctx, id).unwrap_or(ViewportId::ROOT)
let own = self.windows.viewport_of(ctx, id);
if windowless_root(ctx) { own.or_else(|| self.windows.viewports(ctx).first().copied()) } else { own }.unwrap_or(ViewportId::ROOT)
}
/// The viewport of the window with key `key` (the number `ui.inspect` windows gives: `current`, `others[].id`): `None` when there is no such window or its OS window isn't open yet.
pub fn window_viewport(&self, key: u64) -> Option<ViewportId> {
let ctx = self.ctx.as_ref().filter(|ctx| self.windows.native && WindowHost::of(ctx).opens_windows())?;
self.windows.viewport(ctx, key)
}
/// Whether a close request for the root viewport closes only the window drawn there: true
@@ -382,7 +408,12 @@ impl WordApp {
let behind = self.windows.list.active();
let active = self.session.document_id();
for d in self.session.documents() {
if d.id == active || Some(d.id) == self.no_document || d.id == self.shown_document || self.windows.of_doc(d.id).is_some() {
if d.id == active
|| Some(d.id) == self.no_document
|| d.id == self.shown_document
|| self.windows.of_doc(d.id).is_some()
|| self.windows.failed_open.contains(&d.id)
{
continue;
}
self.windows.list.open(Window::new(d.id, Some(Box::new(WindowUi::new(d.id))), None, true));
@@ -462,7 +493,9 @@ impl WordApp {
w.requests.push(req.clone());
}
if let Some(ctx) = &self.ctx {
ctx.request_repaint_of(self.windows.viewport(ctx, key).unwrap_or(ViewportId::ROOT));
ctx.request_repaint_of(
self.windows.viewport(ctx, key).or_else(|| self.windows.viewports(ctx).first().copied()).unwrap_or(ViewportId::ROOT),
);
}
true
}
@@ -535,22 +568,28 @@ impl WordApp {
self.after_windows();
return;
}
let raise_root = self.windows.list.get_mut(self.windows.root).is_some_and(|w| std::mem::take(&mut w.raise));
if raise_root {
WindowHost::of(&ctx).act(ViewportId::ROOT, WindowAction::Focus);
}
self.draw_entry(ui, self.windows.root.get());
let root = self.windows.root;
// The root window gaining OS focus makes its entry the active one, as a child's `focus_gained` does.
let root_focused = WindowHost::of(&ctx).facts(ViewportId::ROOT).is_some_and(|facts| facts.focused);
if root_focused && !std::mem::replace(&mut self.windows.root_focused, root_focused) {
self.windows.list.focus(root);
// A windowless root has no window: its entry is a document window like the others. With a
// visible root (X11) the root window draws the root entry itself.
let windowless = windowless_root(&ctx);
if !windowless {
let raise_root = self.windows.list.get_mut(root).is_some_and(|w| std::mem::take(&mut w.raise));
if raise_root {
WindowHost::of(&ctx).act(ViewportId::ROOT, WindowAction::Focus);
}
self.draw_entry(ui, root.get());
// The root window gaining OS focus makes its entry the active one, as a child's `focus_gained` does.
let root_focused = WindowHost::of(&ctx).facts(ViewportId::ROOT).is_some_and(|facts| facts.focused);
if root_focused && !std::mem::replace(&mut self.windows.root_focused, root_focused) {
self.windows.list.focus(root);
}
self.windows.root_focused = root_focused;
}
self.windows.root_focused = root_focused;
let menu = self.window_menu();
let step = StyleCx::with_root(&ctx, |cx| cx.tokens.size.window.cascade);
let ids: Vec<WindowId> = self.windows.list.ids().filter(|&id| id != root).collect();
let ids: Vec<WindowId> = self.windows.list.ids().filter(|&id| windowless || id != root).collect();
let mut closes = Vec::new();
let mut failed = Vec::new();
for id in ids {
let Some(w) = self.windows.list.get_mut(id) else { continue };
let (raise, place) = (std::mem::take(&mut w.raise), std::mem::take(&mut w.place));
@@ -560,17 +599,40 @@ impl WordApp {
if raise {
window = window.raise();
}
let first = windowless && id == root && self.windows.main_window.is_none();
if first {
self.windows.main_window = Some(id);
}
let main = windowless && self.windows.main_window == Some(id);
if main {
// Every frame, so the place is saved as the user moves or sizes the window.
window = window.remember(SaveKey::new("wordcraft.main_window"));
}
if place && let Some(rect) = self.cascade_from(ui, id, step) {
window = window.first_placed(rect);
} else if first {
// The first window takes the place the root window had: the saved one, else the default size.
let default = egui::Rect::from_min_size(egui::pos2(80.0, 60.0), egui::vec2(1440.0, 920.0));
window = window.first_placed(default);
}
let out = window.show(ui, |ui, cx| self.draw_window(ui, cx, id)).output;
let mut drawn = false;
let out = window
.show(ui, |ui, cx| {
drawn = true;
self.draw_window(ui, cx, id)
})
.output;
if out.focus_gained {
self.windows.list.focus(id);
}
if out.close_requested.is_some() {
closes.push(id);
// Asked to close without ever drawing: the window could not be opened.
if drawn { closes.push(id) } else { failed.push(id) }
}
}
for id in failed {
self.window_failed_to_open(id);
}
self.window_events(&closes);
self.after_windows();
}
@@ -623,13 +685,42 @@ impl WordApp {
/// host asks about ([`WordApp::close_requested`]).
fn window_events(&mut self, closes: &[WindowId]) {
for &id in closes {
if self.quit_requested || self.windows.list.len() <= 1 || !self.windows.list.contains(id) {
if self.quit_requested || !self.windows.list.contains(id) {
continue;
}
self.close_window(id.get());
if self.windows.list.len() > 1 {
self.close_window(id.get());
} else if self.ctx.as_ref().is_some_and(windowless_root) {
// The only window has no root to take its close: it asks as a quit does, which
// ends the app once every document is answered for.
if self.raise_closing().is_none()
&& self.close_requested()
&& let Some(ctx) = &self.ctx
{
WindowHost::of(ctx).act(ViewportId::ROOT, WindowAction::Close);
}
}
}
}
/// Window `id` was asked to close before it drew: the OS refused it (no window or surface). Its
/// entry goes without a Save prompt and the person is told; the document stays open. With no
/// other window the app has nothing to show and ends.
fn window_failed_to_open(&mut self, id: WindowId) {
let Some(doc) = self.windows.list.get(id).map(|w| w.doc) else { return };
let name = self.session.documents().into_iter().find(|d| d.id == doc).map(|d| d.title).unwrap_or_default();
log::error!("window for document {doc} could not be opened");
if self.windows.list.len() <= 1 {
// lean: no window to tell the person in; the log has it. Quit rather than run with nothing.
self.quit_requested = true;
return;
}
self.windows.failed_open.push(doc);
self.windows.list.close(id);
self.settle_windows();
self.status(crate::i18n::fmt(tl!("A window for “{name}” could not be opened, so that document has no window."), &[("name", &name)]));
}
/// The close button of window `key` (not the last one): File › Close in that window, which
/// asks about unsaved changes first.
pub(crate) fn close_window(&mut self, key: u64) {
+220 -1
View File
@@ -38,6 +38,13 @@ impl Rig {
Rig { kit: Kit::with(spec), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new(), builders: Vec::new() }
}
/// A rig whose root is a windowless logical root: every document window is a child.
fn windowless() -> Rig {
let spec = craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), Arc::new(craft::ui::testing::windows::FakeSystem::new()))
.windowless_root();
Rig { kit: Kit::with(spec), focused: None, closing: Vec::new(), commands: Vec::new(), drawn: Vec::new(), builders: Vec::new() }
}
fn ctx(&self) -> egui::Context {
self.kit.ctx.clone()
}
@@ -350,7 +357,7 @@ fn parked_prompt_answer(answer: craft::quit::CloseAnswer, name: &str, saved_text
rig.frame(&mut a);
assert!(a.enter_window(first), "the recorded prompt owner remains open");
let id = a.closing.as_ref().unwrap().prompt.unwrap();
a.dialog_host.get_mut_by_id::<craft::ui::dialog::UnsavedChangesDialog>(id).unwrap().set_answer(answer);
a.dialog_host.get_mut_by_id::<craft::ui::dialog::HostedUnsavedChangesDialog>(id).unwrap().set_answer(answer);
assert!(a.dialog_host.confirm_by_id(&rig.ctx(), id));
a.show_window(second);
rig.frames(&mut a, 3);
@@ -802,6 +809,25 @@ fn quitting_asks_about_each_document_in_its_window() {
assert!(a.quit_requested);
}
/// The app menu's Quit (`ui.quit`) asks about unsaved documents like the Dock's Quit, instead of
/// closing one window (#8709).
#[test]
fn quit_command_asks_about_each_unsaved_document() {
let mut rig = Rig::new();
let mut a = app("One");
rig.frames(&mut a, 2);
a.run("file.new", json!({})).unwrap();
a.run("text.insert", json!({"text": "Two"})).unwrap();
rig.frames(&mut a, 2);
a.run("ui.quit", json!({})).unwrap();
assert_eq!(prompt(&a).as_deref(), Some("saveChanges"));
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
assert_eq!(prompt(&a).as_deref(), Some("saveChanges"), "the other document asks too");
assert!(!a.quit_requested);
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
assert!(a.quit_requested);
}
fn window_labels(a: &WordApp) -> Vec<String> {
let mut l: Vec<String> = a.switch_windows_entries().into_iter().map(|(_, label, _)| label).collect();
l.sort();
@@ -918,6 +944,33 @@ fn a_programmatic_close_of_one_of_two_windows_on_a_document_is_accepted() {
assert!(refused.is_some(), "closing the document would lose the work: {refused:?}");
}
/// `file.close {"save": true}` on a document shown in two windows closes the window alone but
/// still writes the document first.
#[test]
fn a_saving_close_of_one_of_two_windows_writes_the_document() {
let mut rig = Rig::new();
let mut a = app("");
let path = docx_on_disk("saving-close", "First");
a.run("file.open", json!({"path": path.to_string_lossy()})).unwrap();
rig.frames(&mut a, 2);
a.run("text.insert", json!({"text": " more"})).unwrap();
a.run("view.newWindow", json!({})).unwrap();
rig.frames(&mut a, 2);
assert_eq!(a.window_count(), 2);
assert!(a.session.dirty);
let before = std::fs::read(&path).unwrap();
let (req, _reply) = ControlRequest::new("engine.execute", json!({"command": "file.close", "params": {"save": true}}));
let r = match crate::control::handle(&mut a, &rig.ctx(), &req) {
Reply::Done(v) => v,
_ => json!({"ok": false, "error": "not a reply"}),
};
assert_eq!(r["ok"], true, "{r}");
assert_eq!(a.window_count(), 1, "the window closed");
assert!(!a.session.dirty, "the document was saved");
assert_ne!(std::fs::read(&path).unwrap(), before, "the file on disk changed");
}
/// The file picks the app asked for, answered when the test says so.
type Shown = Arc<ScriptedFiles>;
@@ -1100,3 +1153,169 @@ fn mod_shift_v_with_nothing_copied_pastes_text_in_second_window() {
rig.frame(&mut a);
assert_eq!(text(&a), "pasted", "Mod+Shift+V with nothing copied pastes text in the second OS window");
}
/// A control-channel request, answered as the channel answers it.
fn ctl(a: &mut WordApp, rig: &Rig, method: &str, params: serde_json::Value) -> serde_json::Value {
let (req, _) = ControlRequest::new(method, params);
match crate::control::handle(a, &rig.ctx(), &req) {
Reply::Done(v) => v,
_ => json!({"ok": false, "error": "not a reply"}),
}
}
/// Spec rule 8: `file.close` on unsaved work needs `save` (write, then close) or `force`; a
/// document with no file can't be saved without asking, so `save` refuses it.
#[test]
fn file_close_over_control_needs_save_or_force_and_save_writes_first() {
let path = docx_on_disk("close-save", "First");
let mut rig = Rig::new();
let mut a = app("First");
a.run("file.save", json!({"path": path.to_string_lossy()})).unwrap();
a.run("file.autosave", json!({"value": false})).unwrap();
a.run("text.insert", json!({"text": " edited"})).unwrap();
let first = a.session.document_id();
a.run("file.new", json!({})).unwrap();
a.run("text.insert", json!({"text": "Draft"})).unwrap();
let draft = a.session.document_id();
rig.frames(&mut a, 2);
a.show_window(a.windows.of_doc(first).unwrap());
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close"}));
assert_eq!(r["ok"], false);
assert!(r["error"].as_str().unwrap().contains("pass save or force"), "{r}");
assert!(a.session.is_open(first) && a.closing.is_none(), "refused: nothing closes and nothing asks");
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close", "params": {"save": true}}));
assert_eq!(r["ok"], true, "{r}");
assert!(!a.session.is_open(first) && a.closing.is_none());
let mut saved = Session::new(wordcraft_doc::Document::new());
saved.run("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
assert_eq!(saved.doc.plain_text(StoryRef::Body).trim(), "First edited");
std::fs::remove_dir_all(path.parent().unwrap()).ok();
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close", "params": {"save": true}}));
assert_eq!(r["ok"], false, "a never-saved document has nowhere to save: {r}");
assert!(a.session.is_open(draft) && a.closing.is_none());
let r = ctl(&mut a, &rig, "engine.execute", json!({"command": "file.close", "params": {"force": true}}));
assert_eq!(r["ok"], true, "{r}");
assert!(!a.session.is_open(draft));
}
/// Spec rule 8: `ui.closeWindow` closes the active window, or the one `window` names.
#[test]
fn ui_closewindow_closes_the_active_window_or_the_one_named() {
let mut rig = Rig::new();
let mut a = app("One");
rig.frames(&mut a, 2);
a.run("file.new", json!({})).unwrap();
rig.frames(&mut a, 2);
let middle = a.windows.shown();
let middle_vp = a.active_viewport();
a.run("file.new", json!({})).unwrap();
rig.frames(&mut a, 2);
let active_vp = a.active_viewport();
assert_ne!(middle_vp, active_vp);
let r = ctl(&mut a, &rig, "ui.closeWindow", json!({"window": middle}));
assert_eq!(r["ok"], true, "{r}");
rig.frame(&mut a);
assert!(rig.sent(middle_vp, &ViewportCommand::Close) && !rig.sent(active_vp, &ViewportCommand::Close), "only the named window");
ctl(&mut a, &rig, "ui.closeWindow", json!({}));
rig.frame(&mut a);
assert!(rig.sent(active_vp, &ViewportCommand::Close), "no `window`: the active one");
assert_eq!(ctl(&mut a, &rig, "ui.closeWindow", json!({"window": 9999}))["ok"], false);
}
/// Spec rule 3: clicking another window while the Save prompt is up brings the prompt back
/// (existing focus handling already does; this pins it).
#[test]
fn clicking_another_window_while_a_prompt_is_up_raises_the_prompt() {
let mut rig = Rig::new();
let mut a = app("First");
rig.frames(&mut a, 2);
let first = a.windows.shown();
a.run("file.new", json!({})).unwrap();
a.run("text.insert", json!({"text": "Second"})).unwrap();
rig.frames(&mut a, 2);
let child = a.active_viewport();
a.close_window(first);
rig.frame(&mut a);
let owner = a.closing.as_ref().unwrap().window;
assert_eq!(owner, first);
rig.focus(child);
let mut raised = false;
for _ in 0..3 {
rig.frame(&mut a);
raised |= rig.sent(ViewportId::ROOT, &ViewportCommand::Focus);
}
assert!(raised, "the prompt's window comes to the front");
assert_eq!(a.closing.as_ref().map(|c| c.window), Some(first), "still the one prompt, still its window's");
}
/// Spec rule 6: Quit asks about each unsaved document in turn; Cancel on the second stops the
/// quit and leaves the remaining windows as they were. A following quit then asks again.
#[test]
fn quit_with_three_modified_documents_asks_three_times_and_cancel_keeps_two() {
let mut rig = Rig::new();
let mut a = app("One");
rig.frames(&mut a, 2);
for t in ["Two", "Three"] {
a.run("file.new", json!({})).unwrap();
a.run("text.insert", json!({"text": t})).unwrap();
rig.frames(&mut a, 2);
}
assert_eq!(a.window_count(), 3);
assert!(!a.quit());
assert_eq!(prompt(&a).as_deref(), Some("saveChanges"));
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
assert_eq!(prompt(&a).as_deref(), Some("saveChanges"), "the second asks");
a.run("ui.saveChanges", json!({"answer": "cancel"})).unwrap();
assert!(!a.quit_requested && a.closing.is_none());
rig.frames(&mut a, 2);
assert_eq!((a.window_count(), a.session.documents().len()), (2, 2), "Cancel keeps the two that are left");
assert!(!a.quit(), "the next quit asks again");
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
assert!(a.quit_requested);
}
/// Spec rule 1 with the windowless root: the first window is a child like the rest, nothing draws in the root, and
/// closing the first of two windows closes that window's document and leaves the other as it was.
#[test]
fn windowless_root_draws_every_document_in_a_child_and_closes_exactly_the_requested_one() {
let mut rig = Rig::windowless();
let mut a = app("First");
let first_doc = a.session.document_id();
rig.frames(&mut a, 2);
a.run("file.new", json!({})).unwrap();
a.run("text.insert", json!({"text": "Second"})).unwrap();
let second_doc = a.session.document_id();
rig.frames(&mut a, 3);
let viewports = a.windows.viewports(&rig.ctx());
assert_eq!(viewports.len(), 2);
assert!(!viewports.contains(&ViewportId::ROOT), "the root is no document window");
assert_ne!(a.active_viewport(), ViewportId::ROOT);
let first_vp = viewports[0];
rig.close(first_vp);
rig.frames(&mut a, 2);
assert_eq!(a.closing.as_ref().unwrap().guard.current(), Some(&first_doc), "the window closed is the one asked about");
a.run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
rig.frames(&mut a, 2);
assert!(!a.session.is_open(first_doc) && a.session.is_open(second_doc));
assert_eq!(text(&a), "Second");
assert_eq!(a.window_count(), 1);
}
/// `ui.closeWindow` says so when nothing was asked: a Save prompt is already up (spec rule 4).
#[test]
fn ui_closewindow_reports_not_requested_while_a_prompt_is_up() {
let mut rig = Rig::new();
let mut a = app("One");
rig.frames(&mut a, 2);
a.run("file.new", json!({})).unwrap();
a.run("text.insert", json!({"text": "Two"})).unwrap();
rig.frames(&mut a, 2);
let first = a.windows.root_key();
a.close_window(first);
rig.frame(&mut a);
assert!(a.closing.is_some());
let r = ctl(&mut a, &rig, "ui.closeWindow", json!({}));
assert_eq!(r["result"]["requested"], false, "{r}");
}
+12
View File
@@ -13,6 +13,18 @@ draws the document itself, so there it stays as it is. The mechanism comes
from the prototype in storytold/craft-libs#584; the framework docs (`docs/craft-framework.md` in
craft-libs) will carry it.
## Amendment 2026-12-03: X11 keeps a visible root
On X11, XWayland and BSD on X11, egui's windowless root (`RootViewportMode::Windowless`, storytold/egui#91)
returns `UnsupportedConfiguration`. There WordCraft falls back to the visible windowed root, and the old
behaviour stays: closing the first window moves another document into it (#7752), because the root window
can't close while the app runs. The other close rules in [the spec](../specs/multi-window-close.md) still
apply. Revisit when egui supports the windowless root on X11 (asked of Skylar, 2026-12-03).
Under the windowless root, Save As and Open have no parent window: egui gives child viewports no window
handle and craft-libs' dialogs take only the root's. They work, but on macOS they are not sheets and on
Windows they don't block their document window, until craft-libs can parent a dialog to a document window.
## Considered options
- **Root takes over another document** (the old behaviour): no framework change, but it is the reported bug,
+18 -9
View File
@@ -96,16 +96,17 @@ let apps move windows, so there Arrange All and Side by Side only resize.
| `engine.commands` | `search?` | every command: id, label, location, shortcut, params, enabled |
| `document.inspect` | `text?`, `doc?` | blocks (text, style, runs, lists, tables), parts, sections, selection, pages |
| `ui.inspect` | — | UI state, view, window size, page rects on screen, caret, the selected comment balloon (`balloon`), perf; `dialogs`: the open dialogs (`id`, `parent`, `key`, `fields`), the top one last; `windows`: the other windows as the drawn window sees them (`available`, `current`, `others`, `sideBySide`, `syncScroll`); `document`: the active document's id; `documents`: the open documents (`id`, `title`, `path`, `dirty`, `active`) |
| `ui.click` | `x`, `y`, `button?` (`left`, `right`, `middle`), `count?`, `hold?`, modifiers; or the `id` or `label` of a `ui.accessTree` node | real pointer input at window coordinates; `hold: true` keeps the button down until `ui.release` |
| `ui.click` | `x?`, `y?`, `coordinates?`, `page?`, `control?`, `button?` (`left`, `right`, `secondary`, `middle`), `count?`, `hold?`, modifiers; or the `id` or `label` of a `ui.accessTree` node (with optional `button?`: `left`, `right`, `secondary`) | real pointer input at the target point or node; `hold: true` keeps the button down until `ui.release` |
| `ui.clickText` | `page` (0-based), `x`, `y` (points from the page's top-left), `count?` | click inside a page; replies at once with `screen`, the window point it clicks (`[x, y]`), before the click is processed |
| `ui.move` | `x`, `y`, modifiers | pointer move; with a button held (`ui.click` with `hold`), a drag you can screenshot halfway |
| `ui.release` | `button?` or `key?`, `x?`, `y?` | lets go of what `hold` keeps down (with neither `button` nor `key`, everything, modifiers too). A drag is `ui.click` with `"hold": true`, then `ui.move`, then `ui.release` |
| `ui.wheel` | `x`, `y`, `dy`, `dx?`, `unit?` (`points`, the default, or `lines`), modifiers | mouse-wheel or trackpad scroll at window coordinates (`dy` < 0 scrolls down) |
| `ui.move` | `x`, `y`, `coordinates?`, `page?`, `rest?` (0–10 s), modifiers; or the `id` or `label` of a `ui.accessTree` node, `rest?`, modifiers | pointer move (to the point, or to the centre of the node's rect); `rest` waits that many seconds before replying; with a button held (`ui.click` with `hold`), a drag you can screenshot halfway |
| `ui.drag` | `from`, `to` (each `{x?, y?, coordinates?, page?, control?}`), `button?` (`left`, `right`, `middle`), `steps?` (1–200, default 12), modifiers | one-request drag: presses at `from`, moves in even `steps` to `to`, and releases |
| `ui.release` | `button?` or `key?`, `x?`, `y?`, `coordinates?`, `page?`, `control?` | lets go of what `hold` keeps down (with neither `button` nor `key`, everything, modifiers too). A drag you can pause or screenshot halfway is `ui.click` with `"hold": true`, then `ui.move`, then `ui.release` |
| `ui.wheel` | `x?`, `y?`, `coordinates?`, `page?`, `control?`, `dy?`, `dx?`, `unit?` (`points`, the default, or `lines`), modifiers | mouse-wheel or trackpad scroll at the target point (`dy` < 0 scrolls down) |
| `ui.key` | `key` (`B`, `Enter`, `Left`…), `hold?`, modifiers | key press through egui (shortcuts apply); `hold: true` keeps the key down until `ui.release` |
| `ui.type` | `text` | typed text through egui |
| `ui.ime` | `preedit` with `cursor?` (`[start, end]` in its characters), or `commit` | input-method composition: the text being composed, or the text it commits |
| `ui.capsLock` | `on` (`true` or `false`; `null` returns it to the keyboard's own state) | Caps Lock for the input that follows |
| `ui.drop` | `paths`, `hover_only?`, `x?`, `y?` | files dropped on the window there (where the pointer is without `x` and `y`), as from a file manager; `hover_only` only holds them over it |
| `ui.drop` | `paths`, `hover_only?`, `x?`, `y?`, `coordinates?`, `page?`, `control?` | files dropped on the window there (where the pointer is without `x`, `y` and `control`), as from a file manager; `hover_only` only holds them over it |
| `ui.screenshot` | `path?`, `region?` (`[x0, y0, x1, y1]` in points) | PNG of the window (or of `region`) in the root viewport: written to `path` (a `.png` file), or without one returned in the reply as `base64`, with `mime`, `width`, `height` and `pixels_per_point`. 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 |
@@ -115,11 +116,18 @@ let apps move windows, so there Arrange All and Side by Side only resize.
| `ui.dialog.set` | `dialog` (an `id` from `ui.inspect`'s `dialogs`, or `"top"`), `field` and `value`, or `fields` (`[{"field", "value"}]`, all or none) | sets the dialog's fields |
| `ui.dialog.confirm` | `dialog`, `choice?` (which button of a prompt) | answers OK, as the default button does |
| `ui.dialog.cancel` | `dialog` | closes the dialog, as Escape does |
| `ui.closeWindow` | — | the root window's close button: unsaved work brings up the Save prompt; the reply's `requested` says whether the close was asked for |
| `ui.closeWindow` | `window?` | the close button of the window with that key (from `ui.inspect` → `windows`: `current`, `others[].id`), the active window by default: unsaved work brings up the Save prompt in that window; the reply's `requested` says whether the close was asked for (false while a Save prompt is already open: answer it first); errors "no document window is open" when only the windowless root remains |
| `ui.clipboard` | `text?`, `html?`, `rtf?`, `png?` (base64) | puts those flavours on the clipboard; the reply's `offered` lists them |
| `ui.replayAt` | `at` (0–1) | holds Ink Replay at that fraction of its length, while Ink Replay is on |
| `app.quit` | `force?` | quits (see [Closing the document](#closing-the-document)) |
Pointer positions default to window points (`coordinates: "screen"`). `coordinates: "document"` maps
page points through the canvas with `page?` (0-based, default `0`). `control` (`{name, role?,
within?, index?}`) places the pointer at the centre of the matching `ui.accessTree` control plus an
optional `x`, `y` offset (default `0`), and excludes `coordinates`; `ui.click`, `ui.release`,
`ui.wheel` and `ui.drop` resolve `control`, whereas `ui.move` requires `x` and `y` when no `id` or
`label` is given (it allows `control` as a field name, though `x` and `y` still set the point).
Modifiers are `shift`, `alt`, `command` (⌘ on macOS, Ctrl elsewhere) and `ctrl` (the Control key on macOS), each `true` or `false`.
Any other method name is treated as a command id: `{"method": "format.bold"}` works.
@@ -197,8 +205,8 @@ Positions are `{"story": "body" | {"part": n}, "path": [block, row, cell, block,
owns keyboard focus. Shortcuts, dialogs and document protection still apply. These methods do
not activate the native window.
`ui.click`, `ui.move`, `ui.release`, `ui.wheel`, `ui.key`, `ui.type`, `ui.ime`, `ui.capsLock`,
`ui.drop` and `ui.focus` defer their successful replies (`"result": null`). The current app
`ui.click`, `ui.move`, `ui.drag`, `ui.release`, `ui.wheel`, `ui.key`, `ui.type`, `ui.ime`,
`ui.capsLock`, `ui.drop` and `ui.focus` defer their successful replies (`"result": null`). The current app
can send a deferred reply during the final input pass, before the UI has applied that pass.
`ui.clickText` replies at once with the window point it clicks (`"screen": [x, y]`), before
the click is processed. `ui.type` sent after it is queued behind the click, but other requests,
@@ -215,7 +223,8 @@ discard unsaved work is **refused with an error** (the app keeps running and the
save first (`file.save`), or pass `{"force": true}` to discard the changes and go ahead.
`file.close` closes the shown document, so it is refused while that document has unsaved
changes; the bare form `{"method": "file.close", "params": {"force": true}}` (a method name that is a
changes (`unsaved changes: pass save or force`); `{"save": true}` writes it first (a document with no
file yet is an error, never a prompt) and then closes it; the bare form `{"method": "file.close", "params": {"force": true}}` (a method name that is a
command id) is guarded the same way, and only a boolean `true` counts as `force`. A document
without unsaved changes closes at once (#1268). Closing closes the document and its window, and
the window focused before it becomes the active one. The last window stays open with no page,
+1
View File
@@ -232,6 +232,7 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text
| 2026-10-31 | trivial | dialogs are dialogs to screen readers, their tabs are tabs, the one shown selected, and colour fields and swatches say their colour |
| 2026-11-01 | trivial | formatting shortcuts say what they did to screen readers |
| 2026-10-30 | trivial | the Paste button is named "Paste" for screen readers, without macOS's key on other platforms; the status bar's Go To hint shows the platform's key |
| 2026-11-17 | trivial | A floating table placed by an offset takes `w:tblInd` before Word 2013 (its first cell's text at the offset moved by the indent) and, from Word 2013, stands half its left border in from the offset with `w:tblInd` ignored, as measured in Word for Windows; no ranked gap changed |
| 2026-11-17 | trivial | Right-to-left tables (`w:bidiVisual`): a cell's `w:left` and `w:right` margins (or `w:start` and `w:end`, the cell's or the table's) stay on the sides they name, as measured in Word for Windows; only the left and right borders are drawn mirrored; no ranked gap changed |
| 2026-10-30 | trivial | #5: a list item deleted whole under Track Changes shows its number as deleted text, in the deletion's colour and mark, and hides it where deletions are hidden (#4828); estimate unchanged |
| 2026-11-03 | trivial | A picture inserted or pasted in a table cell fits the cell (a nested cell too), in text columns the column, in another section that section, instead of the first section's text width (#5428); a fix, so no ranked gap changed; readiness estimates unchanged |
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -218,7 +218,8 @@ document: the tool works on that document and the active one stays active.
An id that names no open document, or a value that isn't a whole number from 0 up, is a tool error.
`execute` with `view.switchWindows {"id": n}` makes a document active, and `file.closeDocument
{"id": n, "force"?: true}` closes one (unsaved changes need `force`). Through `--connect`, `doc`
{"id": n, "force"?: true}` closes one (unsaved changes need `force`); `file.close {"save"?: true, "force"?: true}` closes the shown
document, and unsaved changes need `save` (write, then close) or `force`. Through `--connect`, `doc`
reaches the app's control channel (see [Open documents](control-protocol.md#open-documents)); the
app's window keeps showing the document it showed. `screenshot`, `click` and `key` act on the
window, so they work on the document on screen.
+1
View File
@@ -176,6 +176,7 @@ Windows/Linux keys are given first, macOS second.
| AltGr (Right Alt on Polish, German, Czech… layouts) | AltGr+letter types the layout's character (AltGr+S → ś, AltGr+L → ł) and a bare AltGr tap does nothing; neither opens KeyTips. On Linux AltGr is the Right Alt key with Level 3 Shift, not Alt, so its modifiers event no longer reads as Alt let go (#2388); on Windows it is Ctrl+Alt. Right Alt on a layout without AltGr (US) is Alt and opens KeyTips like Left Alt | ui-egui `altgr_types_its_characters_without_keytips` |
| Shift+Right (⇧→) at the end of a cell's text | the whole cell is selected first (its end-of-cell mark); the next Shift+Right selects the next cell with it. In an empty cell the first press selects the cell | `shift_right_at_the_end_of_a_cell_selects_the_cell_first` |
| Left / Right (← / →) next to an equation | the arrow steps into the equation instead of over it: Right from just before it opens it at its start, Left from just after it opens it at its end. The arrows then move inside it; past its far end the caret leaves on that side, so the same arrow goes on to the text (or, with two equations side by side, steps into the next one: not yet compared with Word). With text selected, the arrow only collapses the selection, as elsewhere; Shift+Left / Right still selects over the equation as one character. **Differs:** not in right-to-left or mixed-direction paragraphs yet (see Known gaps) (#4138) | `left_and_right_keys_step_into_and_out_of_an_equation`, `right_out_of_an_equation_steps_into_the_one_beside_it`; `cmd::equation::tests::left_and_right_step_into_an_equation_next_to_the_caret` |
| Left / Right across a tracked deletion (#8268) | WordCraft skips hidden deleted text and equations within a paragraph in No Markup. In a paragraph that supports entering equations with the arrow keys, the same press can enter a visible equation immediately beyond the deletion. Shift+Left / Right extends the selection across it. When deleted text is visible inline, it keeps its ordinary caret stops. | `tests::horizontal_caret_skips_hidden_tracked_deletions`, `tests::bidi::arrow_keys_skip_hidden_deletions_in_rtl_text`, `arrow_keys_skip_a_deleted_equation_in_no_markup`, `arrow_keys_enter_a_visible_equation_across_a_hidden_deletion` |
## AutoCorrect and AutoFormat as you type
+1 -10
View File
@@ -58,11 +58,7 @@ Document title opens Rename Document; the account badge opens Options › Genera
| Vertical scrollbar track paging | ✅ clicking the vertical scrollbar track above the elevator moves one screen up, and below it moves one screen down, as in Word (#5853, `canvas::tests::clicking_vertical_scrollbar_track_advances_one_screen`); it previously jumped to the clicked position | moves one screen | 90% | — |
| Scrollbar drag page tip | ✅ while the vertical scrollbar is dragged, a tip beside the pointer names the page at the top of the window in the status bar's words ("Page 7 of 10"), on one line however long the number (#2551, #3341, `canvas::tests::dragging_the_scrollbar_names_the_page_at_the_top`); its look and wording not yet compared with Word's | not compared | 70% | 0.5 |
| Interface text on screen (Linux, BSD) | Drawn by egui with Inter's ttfautohint hints, which match FreeType's light autohinting: measured against headless Firefox (Inter, 18.1 and 15.2 px at 1.45x), the same rows of pixels and weight (ink within 1 %) in the light theme. The dark theme no longer looks semi-bold: egui's dark default thickened light-on-dark text (about 21 % more ink than Firefox); it now adds a light 7 % (plain coverage, Firefox's weight, looked soft on the dark tab row; chosen side by side on a 145 % desktop). Not yet: subpixel (LCD) edges | sharp interface text | 90% | — |
| Page text on screen (Linux, BSD) | Lightly hinted as FreeType's `hintslight` draws it (Firefox and other apps there): FreeType's autohinter puts baselines, x-heights and cap heights on whole pixels, nothing moves sideways, so lines break as before. Measured against headless Firefox (Arial, 21.27 px): the same rows of pixels and weight. Subpixel (LCD) edges are their own row below; the interface text (egui) is hinted separately. Exports are unchanged | sharp document text | 90% | — |
| Page text on screen (macOS, Windows) | Drawn from the fonts' own outlines, unhinted, as macOS draws text. Every baseline sits on a whole device pixel (upright text only; a glyph moves half a pixel at most, never sideways, so lines break as before), so the feet of the letters fill one pixel row; between two rows they were two grey ones, which read as blur beside Preview and OpenOffice on the same screen. On macOS, text is also thickened as the system's font smoothing does it, sideways only (1.21 % of the pixel size on each side, 0.3 px at most, none past 72 px per em): stems gain weight and no grey is added above or below the letters. The outline itself is widened and filled once. The softness was found by comparing 144 dpi screenshots of one paragraph (Times New Roman) in WordCraft, Preview and OpenOffice; the fix is checked on headless rasters, not yet side by side in the running app, and not measured against CoreText's own output. Subpixel (LCD) edges are their own row below. Not yet: Windows text has no ClearType-style hinting | sharp document text | 80% | 4–8 (hinting on Windows) |
| Page text and the system's text settings | **Not followed yet.** What each system's values mean is in place (`screen_text.rs`: macOS `AppleFontSmoothing` as a darkening strength; Windows ClearType and stripe orientation; GNOME's and KDE Plasma's antialiasing, hinting and stripe order), and pages are drawn with those settings, and redrawn when they change, once one is recorded. Nothing records one: the app reads the system only through craft-libs' `platform::appearance`, which reports theme, contrast and reduced motion and no text settings. So pages are drawn each platform's fixed way (macOS darkened; Linux and BSD lightly hinted) plus the user's own Screen text smoothing choice. Shared-API gap: craft-libs needs to report the font smoothing strength, antialiasing kind, hinting and stripe order; an earlier version of this work read them in the app itself (macOS only run), which the move of system access to craft-libs rules out. Previews, dragged objects and File › New thumbnails keep the fixed defaults in any case (thumbnails without baseline snapping) | follows system settings | 20% | 4–8 (the craft-libs reader, then the wiring) |
| Subpixel (LCD) page text | File › Options › General › Screen text smoothing (`view.textSmoothing`): Use system setting, Grayscale, Subpixel (LCD). A WordCraft extension, saved per user, never in the document. With subpixel smoothing each colour channel of a pixel takes the text's coverage around its own stripe: the page is rasterised three times, its text a third of a pixel to the left, in place and to the right, and red, green and blue are taken from the matching pass (RGB or BGR stripes). That equals text rasterised three times as wide and averaged over three neighbours (the box filter FreeType calls its light LCD filter); there is no sharper filter and no fringe reduction, so edges show more colour than ClearType's or FreeType's default. Everything but text is drawn as without it. "Subpixel (LCD)" draws it on any screen, in the screen's stripe order where the system names one, else RGB. "Use system setting" is greyscale until the system's settings are read (row above); it then draws subpixel text where the system asks for it on screens below 2 device pixels per point. Only on a page picture rasterised at the screen's own scale or size (next row): Read Mode's columns, and a part of a page shown reduced, stay greyscale. Costs up to three rasters per page with text; not timed. Formatting marks, watermarks, previews and thumbnails stay greyscale. Vertical stripe orders are not drawn. **Run on macOS only**, on headless rasters; not yet seen on a 1x LCD or on Windows or Linux | subpixel text | 50% | 6–12 (check on real screens, timing, a 5-tap filter) |
| Page pictures at the screen's own size | The shared page view asks for each page's picture by its longest side in pixels, rounded up to a multiple of 16, and draws what it gets as its painter draws every picture: the page's place is rounded to whole pixels and the picture fitted inside it by its own proportions. Only a picture of exactly the rounded place's size is drawn one pixel for one. Rasterised at the side asked for, a page is up to 16 pixels too large (A4 at 100 % on a 2x screen: 2256 pixels for 2245); rasterised at the view's own scale and rounded up, as a first version of this did, it is still a pixel or two too large (2017 × 2852 for a 2016 × 2851 place), squeezed by a twentieth of a percent, and the text slides off the pixel grid and back down the page, which reads as blur. Now: once the view is at rest (two passes running put the pages in the same places), each picture is made exactly as many pixels each way as its place, scaled across and down by whatever that takes (a pixel in two thousand apart). While the view moves, pictures stay as they were; a page that comes into view is first made at the view's scale and again, exactly, when the view rests. Read Mode's columns, and a part of a page shown reduced, are rasterised as asked for, as before. Checked through the real page view and its picture store, headless: one texel per device pixel at 100, 110 and 137 % on 1x and 2x screens. The reporter's blurry screenshot was of the first version; **the fix has not been seen in the running app yet**. The rounding lives in the shared painter, so this follows it from outside: a shared-API gap remains (the page view could say what size it wants, or draw a screen-scale picture at its own size) | sharp document text | 80% | 2–4 (craft-libs page view) |
| Page text on screen (Linux, BSD) | Lightly hinted as FreeType's `hintslight` draws it (Firefox and other apps there): FreeType's autohinter puts baselines, x-heights and cap heights on whole pixels, nothing moves sideways, so lines break as before. Measured against headless Firefox (Arial, 21.27 px): the same rows of pixels and weight. Not yet: subpixel (LCD) edges; the interface text (egui) is hinted separately. macOS keeps its darkened unhinted text; Windows and exports are unchanged | sharp document text | 90% | 4–8 (subpixel edges) |
| Web and Draft Layout rendering | Very long pages render only visible full-resolution raster tiles instead of shrinking one huge texture to the GPU size limit; nearby tiles are cached for scrolling | sharp document text | 95% | — |
| Reading Mode | Existing Read Mode ribbon button opens a read-only, viewport-column layout with animated horizontal paging, transient width/text/spacing controls, heading navigation (Navigation pane) and resize anchoring; print/export layout unchanged. The arrows, Page Up/Down and Escape work straight after entering it; only whole columns show, centred, at any width, text size or window size; the columns end above the page-turn bar (#1772); Page color: None (white, the document's page color and page picture not shown), Sepia or Inverse (a dark page with light text), as Word's View › Page Color in Read Mode, starting at None and kept between Read Mode entries, documents and runs (`view.readPageColor`); ink, object drag previews and table drag arrows drawn over the pages follow it; Read Mode's View menu: Column Width and Page Color work, Layout is missing ([parity-checklist.md](parity-checklist.md), Read Mode 2/3) | reading-optimized view and navigation | 75% | 1–2 |
| Status bar (page x of y, words, language, view buttons, zoom slider) | ✅ (the page is the caret's while the caret is on screen, else the page at the top of the window, so scrolling updates it (#3880); the language is the caret's, by name; a click sets the proofing language, or opens Set Proofing Language… for any other). The count at the right is what it shows in Word: words (default), characters (with spaces) or characters (no spaces), chosen from a right-click menu on it or File › Options › Display (Status bar count, `ui.statusCount`), kept between runs; a selection shows "selected of total" as the Word Count dialog counts them (#2797) | ✅ | 90% | — |
@@ -129,11 +125,6 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text
| Date | Change | Summary |
|---|---|---|
| 2026-11-21 | minor | Page pictures are made exactly as many pixels each way as their place on screen once the view rests (the row "Page pictures at the screen's own scale" is now "…own size"): the first version, a pixel or two too large, was scaled by the shared painter and looked blurry. Also: stretched hinted text and synthetic bold are darkened correctly |
| 2026-11-20 | minor | Ported onto the shared page view and Options (after #7101): page pictures are rasterised at the screen's own scale where the view's zoom accounts for the side asked for, and subpixel text is drawn only there; the Screen text smoothing row is in the shared Options; the app no longer reads the system's text settings itself, so the row "Page text follows the system's text settings" became "Page text and the system's text settings" (not followed yet: craft-libs gap). New row "Page pictures at the screen's own scale" |
| 2026-11-19 | minor | Subpixel (LCD) page text: three rasters with the text a third of a pixel apart, one per colour stripe; File › Options › General › Screen text smoothing (`view.textSmoothing`). New row "Subpixel (LCD) page text"; run on macOS only |
| 2026-11-19 | minor | Page drawing can take the system's text settings; nothing reads them from the system yet (see the row "Page text and the system's text settings") |
| 2026-11-19 | minor | Page text on macOS and Windows: baselines on whole device pixels; macOS stem darkening widens outlines sideways only, in one fill, instead of stroking them all round. New row "Page text on screen (macOS, Windows)" |
| 2026-11-25 | trivial | Review › Comments › Delete is a split button: Delete, Delete All Comments in Document and Delete All Resolved Comments. The last deletes each resolved comment with its replies and keeps the open ones, in one undo step (#7818) |
| 2026-11-17 | trivial | Format Shape pane adds Line section (No line, Solid line with color, width, dash type, and cap type) and Layout & Properties section (size, rotation, and text box direction and vertical alignment), routes active canvas text-box edits to the member while leaving grouped text boxes disabled, rejects unknown outline `dash`/`cap` values, and applies Line and Layout edits across multi-shape selections (#5896) |
| 2026-11-15 | trivial | Paste: a copied table pasted with the caret in a table cell inserts its rows above (caret in the first column, same width) or overwrites the cells from the caret's, adding rows and columns, as Word's Paste does; `edit.pasteNestedTable` (Paste as Nested Table) nests it (#6739). Pasted cells take the destination's cell formatting (Word keeps the source's: not done). Left as before: copies with merged cells, pictures or ragged rows, merged destinations, a one-column destination, Track Changes, PasteAppendTable. Paste into selected cells overwrites from the top-left for plain grids, even when the copied table is wider than the selection (#6742). |
+3 -1
View File
@@ -312,7 +312,9 @@ fi
if [[ -z "${CROSS_TARGET:-}" ]]; then
"$STAGE/usr/bin/wordcraft-cli" --version
elif [[ -n "${EMULATOR:-}" ]]; then
"$EMULATOR" "$STAGE/usr/bin/wordcraft-cli" --version
# Set, so the CLI doesn't restart itself to apply it (malloc_tuning, #7914): under user-mode
# QEMU without binfmt the kernel can't run the restarted foreign binary, and glibc hands it to /bin/sh.
MALLOC_TRIM_THRESHOLD_=131072 "$EMULATOR" "$STAGE/usr/bin/wordcraft-cli" --version
fi
echo "==> done"
ls -lh "$DIST"
+23 -5
View File
@@ -21,7 +21,7 @@ usage: cargo xtask <command>
commands:
assets check that every icon/image/font/asset is attributed in ATTRIBUTION.md
layers enforce the crate dependency layering (docs/architecture.md, Layers)
wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call)
wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates and their wasm-safe test targets
test workspace tests (cargo nextest when installed, else cargo test), the interface
audit with its missing-translation report, then doctests
i18n-report the interface audit: fails on text that skips the catalog, and prints the
@@ -155,9 +155,18 @@ fn wasm_set() -> Result<Vec<String>, String> {
.collect())
}
/// One `cargo check` for the whole set: each crate is checked once, and
/// `--keep-going` still reports every failing crate. Features unify across the
/// set, so each crate is checked with the union of the features the set enables.
/// Crates in `wasm_set()` whose test targets still rely on native-only APIs or
/// dev-dependencies (`proptest` -> `wait-timeout`, `rayon`, `egui_kittest`, `load_system_fonts`).
const WASM_TEST_EXCLUDED: &[&str] = &["doc", "docx", "fonts", "formats", "ui-egui", "validate", "zotero"];
fn wasm_test_set(set: &[String]) -> Vec<String> {
set.iter().filter(|pkg| !WASM_TEST_EXCLUDED.contains(&layers::short_name(pkg))).cloned().collect()
}
/// Checks the wasm-safe crates for `wasm32-unknown-unknown` (first all library
/// targets together so features unify across the set, then `--tests` for the
/// subset whose test targets compile on wasm32). `--keep-going` still reports
/// every failing crate.
fn cmd_wasm() -> Result<(), String> {
let set = wasm_set()?;
if set.is_empty() {
@@ -169,7 +178,16 @@ fn cmd_wasm() -> Result<(), String> {
c.args(["-p", pkg]);
}
run(c, &format!("cargo check --target wasm32-unknown-unknown --keep-going -p {}", set.join(" -p ")))?;
println!("\nwasm32-unknown-unknown check: ok ({} crates: {})", set.len(), set.join(", "));
let test_set = wasm_test_set(&set);
if !test_set.is_empty() {
let mut t = cargo();
t.args(["check", "--target", "wasm32-unknown-unknown", "--tests", "--keep-going"]);
for pkg in &test_set {
t.args(["-p", pkg]);
}
run(t, &format!("cargo check --target wasm32-unknown-unknown --tests --keep-going -p {}", test_set.join(" -p ")))?;
}
println!("\nwasm32-unknown-unknown check: ok ({} crates, {} test targets: {})", set.len(), test_set.len(), set.join(", "));
Ok(())
}