Compare commits

...
Author SHA1 Message Date
Martin BallandClaude Opus 5.5 f8a42491c6 fix(search): command search shows each command's ribbon location (#7983)
Partial: the shortcut per row and the popup width are not done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-11-28 03:33:58 +00:00
Martin BallandClaude Opus 5.5 402fab32c8 fix(ribbon): Customize Ribbon and Quick Access panes share the width (#7981)
Tab names are no longer truncated and Up/Down no longer overlap the list.

Partial: the lists are still unframed (craft-libs List has no frame option).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-11-28 03:33:58 +00:00
Martin BallandClaude Opus 5.5 815e6f71c3 fix(keyboard): Customize Keyboard lists the ribbon tabs as Categories, in a dialog of set size (#7971)
Catalog commands carry their English ribbon location as a menu path; Categories are
the ribbon tabs (from ribbon::TABS), Contextual Tabs, Other and All Commands.

Partial: the Commands list still gets no room until the craft-libs fix (a7d6dcfcbb on
fix/7971-keyboard-categories-height) is synced to main and WordCraft repins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx
2026-11-28 03:33:58 +00:00
FredApps e9286c9487 Merge pull request #7183 from alehel/codex/7172-native-about
macOS: open the WordCraft About dialog from the application menu
2026-11-27 23:27:51 +01:00
FredApps b7057e56f6 Merge pull request #6800 from gmrmad1/fix/6265-print-preview-numeral
Print preview: refresh the cached layout and textures when numerals change (#6265)
2026-11-27 23:27:24 +01:00
FredApps 784e4c3c35 Merge pull request #6772 from RickiNano/fix/6767-arrow-stroke-inside-head
Shapes: a thick line's stroke ends inside its arrowheads (#6767)
2026-11-27 23:26:58 +01:00
FredApps 188be727b7 Merge pull request #5887 from batistalucasv/fix/5847-justified-tab-shrink
Layout: a justified line with a tab shrinks the spaces after its last tab (#5847)
2026-11-27 23:26:05 +01:00
FredApps 05dc3214ea Merge pull request #5870 from batistalucasv/fix/5842-compare-footnotes-endnotes
Compare: diff footnote and endnote content (#5842)
2026-11-27 23:25:36 +01:00
Dylan M. TaylorandFredApps 72ca96a27c ci: notify artcraft-services on release state changes (#7923)
* ci: notify artcraft-services on release state changes

* ci: pass only the dispatch token to the notify-services workflow

secrets: inherit hands the called workflow every repository secret, including
the signing credentials. The reusable workflow only reads
ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one.

---------

Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-27 09:17:48 -05:00
f83d554322 Pictures: an inserted or pasted picture fits the table cell, column or section it goes in (#5428) (#6903)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: D13GOOOO <106814760+D13GOOOO@users.noreply.github.com>
2026-11-27 10:07:07 +00:00
Martin BallandClaude Opus 5.5 0f4e80aedd #7165: Symbol drop-down has compact cells, and hover names the character (#7173)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 10:07:01 +00:00
Martin BallandClaude Opus 5.5 bab08b77e1 #7841: dark-mode interface text gets the lighter Gamma(0.8) curve again (#7867)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 10:06:54 +00:00
Martin BallandClaude Opus 5.5 2b407facd0 #7824: a disabled table menu button keeps its menu shut under read-only protection (#7871)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 10:02:47 +00:00
RickiNano b7819874c8 #6767: file-format parity names the ends that can't move their full inset 2026-11-27 06:42:48 +01:00
RickiNano 9cf6a33374 Merge remote-tracking branch 'origin/main' into fix/6767-arrow-stroke-inside-head
# Conflicts:
#	docs/file-format-parity.md
2026-11-27 06:42:37 +01:00
batistalucasv 29bb5a4f44 Merge upstream/main and resolve ROADMAP conflict (#5847) 2026-11-26 23:22:59 -03:00
batistalucasv aae46e1274 Merge upstream/main and resolve conflicts (#5842) 2026-11-26 23:07:51 -03:00
batistalucasv 9d78c95517 Layout: restrict tab space shrinking to left/default tabs (#5847) 2026-11-26 12:16:48 -03:00
batistalucasv 6ea92c6b93 Layout: restore justify module visibility and guard shrink_line_spaces (#5847) 2026-11-26 12:14:59 -03:00
batistalucasv 7905692c1f Layout: restore layout parity table formatting and strengthen compat-mode tests (#5847) 2026-11-26 12:14:59 -03:00
batistalucasv 7416d36aeb Layout: a justified line with a tab shrinks the spaces after its last tab (#5847) 2026-11-26 12:14:29 -03:00
alehelandClaude Opus 5.5 9e68fdb76a macOS: show the translated About label in the application menu (#7172)
mac_layout looks the label up as `About {app}`, which no WordCraft catalog
has, so the menu stayed English. Use the existing `About WordCraft` entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:03:54 +01:00
alehelandClaude Opus 5.5 d63de66920 Merge main into codex/7172-native-about
Resolve main.rs against the nightly session work and use
NativeMenu::sync_with, which replaced sync in the craft-libs rev on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:03:35 +01:00
batistalucasv bee50afd8f Compare: copy and remap media when adopting revised notes 2026-11-24 15:51:06 -03:00
batistalucasv a1a3b53f74 Compare: diff footnote and endnote content (#5842) 2026-11-24 14:59:46 -03:00
RickiNano 8ff9bdb1a1 #6767: a short straight line's lone arrowhead takes the room its other end doesn't need
An arrowed end moved at most half way along the line, even when the other
end had no arrowhead and stayed put, so on a straight line shorter than
twice the inset the stroke still stuck out of the head. The two ends of a
single straight segment now share its length in proportion to their
insets. Elbow and curved connectors keep the half-way limit.
2026-11-24 07:45:17 +01:00
Madhav Agarwal 694ac7810d Merge main into fix/6265-print-preview-numeral 2026-11-24 10:41:12 +05:30
RickiNano 1441c64970 Merge remote-tracking branch 'origin/main' into fix/6767-arrow-stroke-inside-head
# Conflicts:
#	docs/file-format-parity.md
2026-11-23 16:10:30 +01:00
alehel 3b94750945 ci: retrigger checks for #7183 2026-11-21 08:32:07 +01:00
alehel 376411a22b macOS: open the WordCraft About dialog from the application menu (#7172) 2026-11-21 07:26:10 +01:00
Martin Ball 932f5b4748 Merge branch 'main' into fix/6767-arrow-stroke-inside-head 2026-11-17 09:23:03 +01:00
Martin Ball 011a46c677 Merge branch 'main' into fix/6767-arrow-stroke-inside-head 2026-11-17 05:34:58 +01:00
Martin Ball 4239458948 Merge branch 'main' into fix/6767-arrow-stroke-inside-head 2026-11-17 03:02:09 +01:00
Madhav Agarwal b4219f9745 Print preview: refresh the cached layout and textures when numerals change (#6265) 2026-11-15 22:17:05 +05:30
RickiNanoandClaude Opus 5.5 37e5849e58 #6767: a thick line's stroke ends inside its arrowheads
A line's or connector's stroke ran all the way to each arrowhead's tip,
so a thick line's body and cap stuck out of the narrow end of the head.
Each arrowed end now stops where the head is as wide as the stroke, and a
square or round cap's reach further back. An end moves at most half way
to its neighbouring point, so elbow and curved connectors keep their
shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:25:02 +01:00
33 changed files with 3949 additions and 189 deletions
+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+4
View File
@@ -172,6 +172,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
- 2026-11-15: Get the Missing Fonts. A document opened from a file that is missing fonts their publisher gives away (Microsoft's Aptos family, the default in recent Word documents; Cascadia Code and Mono) brings up a box naming each font, the font drawn instead, the publisher's download page and how to install the download, with Don't show this again. `font.missing` reports the same page, so agents get it without the box. WordCraft links to the page only; it downloads and bundles nothing.
- 2026-10-30: Track Changes: a list item deleted whole, text and paragraph mark, shows its number as deleted text, in the deletion's colour and with its mark (struck through by default, or caret, #, bold, italic, underline), and hides it with No Markup or when Track Changes Options hide deletions (#4828). Readiness unchanged.
- 2026-11-03: A picture inserted or pasted in a table cell fits the cell, as in Word, instead of running out of it; in text columns it fits the column, in a section with other margins that section's width (#5428).
- 2026-11-09: Touchpad and mouse-wheel scroll speed settings (#6146): scales Wayland touchpad point input by default (4×) so two-finger scrolling matches desktop speed rather than crawling 1:1, and scales mouse wheel line distance; File › Options › Advanced › Scrolling; commands ui.scrollSpeed and ui.touchpadScrollSpeed.
- 2026-11-15: Layout: from Word 2013's layout (compatibility mode 15), balancing the columns before a continuous break keeps the last two, three or five lines of a paragraph that began on the page before together, keeps a two- or three-line paragraph that begins the last page whole, and holds a paragraph with keep lines together (or keep with next) whole in the first column when the strict rules fit. Synthetic tests also cover a footnote and a float (#6821); mode 14 splits them as before. Readiness estimates unchanged.
@@ -202,6 +203,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
- 2026-11-08: Layout: a turned inline picture whose file keeps no room for the turn (no or a zero `wp:effectExtent`, as other tools write) keeps its line to its frame and overhangs it, cut at the line's top and bottom, as Word does: the frame as it is in Word 2007 layout, with width and height exchanged from 45° to 135° and 225° to 315° in Word 2013+ layout. Such a file saves the same way. Pictures with the room recorded (Word's own files) still take their rotated bounds. Readiness unchanged.
- 2026-11-08: XML text and CDATA read with their line ends normalised (XML 1.0 §2.11): CR LF and a lone CR are one line feed, `&#13;` stays a CR, so a line break inside `w:t` in a file saved with Windows line ends is one space, not two (#5897); readiness estimates unchanged.
- 2026-11-08: Layout: contextual spacing drops the space after a table cell's last paragraph when that paragraph is in the Normal style, the end-of-cell mark counting as a Normal paragraph next to it; a last paragraph in another style keeps its space after. The rule is inferred from docxide-pdf's notes and its `cell-end-*` fixtures (`cell-end-text-context`, `cell-end-empty-context`); a Word comparison that tells it apart from the neighbouring paragraph's style is still open. Readiness unchanged.
- 2026-11-07: Justified paragraphs that start with a tab or contain tabs shrink the spaces after their last tab in Word 2013+ compatibility mode (mode 15), matching Word (#5847). Spaces before the line's last tab remain at their natural width.
- 2026-11-07: An in-line picture lowered past its own height (`w:position`) lowers its line as far, as in Word; all 156 synthetic lines measured for #3984 match Word (#5796). Exact spacing keeps the line's baseline.
- 2026-11-07: DOCX: a VML text box keeps its text direction: `mso-layout-flow-alt:bottom-to-top` reads as Rotate all text 270° whatever `layout-flow` says, and otherwise `layout-flow:vertical` (or `vertical-ideographic`) as 90°, so the turned text box in a compatibility-mode document's header is drawn turned, as in Word. (#5193)
- 2026-11-07: Newly opened secondary windows constrain their initial viewport dimensions to the monitor's usable area with margins for system panels, preventing new windows from exceeding screen width on high-DPI scaled displays (#5871).
@@ -993,6 +995,7 @@ MATH glyphs that reference the same construction now share its immutable variant
| 2026-11-12 | trivial | Validator: exclude every glossary-typed part from main traversal and fallback assignment; multiple content-type fallback candidates are ambiguous, with no selected anchor (#5875). Synthetic controls; no parity estimate changed. |
| 2026-11-12 | trivial | Validator: mixed Transitional/Strict entry points to the same target skip document checks with coverage in either order (#5875); distinct competing roots retain ambiguity treatment without evaluating the profile gate. No parity estimate changed. |
| 2026-11-12 | trivial | Validator: competing official role targets produce coverage and suppress dependent findings; both-order, repeated-target, malformed-source and owner-isolation controls (#5875). No parity estimate changed. |
| 2026-11-03 | trivial | Progress log: a picture inserted or pasted in a table cell fits the cell (#5428) |
| 2026-11-10 | trivial | Save As on Linux: the desktop portal's Save dialog reports the file type picked, updating the extension so saving as PDF writes a .pdf (#6180) |
| 2026-11-08 | trivial | Progress log: freestanding custom.dic dictionary file support in File › Options › Proofing (#5840) |
| 2026-11-08 | trivial | Progress log: XML line ends in text normalised (#5897) |
@@ -1528,6 +1531,7 @@ MATH glyphs that reference the same construction now share its immutable variant
| 2026-10-10 | major | Full re-measure; progress docs restructured (stage banner, two numbers, dimensions, languages, upcoming, progress log); parity tables moved to `docs/target-app-parity.md`, milestones to `docs/roadmap.md` |
| 2026-10-09 | minor | Recently landed: RTL, Ukrainian and Brazilian Portuguese |
| 2026-10-06 | major | First honest estimate: 88% catalog, ~62% real parity, alpha ~85% of the way |
| 2026-11-07 | trivial | Progress log: a justified line with a tab shrinks the spaces after it (#5847) |
> 2026-10-27 · Technical synchronization: existing Proofing pane hooks and regression tests follow the extracted engine/UI modules on main `436d444`; compact context menus remain upstream. New-SHA validation is pending; readiness unchanged.
> 2026-10-23 · cu20we review follow-up: Only paragraph-relative box floats use the pre-spacing origin. Line-relative floats and page/margin fallbacks in cells and text boxes keep the text-top origin. Synthetic controls compare zero and 24 pt space-before across all four box contexts. New cap conversion helpers and regression tests document their contracts; readiness estimates unchanged.
+1 -1
View File
@@ -57,7 +57,7 @@ winresource = "0.1"
[target.'cfg(target_os = "macos")'.dependencies]
# Finder double-click, Open With, Dock drops and `open -a WordCraft letter.docx` arrive as a
# kAEOpenDocuments Apple event, which winit doesn't handle (#27).
craft = { workspace = true, features = ["platform-apple-events"] }
craft = { workspace = true, features = ["platform-apple-events", "menu"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
+78 -4
View File
@@ -20,6 +20,8 @@ mod build_flavor;
mod control_server;
mod default_apps;
mod launch_profile;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod prefs;
mod process_identity;
@@ -54,6 +56,8 @@ use wordcraft_ui_egui::{Services, WordApp, prefs::Prefs};
/// exit, the print spool it waits for at exit and the control server it stops at exit.
struct App {
app: WordApp,
#[cfg(target_os = "macos")]
native_menu: Option<craft::menu::NativeMenu>,
/// The native panels behind the file service the app reaches through `Host::files`.
panels: FilePanels,
/// Feeds the files dropped on the window into the app's intake (`Services::intake`), the one
@@ -71,10 +75,22 @@ struct App {
}
impl App {
fn before_input(&mut self, ctx: &egui::Context) {
#[cfg(target_os = "macos")]
if let Some(menu) = &mut self.native_menu {
menu.poll(ctx);
}
embed::before_input(ctx, |out| self.app.frame_input(out));
}
/// One frame's logic: what the OS asked, the app, its file dialogs, then the root window's close
/// path. Without `frame` (a test over no window) the dialogs have no parent window.
fn logic_pass(&mut self, ctx: &egui::Context, frame: Option<&eframe::Frame>) {
self.app.logic(ctx);
#[cfg(target_os = "macos")]
if let Some(menu) = &mut self.native_menu {
native_menu::update(menu, &mut self.app, ctx);
}
self.panels.pump_with(self.app.dialog_host_mut(), frame);
// A quit that waits for nothing (the documents are answered for) closes the root window.
if self.app.quit_requested && !self.app.printing.busy() {
@@ -123,7 +139,7 @@ impl eframe::App for App {
if !files.is_empty() {
self.drops.dropped(files);
}
embed::before_input(ctx, |out| self.app.frame_input(out));
self.before_input(ctx);
}
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
self.logic_pass(ctx, Some(frame));
@@ -798,6 +814,8 @@ fn main() -> eframe::Result {
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,
@@ -1014,14 +1032,29 @@ mod smoke {
let drops = intake.sender();
let session = Session::new(wordcraft_doc::Document::new());
let app = WordApp::new(session, services(spool.clone(), intake, false)).with_host(host).with_settings(settings.clone());
Run { app: App { app, panels, drops, settings, spool, control: None, exit: None }, frames, ctx, sender }
Run {
app: App {
#[cfg(target_os = "macos")]
native_menu: None,
app,
panels,
drops,
settings,
spool,
control: None,
exit: None,
},
frames,
ctx,
sender,
}
}
/// One frame as eframe runs it: the input hook once, the logic once, the UI per pass.
/// Returns whether the frame sent a close command.
fn step(&mut self, events: Vec<egui::Event>) -> bool {
let Run { app, frames, ctx, .. } = self;
embed::before_input(ctx, |out| app.app.frame_input(out));
app.before_input(ctx);
let mut first = true;
frames.frame_without_input(events, |ui| {
if std::mem::take(&mut first) {
@@ -1044,7 +1077,7 @@ mod smoke {
/// cancelling the close.
fn close_request_is_let_through(&mut self) -> bool {
let Run { app, ctx, .. } = self;
embed::before_input(ctx, |out| app.app.frame_input(out));
app.before_input(ctx);
let mut input =
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 920.0))), ..Default::default() };
input.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { events: vec![egui::ViewportEvent::Close], ..Default::default() });
@@ -1118,6 +1151,47 @@ mod smoke {
assert!(closed, "Don't Save lets the close through");
}
}
/// A native menu selection reaches the hosted About dialog, including its credits, and Escape
/// dismisses it without changing the document. The fake backend supplies the OS selection.
#[cfg(target_os = "macos")]
#[test]
fn native_about_shows_credits_and_closes_with_escape() {
use craft::menu::{Backend, Dispatch, Event, ItemRole, MenuBar, NativeMenu};
struct Selection(Vec<Event>);
impl Backend for Selection {
fn sync(&mut self, _: &MenuBar) {}
fn attach(&mut self, _: Dispatch) {}
fn drain(&mut self) -> Vec<Event> {
std::mem::take(&mut self.0)
}
}
let mut run = Run::new();
run.app.app.start_screen();
run.settle();
let before = run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body);
let layout = native_menu::layout(&str::to_owned);
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap().command.clone();
run.app.native_menu = Some(NativeMenu::new(Box::new(Selection(vec![Event::Click(about)]))));
run.settle();
assert!(run.app.app.dialog_host_mut().shows_modal());
let tree = run.frames.tree();
for label in ["WordCraft", "Contributors", "Models", "Language data"] {
assert!(tree.keys().into_iter().any(|key| craft::ui::testing::access::name(&tree, key) == Some(label)), "About exposes {label}");
}
run.step(vec![egui::Event::Key {
key: egui::Key::Escape,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers::NONE,
}]);
run.settle();
assert!(run.app.app.dialog_host_mut().is_empty(), "Escape dismisses About");
assert_eq!(run.app.app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), before);
}
}
#[cfg(test)]
+64
View File
@@ -0,0 +1,64 @@
//! The macOS application menu uses the same About dialog as File › About.
use craft::menu::{CommandRef, Gate, Item, ItemRole, Layout, LayoutOptions, Menu, MenuBar, MenuRole, NativeMenu, mac_layout};
use serde_json::json;
use wordcraft_ui_egui::{WordApp, i18n};
const APP_NAME: &str = "WordCraft";
const ABOUT: &str = "About 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)]);
// `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 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);
layout
}
fn lang(app: &WordApp) -> i18n::Lang {
i18n::Lang::from_pref(&app.ui.language)
}
fn layout_in(lang: i18n::Lang) -> Layout {
layout(&|s| i18n::tr(lang, s).to_owned())
}
pub(super) fn install(ctx: &egui::Context, app: &WordApp) -> Option<NativeMenu> {
let menu = craft::menu::mac::install(ctx, &layout_in(lang(app)).bar);
if menu.is_none() {
log::warn!("the WordCraft application menu could not be installed");
}
menu
}
pub(super) fn update(menu: &mut NativeMenu, app: &mut WordApp, ctx: &egui::Context) {
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
for command in menu.take_clicks(ctx) {
if let Err(error) = app.run(&command.id, command.params) {
log::warn!("application menu: {error}");
}
}
menu.set_gate(Gate::default().modal(app.dialog_host_mut().shows_modal()));
let lang = lang(app);
for clash in menu.sync_with(lang.code(), || layout_in(lang)) {
log::warn!("application menu: {clash:?}");
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The catalogs translate "About WordCraft" and have no "About {app}" row.
#[test]
fn about_shows_the_catalogs_translation() {
let translate = |s: &'static str| if s == "About WordCraft" { "Über WordCraft".to_owned() } else { s.to_owned() };
let layout = layout(&translate);
let about = layout.bar.items().into_iter().find(|item| item.role == Some(ItemRole::About)).unwrap();
assert_eq!(about.label, "Über WordCraft");
}
}
+48 -27
View File
@@ -647,6 +647,20 @@ fn remap_media_block(b: &mut Block, map: &BTreeMap<String, String>) {
});
}
/// Remaps media references across `blocks` and any text box stories in `parts`.
fn remap_media_in(blocks: &mut [Block], parts: &mut BTreeMap<u32, Part>, map: &BTreeMap<String, String>) {
if map.is_empty() {
return;
}
for b in blocks {
remap_media_block(b, map);
}
for part in parts.values_mut() {
for b in &mut part.blocks {
remap_media_block(Arc::make_mut(b), map);
}
}
}
/// Visit `(index, item)` in forward (`!last`) or reverse (`last`) order, returning the first `Some`.
fn find_in_slice<T>(slice: &[T], last: bool, mut f: impl FnMut(usize, &T) -> Option<Path>) -> Option<Path> {
if last { slice.iter().enumerate().rev().find_map(|(i, x)| f(i, x)) } else { slice.iter().enumerate().find_map(|(i, x)| f(i, x)) }
@@ -688,7 +702,6 @@ fn trim_para(para: &Paragraph, from: usize, to: usize, clear_section: bool) -> P
}
p
}
impl Document {
/// Convert notes between footnotes and endnotes: footnotes (`foot`) become endnotes and
/// endnotes (`end`) footnotes, both at once to swap them. Each note's kind changes, as do its
@@ -1643,13 +1656,41 @@ impl Document {
Some(id)
}
/// The blocks of `frag`, a fragment of another document, with every text box given a new
/// story of its own here copied from the fragment's parts (as a paste does), to place them
/// in this document; a box the fragment has no story for keeps none.
/// Copies `media` into `self.media`, returning a remap for keys whose bytes differ from an
/// existing entry under the same key.
fn adopt_media(&mut self, media: &BTreeMap<String, Arc<Vec<u8>>>) -> BTreeMap<String, String> {
let mut media_remap = BTreeMap::new();
for (k, v) in media {
if let Some(existing) = self.media.get(k) {
if existing.as_slice() != v.as_slice() {
let ext = k.rsplit_once('.').map_or("png", |(_, ext)| ext);
let new_key = self.add_media((**v).clone(), ext);
media_remap.insert(k.clone(), new_key);
}
} else {
self.media.insert(k.clone(), v.clone());
}
}
media_remap
}
/// The blocks of `frag`, a fragment of another document, with its media copied (remapping
/// conflicting keys) and every text box given a new story of its own here copied from the
/// fragment's parts (as a paste does), to place them in this document; a box the fragment
/// has no story for keeps none.
pub fn adopt_fragment(&mut self, frag: &Fragment) -> Vec<Block> {
let media_remap = self.adopt_media(&frag.media);
let mut blocks = frag.blocks.clone();
let mut remapped_parts;
let parts = if media_remap.is_empty() {
&frag.parts
} else {
remapped_parts = frag.parts.clone();
remap_media_in(&mut blocks, &mut remapped_parts, &media_remap);
&remapped_parts
};
let mut budget = BoxBudget { local: false, ..BoxBudget::new() };
self.adopt_text_boxes(&mut blocks, &frag.parts, 0, &mut budget);
self.adopt_text_boxes(&mut blocks, parts, 0, &mut budget);
if budget.skipped > 0 {
log::warn!(
"{} text boxes are left empty; their stories are past what one copy brings ({MAX_PASTED_BOXES} stories, {MAX_PASTED_BOX_BYTES} bytes)",
@@ -1661,18 +1702,7 @@ impl Document {
/// Insert a fragment at `pos`; returns the position after the pasted content.
pub fn insert_fragment(&mut self, pos: &Pos, frag: &Fragment) -> Result<Pos> {
let mut media_remap = BTreeMap::new();
for (k, v) in &frag.media {
if let Some(existing) = self.media.get(k) {
if existing.as_slice() != v.as_slice() {
let ext = k.rsplit_once('.').map_or("png", |(_, ext)| ext);
let new_key = self.add_media((**v).clone(), ext);
media_remap.insert(k.clone(), new_key);
}
} else {
self.media.insert(k.clone(), v.clone());
}
}
let media_remap = self.adopt_media(&frag.media);
// Tables that would nest deeper than the limit here become their paragraphs (#1596).
let room = MAX_TABLE_DEPTH.saturating_sub(pos.path.depth());
let mut blocks = Vec::with_capacity(frag.blocks.len());
@@ -1689,16 +1719,7 @@ impl Document {
let table_para = table_style_para(self, pos);
let destination_shading = self.styles.resolve_para_in(&dest_para.props, table_para.as_ref()).shading;
let mut parts = frag.parts.clone();
if !media_remap.is_empty() {
for b in &mut blocks {
remap_media_block(b, &media_remap);
}
for part in parts.values_mut() {
for b in &mut part.blocks {
remap_media_block(Arc::make_mut(b), &media_remap);
}
}
}
remap_media_in(&mut blocks, &mut parts, &media_remap);
// Pasted text boxes get stories of their own (never shared with the copy's source).
let mut budget = BoxBudget::new();
self.adopt_text_boxes(&mut blocks, &parts, 0, &mut budget);
+55
View File
@@ -1192,6 +1192,61 @@ fn insert_fragment_remaps_conflicting_media_keys() {
assert_eq!(remapped, other_key);
}
#[test]
fn adopt_fragment_copies_and_remaps_conflicting_media_in_blocks_and_text_boxes() {
let mut d = doc(&["destination"]);
d.media.insert("image1.png".into(), Arc::new(vec![1, 1, 1]));
let mut frag_media = std::collections::BTreeMap::new();
frag_media.insert("image1.png".into(), Arc::new(vec![2, 2, 2]));
frag_media.insert("missing.png".into(), Arc::new(vec![3, 3, 3]));
let img = |key: &str| InlineObject::Image {
media: key.into(),
w: 10.0,
h: 10.0,
alt: String::new(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
let mut tb_para = Paragraph::with_text(&crate::para::OBJ.to_string(), CharProps::default());
tb_para.objects.push(img("image1.png"));
let mut parts = std::collections::BTreeMap::new();
parts.insert(7, Part { kind: PartKind::TextBox, blocks: vec![para_block(tb_para)], body: Default::default() });
let mut top_para = Paragraph::with_text(&format!("{}{}", crate::para::OBJ, crate::para::OBJ), CharProps::default());
top_para.objects.push(img("missing.png"));
top_para.objects.push(InlineObject::Shape {
kind: crate::para::ShapeKind::TextBox,
w: 40.0,
h: 40.0,
fill: None,
stroke: None,
stroke_width: 1.0,
float: Default::default(),
story: Some(7),
freeform: None,
effects: Default::default(),
extra: Default::default(),
});
let frag = Fragment { blocks: vec![Block::Para(top_para)], parts, media: frag_media };
let adopted = d.adopt_fragment(&frag);
assert_eq!(d.media["image1.png"].as_slice(), &[1, 1, 1]);
assert_eq!(d.media["missing.png"].as_slice(), &[3, 3, 3]);
let remapped_key = d.media.keys().find(|k| k.as_str() != "image1.png" && k.as_str() != "missing.png").unwrap();
assert_eq!(d.media[remapped_key].as_slice(), &[2, 2, 2]);
let adopted_para = adopted[0].as_para().unwrap();
assert!(matches!(&adopted_para.objects[0], InlineObject::Image { media, .. } if media == "missing.png"));
let adopted_tb_id = adopted_para.objects[1].text_box().unwrap();
let adopted_tb_para = d.parts[&adopted_tb_id].blocks[0].as_para().unwrap();
assert!(matches!(&adopted_tb_para.objects[0], InlineObject::Image { media, .. } if media == remapped_key));
}
/// #6788: splitting a paragraph after its first letters leaves the drop cap on the first
/// paragraph only; the new one (also when it is empty) is plain. A split at offset 0 is unchanged.
#[test]
+2 -2
View File
@@ -117,9 +117,9 @@ fn place_picture(s: &mut Session, bytes: Vec<u8>, width: Option<f32>, alt: &str)
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, TIFF, WMF, EMF)".into())),
},
};
// Fitted to the room where it goes: the table cell, the column, its own section (#5428).
let max_w = s.room_at(&s.sel.ordered().0);
let key = s.doc.add_media(bytes, ext);
// Fitted to the text width.
let max_w = s.doc.sections().first().map(|(_, sp)| sp.text_width()).unwrap_or(468.0);
let (mut w, mut h) = (natural_w, natural_h);
if let Some(want) = width {
// At most 22 inches, as for icons: a huge width made the height of a tall picture infinite.
+16 -3
View File
@@ -499,10 +499,23 @@ pub(crate) fn unlink_sections(blocks: &mut [Block]) {
/// lists and styles it refers to (renumbered so they can't collide with ours).
fn adopt(s: &mut Session, src: Document) -> Fragment {
let mut frag = s.doc.adopt(src);
// Pasted pictures fit our text width, like Insert › Pictures (layout keeps their size).
let max_w = crate::io::text_width(&s.doc);
// Pasted pictures fit the room where they go, like Insert › Pictures: the table cell, the
// column, its own section (#5428; layout keeps their size). Measured (a layout) only when
// the fragment holds an inline picture.
let mut has_picture = false;
for b in &mut frag.blocks {
crate::io::fit_block_pictures(b, max_w);
each_para(b, 0, &mut |p| {
has_picture |= p
.objects
.iter()
.any(|o| matches!(o, wordcraft_doc::InlineObject::Image { float, .. } if float.wrap == wordcraft_doc::para::Wrap::Inline));
});
}
if has_picture {
let max_w = s.room_at(&s.sel.ordered().0);
for b in &mut frag.blocks {
crate::io::fit_block_pictures(b, max_w);
}
}
unlink_sections(&mut frag.blocks);
frag
+1 -1
View File
@@ -21,7 +21,7 @@ mod typing;
pub use autocorrect::{AUTOCORRECT, AutoCap, AutoCorrectPrefs, lenient_autocorrect};
#[cfg(test)]
use compare::{Op, collapse_noise_matches, lcs_ops};
use compare::{Op, collapse_noise_matches, lcs_len, lcs_ops};
pub use specs::specs;
pub use typing::{INITIAL_CAPS_EXCEPTIONS, autocorrect, autocorrect_word, emphasis_autoformat, has_emphasis};
pub(crate) use typing::{is_turkic, lower_char, upper_char};
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+37
View File
@@ -204,6 +204,43 @@ impl Session {
Arc::new(wordcraft_layout::layout(doc, &mut LayoutCache::new(), &opts))
}
/// How wide a picture put in at `pos` may be, as Word fits an inserted or pasted picture
/// (#5428): the room its paragraph's lines have (the width available to its widest laid-out line,
/// so the paragraph's indents are already taken out; inside a table cell, the innermost cell's
/// text area, nested tables included; a turned cell isn't measured and falls back to the
/// column width), never wider than the column it is in, of its own section. The narrowest
/// section's text width ([`crate::io::text_width`]) when `pos` isn't laid out. It is measured on the pages, whatever the view: Web Layout and Read Mode reflow the
/// text to the window, and a picture put in there keeps the size it gets in the document.
pub(crate) fn room_at(&mut self, pos: &wordcraft_doc::Pos) -> f32 {
let first = crate::io::text_width(&self.doc);
let l =
if !self.view.read_mode && self.view.mode == ViewMode::Print { self.layout() } else { self.output_layout_of(&self.doc, false, false) };
let Some((caret, page)) = l.caret_on(pos, self.page_hint).and_then(|c| Some((c, l.pages.get(c.page)?))) else { return first };
// A page can hold several continuous sections: the body's own comes from the position.
let at = match (pos.story, pos.path.0.first()) {
(StoryRef::Body, Some(b)) => self.doc.section_index_of(*b as usize),
_ => page.section,
};
let section = self.doc.sections().get(at).map(|(_, sp)| (*sp).clone());
let column = match (&section, pos.story) {
(Some(sp), StoryRef::Body) => {
let boxes = sp.column_boxes();
let x = caret.x - page.body.x;
boxes.iter().find(|(cx, w)| x >= cx - 0.5 && x <= cx + w + 0.5).map_or_else(|| sp.text_width(), |(_, w)| *w)
}
(Some(sp), StoryRef::Part(_)) => sp.text_width(),
(None, _) => first,
};
let lines = wordcraft_layout::hit::page_lines(page, pos.story)
.iter()
.filter(|h| *h.path == pos.path)
.map(|h| h.right - h.left)
.filter(|w| w.is_finite())
.fold(0.0f32, f32::max);
let room = if lines >= 1.0 { lines.min(column) } else { column };
if room.is_finite() && room >= 1.0 { room } else { first }
}
/// Invalidate the cached layout (fonts changed etc.).
pub fn relayout(&mut self) {
self.layout = Default::default();
+137
View File
@@ -14943,6 +14943,143 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
}
/// #5428: an inserted or pasted picture fits where it goes, as in Word: a table cell's width
/// (a nested cell's too), a column's, not the whole page's text width.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_inserted_or_pasted_picture_fits_where_it_goes() {
let png = |w: u32, h: u32| {
let mut b = Vec::new();
image::RgbaImage::from_pixel(w, h, image::Rgba([30, 90, 200, 255]))
.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)
.unwrap();
cmd::insert::base64_encode(&b)
};
let widths = |s: &Session| {
let mut v = Vec::new();
for b in s.doc.body.iter() {
let mut b = (**b).clone();
cmd::paste::each_para(&mut b, 0, &mut |p| {
for o in &p.objects {
if let wordcraft_doc::InlineObject::Image { w, h, .. } = o {
v.push((*w, *h));
}
}
});
}
v
};
let text_w = crate::io::text_width(&Session::new(wordcraft_doc::Document::new()).doc);
let in_cell = |cols: u32| {
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "insert.table", json!({"rows": 1, "cols": cols}));
assert!(s.sel.focus.path.depth() > 0, "the caret is in the first cell");
s
};
// Insert › Pictures and Paste in a cell of a three-column table.
let cell = text_w / 3.0;
let mut s = in_cell(3);
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
let mut p = in_cell(3);
let html = format!("<p><img src=\"data:image/png;base64,{}\"></p>", png(1000, 200));
run(&mut p, "edit.pasteSpecial", json!({"as": "html", "html": html}));
for (how, s) in [("inserted", &s), ("pasted", &p)] {
let got = widths(s);
let [(w, h)] = got.as_slice() else { panic!("{how}: {got:?}") };
assert!(*w <= cell && *w > cell - 20.0, "{how}: {w} fits the cell's text area ({cell} less its margins)");
assert!((h * 5.0 - w).abs() < 0.1, "{how}: proportions kept: {w} × {h}");
}
// A table in that cell: its own narrower cell.
let mut s = in_cell(2);
let outer = s.room_at(&s.sel.focus.clone());
// (A table inserted in a cell takes the page's text width for its columns, so four columns
// make its cells narrower than the outer one.)
run(&mut s, "insert.table", json!({"rows": 1, "cols": 4}));
assert!(s.sel.focus.path.depth() > 1, "the caret is in the nested cell");
let nested = s.room_at(&s.sel.focus.clone());
assert!(nested < outer - 50.0, "the nested cell ({nested}) is narrower than the outer one ({outer})");
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
let w = widths(&s)[0].0;
assert!((w - nested).abs() < 0.5 && w <= text_w / 4.0, "{w} fits the nested cell ({nested})");
// Two text columns: one column's width.
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "layout.columns", json!({"count": 2}));
let column = s.doc.sections()[0].1.column_boxes()[0].1;
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
let w = widths(&s)[0].0;
assert!((w - column).abs() < 0.5, "{w} fits the column ({column})");
// Body text keeps the full text width.
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
assert!((widths(&s)[0].0 - text_w).abs() < 0.5);
}
/// #5428 review: a page can hold several continuous sections; a picture goes by the section of the
/// position, not of the page's first one (two columns, then a continuous single-column section).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_picture_after_a_continuous_break_fits_its_own_section() {
let sect = |cols: &str, kind: &str| format!(r#"<w:sectPr>{kind}<w:pgSz w:w="11906" w:h="16838"/><w:cols {cols} w:space="708"/></w:sectPr>"#);
let body = [
"<w:p><w:r><w:t>one</w:t></w:r></w:p>".to_string(),
format!("<w:p><w:pPr>{}</w:pPr></w:p>", sect(r#"w:num="2""#, "")),
"<w:p><w:r><w:t>two</w:t></w:r></w:p>".to_string(),
sect("", r#"<w:type w:val="continuous"/>"#),
]
.concat();
let mut s = Session::new(wordcraft_docx::read(&docx_with_styles(&body, "")).unwrap());
let last = s.doc.body.len() - 1;
s.sel = crate::Selection::caret(Pos::body(last, 0));
let room = s.room_at(&s.sel.focus.clone());
let column = s.doc.sections()[0].1.column_boxes()[0].1;
assert!(room > column + 50.0, "{room} is the single column's width, not the earlier two columns' ({column})");
}
/// #5428 review: Web Layout and Read Mode reflow the text to the window, but a picture put in
/// there is fitted to the page's text width, as in Print Layout: the size stays in the document.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_picture_put_in_in_web_layout_fits_the_page_not_the_window() {
let png = |w: u32, h: u32| {
let mut b = Vec::new();
image::RgbaImage::from_pixel(w, h, image::Rgba([30, 90, 200, 255]))
.write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)
.unwrap();
cmd::insert::base64_encode(&b)
};
let width = |s: &Session| {
s.doc.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).find_map(|o| match o {
wordcraft_doc::InlineObject::Image { w, .. } => Some(*w),
_ => None,
})
};
let text_w = crate::io::text_width(&Session::new(wordcraft_doc::Document::new()).doc);
let web = || {
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "view.webLayout", json!({}));
// A narrow window, or a high zoom.
s.view.web_width = 350.0;
assert!(s.layout().pages[0].w < text_w, "the window is narrower than the page's text");
s
};
let mut s = web();
run(&mut s, "insert.picture", json!({"data": png(1000, 200)}));
let mut p = web();
let html = format!("<p><img src=\"data:image/png;base64,{}\"></p>", png(1000, 200));
run(&mut p, "edit.pasteSpecial", json!({"as": "html", "html": html}));
for (how, s) in [("inserted", &s), ("pasted", &p)] {
let w = width(s).unwrap();
assert!((w - text_w).abs() < 0.5, "{how}: {w} fits the page's text width ({text_w})");
}
// Read Mode's narrow pages don't set it either.
let mut s = Session::new(wordcraft_doc::Document::new());
run(&mut s, "text.insert", json!({"text": "Read"}));
run(&mut s, "view.readMode", json!({}));
s.view.read_width = 240.0;
let room = s.room_at(&s.sel.focus.clone());
assert!((room - text_w).abs() < 0.5, "Read Mode: {room} is the page's text width ({text_w})");
}
/// A picture an OpenDocument file gives no size is shown at its own, fitted to the text as other
/// formats' are; one with a stated size keeps it, in line too.
#[test]
+80 -15
View File
@@ -1,7 +1,7 @@
use super::options::DisplayOptions;
use super::paint::{Paint, paint_for};
use super::{BezPath, Document, Draw, FaceRef, Graphic, GraphicItem, GraphicKind, InlineObject, PathSeg, Rect, Rgb, ShapeKind, Spin, TextAlign};
use wordcraft_doc::connector::ArrowStyle;
use wordcraft_doc::connector::{ArrowStyle, LineCap};
/// The draws of a chart or diagram's items inside `rect` (page coordinates). The items were built
/// for the size `g.w` × `g.h` (0: `rect`'s own size), so they are scaled to `rect`; strokes and text
@@ -294,9 +294,14 @@ fn line_draws(
out: &mut Vec<Draw>,
) {
use wordcraft_doc::connector::{connector_segs, end_direction};
let start_dir = end_direction(kind, rect.w, rect.h, false);
let end_dir = end_direction(kind, rect.w, rect.h, true);
// An arrowed end stops inside its head, which the stroke would otherwise stick out of.
let inset = |on: bool, style| if on && stroke.is_some() { arrow_inset(stroke_width, style, extra.cap) } else { 0.0 };
let ends = [(inset(extra.arrow_start, extra.start_style), start_dir), (inset(extra.arrow_end, extra.end_style), end_dir)];
match connector_segs(kind, rect.w, rect.h) {
Some(segs) => {
let segs = segs
let mut segs: Vec<PathSeg> = segs
.into_iter()
.map(|s| match s {
PathSeg::Move(x, y) => PathSeg::Move(rect.x + x, rect.y + y),
@@ -305,32 +310,92 @@ fn line_draws(
PathSeg::Close => PathSeg::Close,
})
.collect();
shorten_ends(&mut segs, ends);
let width = path_stroke_width(stroke_width);
out.push(Draw::Path { segs, fill: None, stroke, stroke_width: width, dash: extra.dash.pattern(width), cap: extra.cap });
}
None => out.push(Draw::Shape {
rect,
kind,
fill: None,
stroke,
stroke_width,
effects,
corner: None,
dash: extra.dash.pattern(stroke_width),
cap: extra.cap,
}),
None => {
// A line's frame is its diagonal, top left to bottom right: shortened, it stays one.
let mut segs = [PathSeg::Move(rect.x, rect.y), PathSeg::Line(rect.right(), rect.bottom())];
shorten_ends(&mut segs, ends);
let line = match segs {
[PathSeg::Move(x0, y0), PathSeg::Line(x1, y1)] => Rect::new(x0.min(x1), y0.min(y1), (x1 - x0).abs(), (y1 - y0).abs()),
_ => rect,
};
out.push(Draw::Shape {
rect: line,
kind,
fill: None,
stroke,
stroke_width,
effects,
corner: None,
dash: extra.dash.pattern(stroke_width),
cap: extra.cap,
});
}
}
let Some(color) = stroke else { return };
// A line runs from the top-left corner to the bottom-right, as it is drawn (DrawingML's
// `line`), and so do connectors; flips are the frame's turn.
let (start, end) = ((rect.x, rect.y), (rect.right(), rect.bottom()));
for (on, tip, at_end, style) in [(extra.arrow_start, start, false, extra.start_style), (extra.arrow_end, end, true, extra.end_style)] {
for (on, tip, dir, style) in [(extra.arrow_start, start, start_dir, extra.start_style), (extra.arrow_end, end, end_dir, extra.end_style)] {
if on {
out.push(arrowhead(tip, end_direction(kind, rect.w, rect.h, at_end), stroke_width, style, color));
out.push(arrowhead(tip, dir, stroke_width, style, color));
}
}
}
/// How far short of an arrowhead's tip a line `stroke_width` wide with `cap` ends stops, so that
/// none of its stroke shows outside the head (#6767): where the head is as wide as the stroke,
/// plus what the cap reaches past the end. A head is at least twice as wide as its line, so this
/// is inside the head; never past its base.
fn arrow_inset(stroke_width: f32, style: ArrowStyle, cap: LineCap) -> f32 {
let width = path_stroke_width(stroke_width);
let (len, wide) = style.dims(stroke_width);
let reach = if cap == LineCap::Flat { 0.0 } else { width / 2.0 };
(len * width / wide.max(f32::EPSILON) + reach).clamp(0.0, len)
}
/// Draw the path `segs` (a line's or connector's, from its start to its end) short of its ends:
/// each end by its distance, back against its unit direction (where its arrowhead points). An end
/// moves at most half way to its neighbouring point, so the path keeps its shape, and a curve its
/// direction at the end. The two ends of a single straight segment share its length in proportion
/// to their distances instead, so an end without an arrowhead leaves its share to the other.
fn shorten_ends(segs: &mut [PathSeg], [(start, start_dir), (end, end_dir)]: [(f32, (f32, f32)); 2]) {
let distance = |by: f32| if by.is_finite() { by.max(0.0) } else { 0.0 };
let (start, end) = (distance(start), distance(end));
let share = |by: f32| match segs {
[PathSeg::Move(..), PathSeg::Line(..)] => by / (start + end).max(f32::EPSILON),
_ => 0.5,
};
let (start_share, end_share) = (share(start), share(end));
let pull = |(x, y): (f32, f32), toward: Option<(f32, f32)>, by: f32, share: f32, (dx, dy): (f32, f32)| {
let room = toward.map_or(0.0, |(tx, ty)| (tx - x).hypot(ty - y) * share);
let by = if room.is_finite() { by.min(room) } else { 0.0 };
(x - dx * by, y - dy * by)
};
// The points next to each end, before either moves.
let after_first = match segs.get(1) {
Some(PathSeg::Line(x, y) | PathSeg::Cubic(x, y, ..)) => Some((*x, *y)),
_ => None,
};
let before_last = match segs.len().checked_sub(1).map(|i| segs.split_at(i)) {
Some((_, [PathSeg::Cubic(_, _, x, y, ..)])) => Some((*x, *y)),
Some((head, [PathSeg::Line(..)])) => match head.last() {
Some(PathSeg::Move(x, y) | PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y)) => Some((*x, *y)),
_ => None,
},
_ => None,
};
if let Some(PathSeg::Move(x, y)) = segs.first_mut() {
(*x, *y) = pull((*x, *y), after_first, start, start_share, start_dir);
}
if let Some(PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y)) = segs.last_mut() {
(*x, *y) = pull((*x, *y), before_last, end, end_share, end_dir);
}
}
pub fn seg_path(segs: &[PathSeg]) -> BezPath {
let mut p = BezPath::new();
for s in segs {
+56
View File
@@ -488,4 +488,60 @@ mod tests {
}
assert_eq!(lookup_family(&d, "No Such Roman Font"), MISSING_ROMAN_FONT);
}
/// #5847: shrink_line_spaces is a no-op when there are no spaces after the line's last tab,
/// guarding against division by zero, negative room, or shifting pre-tab clusters.
#[test]
fn shrink_line_spaces_with_no_spaces_after_last_tab_is_noop() {
crate::test_fonts();
let chr = CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let mut d = Document::new();
d.settings.compat_mode = 15;
let fields = FieldCtx::default();
let env = ParaEnv {
doc: &d,
fields: &fields,
width: 468.0,
label: None,
show_hidden: false,
hide_deleted: Default::default(),
table: None,
proofing: None,
typing_word: None,
field_codes: false,
grid: Grid::default(),
exclusions: &[],
eq_number: 0,
numeral: Default::default(),
read_line_spacing: None,
fit_objects: false,
fitted: &[],
joined: false,
};
let mut p = Paragraph::with_text("n n n n\tWordWithoutSpaces", chr);
p.props = ParaProps {
align: Some(Align::Justify),
tabs: Some(vec![TabStop { pos: 150.0, align: TabAlign::Left, leader: Default::default() }]),
..Default::default()
};
let mut pl = layout_para(&p, &env);
let mark_style = pl.clusters[0].style;
break_lines(&mut pl, &env, mark_style, None);
let c0 = pl.lines[0].c0;
let c1 = pl.lines[0].c1;
let last_tab = (c0..c1).rev().find(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Tab)).unwrap();
let from = last_tab + 1;
let spaces_after = (from..c1).filter(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Space)).count();
assert_eq!(spaces_after, 0);
let orig_xs = pl.lines[0].xs.clone();
let content_end = *orig_xs.last().unwrap();
for slack in [-20.0, 0.0, f32::NEG_INFINITY] {
let mut xs = orig_xs.clone();
justify::shrink_line_spaces(&pl, &mut xs, (c0, from), c1, content_end, slack);
assert_eq!(xs, orig_xs, "slack {slack} with 0 post-tab spaces must not shift any cluster");
}
}
}
+12 -6
View File
@@ -22,23 +22,29 @@ pub(super) fn space_room(spaces: f32, word: f32) -> f32 {
(spaces * MAX_SPACE_SHRINK).min(word.max(0.0) * MAX_WORD_OVERRUN)
}
/// Take `-slack` (an overflow) out of the line's inner spaces, in proportion to their widths and
/// never more than [`MAX_SPACE_SHRINK`] of them. Trailing spaces hang and are left alone.
pub(super) fn shrink_line_spaces(pl: &ParaLayout, xs: &mut [f32], c0: usize, c1: usize, content_end: f32, slack: f32) {
let spaces: Vec<(usize, f32)> = (c0..c1)
/// Take `-slack` (an overflow) out of the line's inner spaces from `from` on (after the line's last
/// left/default tab), in proportion to their widths and never more than [`MAX_SPACE_SHRINK`] of them.
/// Trailing spaces hang and are left alone.
///
/// `c0` is the first cluster on the line, and `from` is where space shrinking begins (the cluster
/// following the line's last tab, or `c0` when there are no tabs on the line). `c1` is the end of
/// the line's cluster range.
pub(super) fn shrink_line_spaces(pl: &ParaLayout, xs: &mut [f32], (c0, from): (usize, usize), c1: usize, content_end: f32, slack: f32) {
let from = from.max(c0);
let spaces: Vec<(usize, f32)> = (from..c1)
.filter_map(|k| {
let c = pl.clusters.get(k).filter(|c| c.kind == ClKind::Space)?;
(xs.get(k - c0).copied().unwrap_or(f32::MAX) < content_end - 0.01).then_some((k, c.adv))
})
.collect();
let total: f32 = spaces.iter().map(|s| s.1).sum();
if total <= 0.0 || !slack.is_finite() {
if !total.is_finite() || total <= 0.0 || !slack.is_finite() {
return;
}
let ratio = (-slack / total).clamp(0.0, MAX_SPACE_SHRINK);
let mut take = 0.0;
let mut next = spaces.iter().peekable();
for k in c0..c1 {
for k in from..c1 {
if let Some(v) = xs.get_mut(k - c0) {
*v -= take;
}
+22 -9
View File
@@ -25,7 +25,7 @@ struct Breaker<'e> {
/// Where default tab stops are counted from (see [`next_tab`]).
tab_origin: f32,
/// Word 2013+ (compatibility mode 15) fits more text on a justified line by shrinking its
/// spaces (`space_room`); never on lines with tabs.
/// spaces (`space_room`); on a line with tabs, only the spaces after a final left/default tab.
shrink_spaces: bool,
/// Word 2003's indent rules (`w:doNotSuppressIndentation`) before Word 2013's layout, for an
/// unnumbered paragraph: a row starts right after a floating object before the indent.
@@ -100,9 +100,13 @@ struct Scan {
pending_tab: Option<(usize, TabStop, f32)>,
/// The text after a pending decimal tab looked at so far for its '.'.
decimal: Option<DecimalScan>,
/// The width of the spaces so far on this line.
/// The width of the spaces so far on this line, after its last tab.
space_w: f32,
has_tab: bool,
/// Whether spaces after the last tab so far may shrink (true initially and after left/default
/// tabs; false after right, center, or decimal tabs whose anchors use unshrunk widths).
shrink_tab: bool,
/// Tab cluster indices on this line whose alignment is not `TabAlign::Left`.
non_left_tabs: Vec<usize>,
/// The first word doesn't fit a span narrowed by a floating object: it moves on whole.
skip: bool,
}
@@ -306,7 +310,8 @@ impl<'e> Breaker<'e> {
pending_tab: None,
decimal: None,
space_w: 0.0,
has_tab: false,
shrink_tab: true,
non_left_tabs: Vec::new(),
skip: false,
}
}
@@ -603,10 +608,12 @@ impl<'e> Breaker<'e> {
// A line ending in a manual line break is stretched too, unless `doNotExpandShiftReturn` says not to.
let stretch_end = sc.end == LineEnd::Wrap || (sc.end == LineEnd::LineBreak && self.expand_break);
let justify = display.is_none() && ((align == Align::Justify && stretch_end) || align == Align::Distribute);
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too.
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && last_tab.is_none();
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too,
// unless its last tab is a non-left tab whose anchor was resolved with unshrunk widths.
let can_shrink_tab = last_tab.is_none_or(|k| !sc.non_left_tabs.contains(&k));
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && can_shrink_tab;
if shrink {
shrink_line_spaces(pl, &mut sc.xs, c0, c1, content_end, slack);
shrink_line_spaces(pl, &mut sc.xs, (c0, align_from), c1, content_end, slack);
} else if justify && slack > 0.0 {
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), align == Align::Distribute);
}
@@ -834,7 +841,8 @@ impl Scan {
/// A tab: its stop, and the room to it. True when the line ends before it.
fn tab(&mut self, bk: &mut Breaker, pl: &mut ParaLayout) -> bool {
let j = self.j;
self.has_tab = true;
// Only the spaces after a line's last tab shrink (measured in Word for Mac).
self.space_w = 0.0;
resolve_tab(pl, &mut self.pending_tab, &mut self.xs, self.c0, self.x, &mut self.x);
let rp = &bk.rp;
let ptab = pl.ptabs.iter().find(|t| t.0 == j).map(|&(_, a, b, l)| ptab_stop(a, b, l, bk.width, (rp.indent_left, rp.indent_right)));
@@ -877,6 +885,10 @@ impl Scan {
/// decimal tab).
fn place_tab(&mut self, pl: &mut ParaLayout, stop: TabStop) {
let j = self.j;
self.shrink_tab = stop.align == TabAlign::Left;
if !self.shrink_tab {
self.non_left_tabs.push(j);
}
match stop.align {
TabAlign::Left | TabAlign::Bar | TabAlign::Clear => {
let w = (stop.pos - self.x).max(0.0);
@@ -917,7 +929,7 @@ impl Scan {
// each segment's font, glyphs and position for painting.
let advance = pl.atomic_advance(j);
let absorbs = self.absorbs(pl, advance);
let shrink = if bk.shrink_spaces && !self.has_tab {
let shrink = if bk.shrink_spaces && self.shrink_tab {
space_room(self.space_w, self.x + advance - pl.auto_space_after(j) - self.word_from)
} else {
0.0
@@ -1057,6 +1069,7 @@ impl Scan {
self.last_break = Some(tj - 1);
self.pending_tab = None;
self.leaders.retain(|(k, _)| *k < tj);
self.non_left_tabs.retain(|&k| k < tj);
}
}
+560 -1
View File
@@ -4738,7 +4738,147 @@ fn a_lines_arrowheads_sit_at_its_ends() {
_ => None,
})
.collect();
assert_eq!(tips, [(rect.x, rect.y), (rect.right(), rect.bottom())]);
let [(x0, y0), (x1, y1)] = tips[..] else { panic!("two arrowheads: {tips:?}") };
assert!((x1 - x0 - 60.0).abs() < 0.01 && (y1 - y0 - 40.0).abs() < 0.01, "tips at the frame's corners: {tips:?}");
// The line, drawn short of its arrowed ends (#6767), runs along the same diagonal.
assert!(rect.x > x0 && rect.y > y0 && rect.right() < x1 && rect.bottom() < y1, "{rect:?} between {tips:?}");
assert!(((rect.x - x0) / 60.0 - (rect.y - y0) / 40.0).abs() < 0.001, "{rect:?} on the diagonal from {tips:?}");
assert!(((x1 - rect.right()) / 60.0 - (y1 - rect.bottom()) / 40.0).abs() < 0.001, "{rect:?} on the diagonal to {tips:?}");
}
#[test]
fn a_thick_lines_stroke_ends_inside_its_arrowheads() {
// #6767: the stroke stopped at each arrowhead's tip, so a thick line's body and cap stuck out
// of the narrow head. Each arrowed end now stops where the head is as wide as the stroke (and
// its cap's reach before that), for lines and every connector.
use wordcraft_doc::connector::{LineCap, ShapeExtra};
use wordcraft_doc::para::{Float, ShapeKind};
use wordcraft_doc::props::Rgb;
let width = 6.0;
let kinds = [ShapeKind::Line, ShapeKind::StraightConnector, ShapeKind::ElbowConnector, ShapeKind::CurvedConnector];
for kind in kinds {
for cap in [LineCap::Flat, LineCap::Square, LineCap::Round] {
let shape = InlineObject::Shape {
kind,
w: 120.0,
h: 60.0,
fill: None,
stroke: Some(Rgb::BLACK),
stroke_width: width,
float: Float::default(),
story: None,
freeform: None,
effects: Default::default(),
extra: ShapeExtra { arrow_start: true, arrow_end: true, cap, ..Default::default() },
};
let (ends, heads, draws) = line_ends_and_heads(shape);
assert_eq!((ends.len(), heads.len()), (2, 2), "{kind:?} {cap:?}: {draws:?}");
for (end, head) in ends.iter().zip(&heads) {
for corner in stroke_end_corners(*end, *head, width, cap) {
assert!(in_triangle(corner, *head), "{kind:?} {cap:?}: stroke corner {corner:?} outside the head {head:?}");
}
}
}
}
}
#[test]
fn a_short_lines_lone_arrowhead_takes_the_room_its_other_end_does_not_need() {
// #6767: an arrowed end moved at most half way along a straight line, even when the other end
// had no arrowhead and stayed put, so a short thick line's stroke still stuck out of its head.
use wordcraft_doc::connector::{LineCap, ShapeExtra};
use wordcraft_doc::para::{Float, ShapeKind};
use wordcraft_doc::props::Rgb;
let width = 6.0;
// Each is shorter than twice its inset (6 pt flat, 9 pt with the cap's reach) but no shorter
// than one inset, so the head can cover the stroke: 8 pt and 10 pt diagonals.
for (cap, (w, h)) in [(LineCap::Flat, (6.4, 4.8)), (LineCap::Square, (8.0, 6.0)), (LineCap::Round, (8.0, 6.0))] {
for kind in [ShapeKind::Line, ShapeKind::StraightConnector] {
for at_start in [true, false] {
let shape = InlineObject::Shape {
kind,
w,
h,
fill: None,
stroke: Some(Rgb::BLACK),
stroke_width: width,
float: Float::default(),
story: None,
freeform: None,
effects: Default::default(),
extra: ShapeExtra { arrow_start: at_start, arrow_end: !at_start, cap, ..Default::default() },
};
let (ends, heads, draws) = line_ends_and_heads(shape);
let (&[start, end], &[head]) = (&ends[..], &heads[..]) else { panic!("{kind:?} {cap:?}: {draws:?}") };
let tip = head[0];
let (near, far) = if at_start { (start, end) } else { (end, start) };
// The end without an arrowhead stays where it was.
let other = if at_start { (tip.0 + w, tip.1 + h) } else { (tip.0 - w, tip.1 - h) };
assert!((far.0 - other.0).abs() < 0.01 && (far.1 - other.1).abs() < 0.01, "{kind:?} {cap:?}: {far:?} moved from {other:?}");
for corner in stroke_end_corners(near, head, width, cap) {
assert!(in_triangle(corner, head), "{kind:?} {cap:?} start={at_start}: stroke corner {corner:?} outside the head {head:?}");
}
}
}
}
}
/// The ends of the stroked line or connector `shape` draws, from its start to its end, its
/// arrowheads (each tip first), and all its draws.
fn line_ends_and_heads(shape: InlineObject) -> (Vec<(f32, f32)>, Vec<[(f32, f32); 3]>, Vec<display::Draw>) {
use wordcraft_doc::graphic::PathSeg;
use wordcraft_doc::para::ShapeKind;
let mut doc = Document::from_text("Scan");
doc.insert_object(&Pos::body(0, 0), shape, &Default::default()).unwrap();
let draws = flat(display::page_display(&doc, &lay(&doc).pages[0], &Default::default()));
let mut ends = Vec::new();
let mut heads = Vec::new();
for d in &draws {
match d {
display::Draw::Shape { rect, kind: ShapeKind::Line, .. } => ends.extend([(rect.x, rect.y), (rect.right(), rect.bottom())]),
display::Draw::Path { fill: None, stroke: Some(_), segs, .. } => {
let point = |s: &PathSeg| match *s {
PathSeg::Move(x, y) | PathSeg::Line(x, y) | PathSeg::Cubic(.., x, y) => Some((x, y)),
PathSeg::Close => None,
};
ends.extend(segs.first().and_then(point));
ends.extend(segs.last().and_then(point));
}
display::Draw::Path { fill: Some(_), segs, .. } => {
if let [PathSeg::Move(tx, ty), PathSeg::Line(ax, ay), PathSeg::Line(bx, by), PathSeg::Close] = segs[..] {
heads.push([(tx, ty), (ax, ay), (bx, by)]);
}
}
_ => {}
}
}
(ends, heads, draws)
}
/// The corners of a `width` stroke's `end` under arrowhead `head`, its `cap` included (a round
/// cap lies inside them).
fn stroke_end_corners(end: (f32, f32), head: [(f32, f32); 3], width: f32, cap: wordcraft_doc::connector::LineCap) -> [(f32, f32); 2] {
let [tip, a, b] = head;
let base = ((a.0 + b.0) / 2.0, (a.1 + b.1) / 2.0);
let len = (tip.0 - base.0).hypot(tip.1 - base.1);
// The head's direction, and across it.
let (dx, dy) = ((tip.0 - base.0) / len, (tip.1 - base.1) / len);
let (nx, ny) = (-dy, dx);
let reach = if cap == wordcraft_doc::connector::LineCap::Flat { 0.0 } else { width / 2.0 };
[-1.0, 1.0].map(|side| (end.0 + dx * reach + nx * side * width / 2.0, end.1 + dy * reach + ny * side * width / 2.0))
}
/// Whether `p` lies inside (or within 0.01 pt of) triangle `t`.
fn in_triangle(p: (f32, f32), t: [(f32, f32); 3]) -> bool {
let edge = |(ax, ay): (f32, f32), (bx, by): (f32, f32)| {
let len = (bx - ax).hypot(by - ay);
((bx - ax) * (p.1 - ay) - (by - ay) * (p.0 - ax)) / len
};
let sides = [edge(t[0], t[1]), edge(t[1], t[2]), edge(t[2], t[0])];
sides.iter().all(|s| *s >= -0.01) || sides.iter().all(|s| *s <= 0.01)
}
#[test]
@@ -7385,6 +7525,425 @@ fn justified_spaces_shrink_a_quarter_at_most_and_by_the_word() {
}
}
/// Measured in Word for Mac (compatibility mode 15, synthetic justified paragraphs that start
/// with a label and a tab, or with words and then a left tab): a line with a tab shrinks its
/// spaces too, but only those after its last tab. WordCraft never shrank a line with a tab, so a
/// numbered paragraph's first line wrapped a word earlier than Word's (#4845, #5847).
#[test]
fn justified_line_with_a_tab_shrinks_only_the_spaces_after_it() {
use wordcraft_doc::props::{TabAlign, TabStop};
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let word = "nnnn";
let (lead, n) = ("n n n n n n n n n n n n", 12);
let tab_at = 200.0;
let para = |text: &str, right: f32| {
let mut d = Document::new();
d.settings.compat_mode = 15;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps {
align: Some(Align::Justify),
indent_right: Some(right),
tabs: Some(vec![TabStop { pos: tab_at, align: TabAlign::Left, leader: Default::default() }]),
..Default::default()
};
d.body = vec![wordcraft_doc::para_block(p)];
d
};
// Words after the tab on the first line.
let after_tab = |d: &Document| {
let l = lay(d);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let line = &pl.lines[0];
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
};
let probe = para(&format!("{word} {word}"), 0.0);
let l = lay(&probe);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
// Room from the n spaces after the tab alone; the eleven before it would allow more.
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
let all_room = (0.25 * (n + 11) as f32 * sw).min(0.355 * (w + sw));
assert!(all_room > room + 0.5, "the test needs the spaces before the tab to matter: {room} vs {all_room}");
let text = format!("{lead}\t{}", vec![word; 3 * n].join(" "));
let full = probe.last_section.text_width();
let width = |overrun: f32| tab_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
let d = para(&text, full - width(overrun));
assert_eq!(after_tab(&d), words, "overrun {overrun:.2} of {room:.2} allowed");
}
// Verify rendered positions: spaces after the tab shrink in the allowed-overrun case,
// while positions before the tab remain unchanged.
let shrunk_doc = para(&text, full - width(room - 0.1));
let unconstrained_doc = para(&text, 0.0);
let l_shrunk = lay(&shrunk_doc);
let l_unconstrained = lay(&unconstrained_doc);
let pl_shrunk = l_shrunk.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let pl_unconstrained =
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
// Characters in `lead` and the tab's start position must have identical positions.
for k in 0..=lead.len() {
assert_eq!(pl_shrunk.x_of(0, k), pl_unconstrained.x_of(0, k), "char {k} before tab must not move when spaces after tab shrink");
}
// Text after the tab starts at tab_at.
assert!((pl_shrunk.x_of(0, lead.len() + 1).unwrap() - tab_at).abs() < 0.01, "tab position");
// Text after the tab is shifted left compared to its natural (un-shrunk) positions:
// for each word k after the tab on line 0, natural position is tab_at + k * (w + sw).
let natural_x = |k: usize| tab_at + k as f32 * (w + sw);
for k in 1..=n {
let char_pos = lead.len() + 1 + k * (word.len() + 1);
let x = pl_shrunk.x_of(0, char_pos).expect("word position on shrunk line");
assert!(x < natural_x(k), "word {k} after tab at {x} must be shifted left from natural {}", natural_x(k));
}
}
/// #5847: a justified line with multiple tabs shrinks spaces only after its last tab.
/// Spaces before the first tab and between tabs retain their natural width and positions,
/// and only spaces after the last tab count toward space_room.
#[test]
fn justified_line_with_multiple_tabs_shrinks_only_spaces_after_last_tab() {
use wordcraft_doc::props::{TabAlign, TabStop};
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let word = "nnnn";
let (lead1, lead2, n) = ("n n n n n n", "n n n n n n", 12);
let tab1_at = 120.0;
let tab2_at = 240.0;
let para = |text: &str, right: f32| {
let mut d = Document::new();
d.settings.compat_mode = 15;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps {
align: Some(Align::Justify),
indent_right: Some(right),
tabs: Some(vec![
TabStop { pos: tab1_at, align: TabAlign::Left, leader: Default::default() },
TabStop { pos: tab2_at, align: TabAlign::Left, leader: Default::default() },
]),
..Default::default()
};
d.body = vec![wordcraft_doc::para_block(p)];
d
};
// Words after the second tab on the first line.
let after_second_tab = |d: &Document| {
let l = lay(d);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let line = &pl.lines[0];
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
text.split('\t').nth(2).unwrap_or("").split_whitespace().count()
};
let probe = para(&format!("{word} {word}"), 0.0);
let l = lay(&probe);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
// Room from the n spaces after the second tab alone; spaces before tab 1 or between tabs would allow more.
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
let all_room = (0.25 * (n + 10) as f32 * sw).min(0.355 * (w + sw));
assert!(all_room > room + 0.5, "the test needs the spaces before the last tab to matter: {room} vs {all_room}");
let text = format!("{lead1}\t{lead2}\t{}", vec![word; 3 * n].join(" "));
let full = probe.last_section.text_width();
let width = |overrun: f32| tab2_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
let d = para(&text, full - width(overrun));
assert_eq!(after_second_tab(&d), words, "overrun {overrun:.2} of {room:.2} allowed");
}
// Verify rendered positions: spaces after the last tab shrink in the allowed-overrun case,
// while positions before tab 1 and between tabs remain completely unchanged.
let shrunk_doc = para(&text, full - width(room - 0.1));
let unconstrained_doc = para(&text, 0.0);
let l_shrunk = lay(&shrunk_doc);
let l_unconstrained = lay(&unconstrained_doc);
let pl_shrunk = l_shrunk.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let pl_unconstrained =
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
// Characters in `lead1`, tab 1, and `lead2` up to the second tab must have identical positions.
let pre_last_tab_len = lead1.len() + 1 + lead2.len();
for k in 0..=pre_last_tab_len {
assert_eq!(pl_shrunk.x_of(0, k), pl_unconstrained.x_of(0, k), "char {k} before last tab must not move when spaces after last tab shrink");
}
// Text after the second tab starts at tab2_at.
assert!((pl_shrunk.x_of(0, pre_last_tab_len + 1).unwrap() - tab2_at).abs() < 0.01, "second tab position");
// Text after the second tab is shifted left compared to its natural (un-shrunk) positions:
let natural_x = |k: usize| tab2_at + k as f32 * (w + sw);
for k in 1..=n {
let char_pos = pre_last_tab_len + 1 + k * (word.len() + 1);
let x = pl_shrunk.x_of(0, char_pos).expect("word position on shrunk line");
assert!(x < natural_x(k), "word {k} after last tab at {x} must be shifted left from natural {}", natural_x(k));
}
}
/// #5847: a tabbed line with no spaces after its last tab has zero shrink room.
/// Space shrinking is a no-op, guarding against division by zero, negative room,
/// or shifting pre-tab clusters when there are no spaces to shrink after the tab.
#[test]
fn justified_line_with_tab_and_no_spaces_after_it_does_not_shrink() {
use wordcraft_doc::props::{TabAlign, TabStop};
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let lead = "n n n n n n n n";
let word = "OverlongWordWithoutAnySpace";
let tab_at = 200.0;
let para = |text: &str, right: f32| {
let mut d = Document::new();
d.settings.compat_mode = 15;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps {
align: Some(Align::Justify),
indent_right: Some(right),
tabs: Some(vec![TabStop { pos: tab_at, align: TabAlign::Left, leader: Default::default() }]),
..Default::default()
};
d.body = vec![wordcraft_doc::para_block(p)];
d
};
let probe = para(word, 0.0);
let l = lay(&probe);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let word_w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
let text = format!("{lead}\t{word}");
let full = probe.last_section.text_width();
// Constrain the line so that `word` overruns the right edge by 2.0 pt.
// Because there are no spaces after the tab, shrink room is 0 and the word
// must wrap to line 1 rather than shrinking onto line 0.
let tight_doc = para(&text, full - (tab_at + word_w - 2.0));
let l_tight = lay(&tight_doc);
let pl_tight = l_tight.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
assert_eq!(pl_tight.lines.len(), 2, "word with no spaces after tab must wrap when it overruns the line");
// When the word fits within the line, characters before the tab and the word after the tab
// remain at their exact natural positions (no pre-tab shift, no shrink).
let fit_doc = para(&text, full - (tab_at + word_w + 50.0));
let unconstrained_doc = para(&text, 0.0);
let l_fit = lay(&fit_doc);
let l_unconstrained = lay(&unconstrained_doc);
let pl_fit = l_fit.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let pl_unconstrained =
l_unconstrained.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
for k in 0..=text.len() {
assert_eq!(
pl_fit.x_of(0, k),
pl_unconstrained.x_of(0, k),
"char {k} position must be unchanged when there are no spaces to shrink after the tab"
);
}
}
/// #5847: justified paragraphs starting with a tab shrink spaces on the first line in Word 2013+
/// mode, fitting more text than legacy mode 14 just as non-tab lines do.
#[test]
fn justified_lines_with_tab_shrink_spaces_in_word_2013_mode() {
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let word = "nnnn";
let n = 12;
let tab_at = 36.0; // default 0.5" tab stop
let para = |text: &str, right: f32, mode: u32| {
let mut d = Document::new();
d.settings.compat_mode = mode;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), ..Default::default() };
d.body = vec![wordcraft_doc::para_block(p)];
d
};
let first = |d: &Document| {
let l = lay(d);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let line = &pl.lines[0];
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
};
let probe = para(&format!("{word} {word}"), 0.0, 15);
let l = lay(&probe);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
let text = format!("\t{}", vec![word; 3 * n].join(" "));
let full = probe.last_section.text_width();
let width = tab_at + (n + 1) as f32 * w + n as f32 * sw - (room - 0.1);
// Verify on the tabbed first line that mode 15 fits the extra word via space shrinking
// while legacy mode 14 does not shrink spaces, wrapping the extra word to the next line.
let modern_doc = para(&text, full - width, 15);
let legacy_doc = para(&text, full - width, 14);
assert_eq!(first(&modern_doc), n + 1, "mode 15 with leading tab fits extra word within allowable overrun");
assert_eq!(first(&legacy_doc), n, "mode 14 with leading tab does not shrink spaces and wraps extra word");
// Multi-line justified paragraph with leading tab also fits more lines overall in mode 15.
let text_full = format!("\t{}", "We tie the spend to a pipe and to the books, so it is in an ad hoc view of all of it. ".repeat(40));
let (modern, ends) = justified_lines(&text_full, 15, Align::Justify);
let (legacy, legacy_ends) = justified_lines(&text_full, 14, Align::Justify);
assert!(modern < legacy, "mode 15 with leading tab fits more per line: {modern} vs {legacy} lines");
for e in ends.iter().chain(&legacy_ends) {
assert!(*e <= 540.0 + 0.05, "line ends past the right margin: {e}");
}
for e in &ends[..ends.len() - 1] {
assert!((*e - 540.0).abs() < 0.05, "justified line ends at {e}");
}
}
/// #5847: leading tab on a justified line shrinks spaces after the tab when fitting words.
#[test]
fn justified_line_with_leading_tab_shrinks_spaces() {
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let word = "nnnn";
let n = 12;
let tab_at = 36.0; // default 0.5" tab stop
let para = |text: &str, right: f32| {
let mut d = Document::new();
d.settings.compat_mode = 15;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), ..Default::default() };
d.body = vec![wordcraft_doc::para_block(p)];
d
};
let first = |d: &Document| {
let l = lay(d);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let line = &pl.lines[0];
let text = &d.para(StoryRef::Body, &Path::top(0)).unwrap().text[line.start..line.stop];
text.split('\t').nth(1).unwrap_or("").split_whitespace().count()
};
let probe = para(&format!("{word} {word}"), 0.0);
let l = lay(&probe);
let pl = l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap();
let w = pl.x_of(0, word.len()).unwrap() - pl.x_of(0, 0).unwrap();
let sw = pl.x_of(0, word.len() + 1).unwrap() - pl.x_of(0, word.len()).unwrap();
let room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
let text = format!("\t{}", vec![word; 3 * n].join(" "));
let full = probe.last_section.text_width();
let width = |overrun: f32| tab_at + (n + 1) as f32 * w + n as f32 * sw - overrun;
for (overrun, words) in [(room - 0.1, n + 1), (room + 0.1, n)] {
let d = para(&text, full - width(overrun));
assert_eq!(first(&d), words, "leading tab overrun {overrun:.2} of {room:.2} allowed");
}
}
/// #5847: fit-time and final space compression apply only after left/default tabs, not after
/// right, center, or decimal tabs whose anchors are resolved with unshrunk widths.
#[test]
fn justified_line_with_non_left_tab_preserves_anchor_and_does_not_shrink() {
use wordcraft_doc::props::{TabAlign, TabStop};
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let para = |text: &str, right: f32, tabs: Vec<TabStop>| {
let mut d = Document::new();
d.settings.compat_mode = 15;
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.props = ParaProps { align: Some(Align::Justify), indent_right: Some(right), tabs: Some(tabs), ..Default::default() };
d.body = vec![wordcraft_doc::para_block(p)];
d
};
let first_pl = |d: &Document| {
let l = lay(d);
l.pages[0].items.iter().find_map(|it| if let Placed::Lines { para, .. } = it { Some(para.clone()) } else { None }).unwrap()
};
// 1. Right tab past the usable right edge: multiword run is absorbed against the stop and
// must keep its final edge at the stop rather than shrinking left of it.
let right_text = "lead\tnnnn nnnn nnnn";
let right_stop = 280.0;
let right_edge = 240.0;
let right_tabs = vec![TabStop { pos: right_stop, align: TabAlign::Right, leader: Default::default() }];
let right_unconstrained = para(right_text, 0.0, right_tabs.clone());
let full = right_unconstrained.last_section.text_width();
let pl_right_unconstrained = first_pl(&right_unconstrained);
let pl_right = first_pl(&para(right_text, full - right_edge, right_tabs));
assert_eq!(pl_right.lines.len(), 1, "absorbed multiword run after right tab stays on line 0");
assert!(
(pl_right.x_of(0, right_text.len()).unwrap() - right_stop).abs() < 0.01,
"right-tabbed multiword run must remain aligned to stop {right_stop}, got {:?}",
pl_right.x_of(0, right_text.len())
);
for k in 0..=right_text.len() {
assert_eq!(pl_right.x_of(0, k), pl_right_unconstrained.x_of(0, k), "char {k} after right tab must not shrink");
}
// 2. Decimal tab on an overfull line: spaces before the decimal point must not shrink and
// pull the decimal point left of its stop.
let dec_text = "\t12 34.56789";
let dec_stop = 200.0;
let dec_tabs = vec![TabStop { pos: dec_stop, align: TabAlign::Decimal, leader: Default::default() }];
let dec_unconstrained = para(dec_text, 0.0, dec_tabs.clone());
let pl_dec_unconstrained = first_pl(&dec_unconstrained);
let dot_idx = dec_text.find('.').unwrap();
let dec_end = pl_dec_unconstrained.x_of(0, dec_text.len()).unwrap();
let pl_dec = first_pl(&para(dec_text, full - (dec_end - 5.0), dec_tabs));
assert_eq!(pl_dec.lines.len(), 1, "decimal-tabbed run stays on line 0");
assert_eq!(
pl_dec.x_of(0, dot_idx),
pl_dec_unconstrained.x_of(0, dot_idx),
"decimal point must keep its unconstrained anchor on an overfull line"
);
for k in 0..=dec_text.len() {
assert_eq!(pl_dec.x_of(0, k), pl_dec_unconstrained.x_of(0, k), "char {k} after decimal tab must not shrink");
}
// 3. Center tab:
// (a) Overfull center-tabbed line must not run final compression and shift off its stop.
let center_overfull_text = "\taaaaaaaaaa bbbbbbbbbb";
let center_overfull_stop = 250.0;
let center_overfull_tabs = vec![TabStop { pos: center_overfull_stop, align: TabAlign::Center, leader: Default::default() }];
let center_unconstrained = para(center_overfull_text, 0.0, center_overfull_tabs.clone());
let pl_center_unconstrained = first_pl(&center_unconstrained);
let pl_center_overfull = first_pl(&para(center_overfull_text, full - 260.0, center_overfull_tabs));
assert_eq!(pl_center_overfull.lines.len(), 1, "overfull center-tabbed line stays on line 0");
let mid = (pl_center_overfull.x_of(0, 1).unwrap() + pl_center_overfull.x_of(0, center_overfull_text.len()).unwrap()) / 2.0;
assert!((mid - center_overfull_stop).abs() < 0.01, "centered midpoint {mid} must stay at {center_overfull_stop}");
for k in 0..=center_overfull_text.len() {
assert_eq!(pl_center_overfull.x_of(0, k), pl_center_unconstrained.x_of(0, k), "char {k} after center tab must not shrink");
}
// (b) Fit-time compression must not pull an overflowing trailing word onto a non-left-tabbed line.
let probe = para("n n i", 0.0, Vec::new());
let pl_probe = first_pl(&probe);
let sw = pl_probe.x_of(0, 2).unwrap() - pl_probe.x_of(0, 1).unwrap();
let w_i = pl_probe.x_of(0, 5).unwrap() - pl_probe.x_of(0, 4).unwrap();
let prefix = "n ".repeat(12);
let fit_text = format!("\t{prefix}i");
let pl_prefix = first_pl(&para(&prefix, 0.0, Vec::new()));
let w_pre = pl_prefix.x_of(0, prefix.len()).unwrap();
let room = (0.25 * 12.0 * sw).min(0.355 * (sw + w_i));
let fit_edge = w_pre + w_i - (room - 0.1);
for align in [TabAlign::Right, TabAlign::Center, TabAlign::Decimal] {
let pl_fit = first_pl(&para(&fit_text, full - fit_edge, vec![TabStop { pos: 3.0, align, leader: Default::default() }]));
assert_eq!(pl_fit.lines.len(), 2, "{align:?} tab must not use fit-time space shrinking to accept 'i'");
}
// 4. Right tab followed by a left tab: spaces after the final left tab still shrink while the
// earlier right tab keeps its anchor.
let word = "nnnn";
let n = 12;
let right_seg = "aa bb";
let pl_w = first_pl(&para(&format!("{word} {word}"), 0.0, Vec::new()));
let w = pl_w.x_of(0, word.len()).unwrap();
let left_room = (0.25 * n as f32 * sw).min(0.355 * (w + sw));
let mixed_text = format!("\t{right_seg}\t{}", vec![word; 3 * n].join(" "));
let mixed_right_stop = 120.0;
let mixed_left_stop = 160.0;
let mixed_width = mixed_left_stop + (n + 1) as f32 * w + n as f32 * sw - (left_room - 0.1);
let pl_mixed = first_pl(&para(
&mixed_text,
full - mixed_width,
vec![
TabStop { pos: mixed_right_stop, align: TabAlign::Right, leader: Default::default() },
TabStop { pos: mixed_left_stop, align: TabAlign::Left, leader: Default::default() },
],
));
assert!(
(pl_mixed.x_of(0, 1 + right_seg.len()).unwrap() - mixed_right_stop).abs() < 0.01,
"earlier right tab must keep its stop {mixed_right_stop}"
);
let first_line_words = mixed_text[pl_mixed.lines[0].start..pl_mixed.lines[0].stop].split('\t').nth(2).unwrap_or("").split_whitespace().count();
assert_eq!(first_line_words, n + 1, "spaces after final left tab still shrink");
}
#[test]
fn space_shrinking_is_only_for_justified_text() {
crate::test_fonts();
+1
View File
@@ -319,6 +319,7 @@ impl WordApp {
pub fn logic(&mut self, ctx: &egui::Context) {
let lang = i18n::Lang::from_pref(&self.ui.language);
if self.ctx.is_none() {
theme::set_dark_text_curve(ctx);
self.ctx = Some(ctx.clone());
}
updates_ui::tick(self, ctx);
+11
View File
@@ -147,6 +147,12 @@ const LINKED_EDIT: [craft::ui::runtime::commands::EditCommands; 5] = {
[Cut, Copy, Paste, Undo, Redo]
};
/// The English parts of a registry `location` (`Home › Font`, split as `i18n::location` does); `None` for no place.
pub(crate) fn location_path(location: &str) -> Option<Vec<&str>> {
let path: Vec<&str> = location.split(" › ").filter(|part| !part.is_empty()).collect();
(!path.is_empty()).then_some(path)
}
impl WordApp {
/// The app's commands as the keymap knows them: every engine command with its default
/// chords, then the interface commands. The interface commands come last because a tie in the
@@ -183,6 +189,11 @@ impl WordApp {
// warned about), so their chords go in as the set's replaced defaults (the `LINKED_EDIT` fold below).
for spec in registry.all().iter().filter(|spec| seen.insert(spec.id) && !LINKED_EDIT.iter().any(|c| c.id() == spec.id)) {
let mut def = CommandDef::new(CommandRef::new(spec.id), tl!(spec.label), Scope::app());
// Its ribbon place is its menu path, in English: Customize Keyboard files it under the tab by name,
// and the framework translates each segment where it shows it.
if let Some(path) = location_path(spec.location) {
def = def.with_path(path.into_iter().map(str::to_owned).collect());
}
for binding in default_bindings(spec.shortcut) {
def = def.with_default(binding);
}
+19 -1
View File
@@ -25,7 +25,11 @@ pub(crate) fn help_entries(app: &WordApp) -> Vec<HelpEntry> {
.map(|c| {
let command =
if c.id == "view.paperColor" { CommandRef::with_params("file.options", json!({"pane": "general"})) } else { CommandRef::new(c.id) };
HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string())
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())),
None => entry,
}
})
.collect()
}
@@ -81,3 +85,17 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, compact: bool) -> egui::Rect
}
rect
}
#[cfg(test)]
mod tests {
use crate::{Services, WordApp};
/// #7983: a search result names the ribbon place of its command.
#[test]
fn search_entries_show_the_ribbon_location() {
let app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Services::default());
let entries = super::help_entries(&app);
let bold = entries.iter().find(|e| e.command().id == "format.bold").expect("format.bold is searchable");
assert!(!bold.path().is_empty(), "the entry has a path");
}
}
@@ -5,10 +5,11 @@
//! through `tools.customizeKeyboard`, so agents get the same result without the dialog.
use craft::keymap::{Binding, CommandDef, Keymap, Overrides};
use craft::menu::shortcuts::{DialogState, Layout, Options, Outcome, ShortcutsDialog};
use craft::menu::shortcuts::{Area, DialogState, Layout, Options, Outcome, ShortcutsDialog};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use egui::{Context, Ui};
use serde_json::{Value, json};
use wordcraft_engine::ribbon::{CONTEXTUAL_TABS, TABS};
use super::host::{DialogHooks, Settle, open_with};
use crate::WordApp;
@@ -49,11 +50,61 @@ fn assignable(binding: &Binding) -> bool {
chord.mods.cmd || chord.mods.ctrl || chord.mods.alt || chord.is_function_key()
}
/// The ribbon tab a command lives on, in English (the first part of its path).
fn tab(def: &CommandDef) -> &str {
def.paths.first().and_then(|path| path.first()).map_or("", String::as_str)
}
/// Tabs that come up with the selection or a view, besides the engine's contextual ones; they share one Categories entry.
const EXTRA_CONTEXT_TABS: [&str; 3] = ["Header & Footer", "Outlining", "Reading"];
fn in_tab<const N: usize>(def: &CommandDef) -> bool {
tab(def) == TABS[N]
}
fn in_context_tab(def: &CommandDef) -> bool {
CONTEXTUAL_TABS.contains(&tab(def)) || EXTRA_CONTEXT_TABS.contains(&tab(def))
}
fn in_no_tab(def: &CommandDef) -> bool {
!TABS.contains(&tab(def)) && !in_context_tab(def)
}
/// One filter per entry of `TABS` (the array's length makes the compiler check it).
const TAB_FILTERS: [fn(&CommandDef) -> bool; TABS.len()] = [
in_tab::<0>,
in_tab::<1>,
in_tab::<2>,
in_tab::<3>,
in_tab::<4>,
in_tab::<5>,
in_tab::<6>,
in_tab::<7>,
in_tab::<8>,
in_tab::<9>,
in_tab::<10>,
in_tab::<11>,
in_tab::<12>,
];
/// Categories as Word lists them: the ribbon tabs (not the framework's menu and panel ids), the contextual tabs, the
/// rest, then All Commands.
fn areas() -> Vec<Area> {
let mut areas: Vec<Area> = TABS.iter().copied().zip(TAB_FILTERS).map(|(name, rows)| Area::new(name, tl!(name), rows)).collect();
areas.push(Area::new("Contextual Tabs", tl!("Contextual Tabs"), in_context_tab));
areas.push(Area::new("Other", tl!("Other"), in_no_tab));
areas.push(Area::new("All Commands", tl!("All Commands"), |_| true));
areas
}
/// The framework dialog's options: the command-list layout, sorted by label, with the assign rule above.
fn options() -> Options {
Options::default().with(|o| {
o.layout = Layout::CommandLists;
o.sort_by_label = true;
o.own_areas = true;
o.size = Some(egui::vec2(720.0, 700.0));
o.areas = areas();
o.title = Some(tl!("Customize Keyboard").to_string());
o.accept = Some(Box::new(|_: &CommandDef, binding: &Binding| {
if assignable(binding) { Ok(()) } else { Err(tl!("Use a key combination with Ctrl, Alt or a function key.").to_string()) }
@@ -247,4 +298,53 @@ mod tests {
let unbound_labels = keys_list_labels(&h);
assert!(unbound_labels.iter().any(|t| t == "None"), "empty keys list says None: {unbound_labels:?}");
}
/// #7971: Categories are the ribbon tabs a command is on, not menu or panel ids; a command with no tab is under Other,
/// and every command is under All Commands.
#[test]
fn categories_are_ribbon_tabs() {
use craft::keymap::{CommandDef, Scope};
let on = |path: &[&str]| {
let mut def = CommandDef::new(CommandRef::new("x"), "X", Scope::app());
if !path.is_empty() {
def = def.with_path(path.iter().map(|part| part.to_string()).collect());
}
def
};
let areas = super::areas();
let listing = |def: &CommandDef| areas.iter().filter(|a| (a.rows)(def)).map(|a| a.id).collect::<Vec<_>>();
assert_eq!(listing(&on(&["Home", "Font"])), ["Home", "All Commands"]);
assert_eq!(listing(&on(&["Help", "Support"])), ["Help", "All Commands"], "every ribbon tab has its entry");
assert_eq!(listing(&on(&["Table Design", "Styles"])), ["Contextual Tabs", "All Commands"]);
assert_eq!(listing(&on(&[])), ["Other", "All Commands"]);
assert_eq!(areas.last().map(|a| a.id), Some("All Commands"), "All Commands comes last");
}
/// #7971: under another language, and for the SmartArt tab that shows as "Diagram Design", commands still land
/// under their tab (the catalog keeps English paths; only the display is translated).
#[test]
fn commands_stay_under_their_tab_in_another_language() {
let ctx = egui::Context::default();
crate::i18n::fixture_host(&ctx, "x-fixture", "\tHome\tHome-FX\n\tFont\tFont-FX\n\tDiagram Design\tDiagram-FX\n");
let mut a = app();
let catalog = a.catalog().expect("catalog");
let areas = super::areas();
let under = |id: &str, area: &str| {
let def = catalog.defs().iter().find(|def| def.command == CommandRef::new(id)).unwrap_or_else(|| panic!("{id} in catalog"));
areas.iter().any(|a| a.id == area && (a.rows)(def))
};
assert!(under("format.bold", "Home"), "Bold is under Home in a translated interface");
assert!(!under("format.bold", "Other"));
let smart = a.session.registry.all().iter().find(|spec| spec.location.starts_with("SmartArt Design")).expect("a SmartArt command");
assert!(under(smart.id, "Contextual Tabs") && !under(smart.id, "Other"), "{} is under the contextual tabs", smart.id);
}
/// #7971: the board's catalog files each engine command under its ribbon tab.
#[test]
fn catalog_paths_follow_the_ribbon_location() {
let mut a = app();
let catalog = a.catalog().expect("catalog");
let bold = catalog.defs().iter().find(|def| def.command == CommandRef::new("format.bold")).expect("format.bold");
assert_eq!(bold.paths.first().and_then(|p| p.first()).map(String::as_str), Some("Home"));
}
}
+10 -8
View File
@@ -20,7 +20,7 @@ use craft::ui::contract::{
};
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, PromptChoice, StackDialog, StandardPrompt, dialog_id};
use craft::ui::display::Text;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::layout_components::{Grid, Row, Stack};
use craft::ui::list::{List, ListRow, ToggleCell, ToggleState};
use craft::ui::notices::Notice;
use craft::ui::runtime::env::Label;
@@ -51,6 +51,8 @@ pub struct TreeItem {
pub command: Option<String>,
}
/// The body's panes: the command pickers, the Add and Remove buttons, then the ribbon or toolbar list.
const PANES: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::Content, ColumnWidth::fill(1.0)];
/// The column of show boxes in the ribbon tree.
const SHOWN: ColumnKey = ColumnKey::new("shown");
@@ -143,10 +145,10 @@ impl RibbonDialog {
fn body(&mut self, ui: &mut Ui) {
self.page_tabs(ui);
search(ui, &mut self.filter);
Row::new().show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
Grid::new(&PANES).fill_width().show(ui, |ui, _| {
Stack::new().fill_width().show(ui, |ui, _| {
Text::new(word("Choose a command")).show(ui);
Row::new().show(ui, |ui, _| {
Row::new().fill_width().show(ui, |ui, _| {
if let Some(category) = pick(ui, "rb_categories", "Categories:", &self.categories, &self.category) {
self.category = category;
self.filter.clear();
@@ -219,9 +221,9 @@ impl RibbonDialog {
self.file("remove", Value::Object(address(&sel)));
}
});
Stack::new().show(ui, |ui, _| {
Stack::new().fill_width().show(ui, |ui, _| {
Text::new(word("Ribbon tabs")).show(ui);
Row::new().show(ui, |ui, _| {
Row::new().fill_width().show(ui, |ui, _| {
self.tree(ui);
Stack::new().show(ui, |ui, _| {
for (text, by) in [("Up", -1), ("Down", 1)] {
@@ -309,9 +311,9 @@ impl RibbonDialog {
self.file("qatRemove", json!(self.qat_selected));
}
});
Stack::new().show(ui, |ui, _| {
Stack::new().fill_width().show(ui, |ui, _| {
Text::new(word("Quick Access Toolbar")).show(ui);
Row::new().show(ui, |ui, _| {
Row::new().fill_width().show(ui, |ui, _| {
if let Some(id) = pick(ui, "rb_qat", "Quick Access Toolbar", &self.qat, &self.qat_selected) {
self.qat_selected = id;
}
+29 -4
View File
@@ -155,13 +155,14 @@ fn markup_key(app: &WordApp) -> MarkupKey {
/// What the preview's layout is made from besides the document's text: the document id, the
/// revision, Print Markup and Track Changes Options, the file name and path FILENAME fields show
/// (#6282: Save As and Rename change them without an edit), and the font database generation the
/// app has seen (#6283: `WordApp::watch_fonts` moves it when fonts are added or removed).
type LayoutKey = (u64, u64, MarkupKey, (String, String), u64);
/// (#6282: Save As and Rename change them without an edit), the numeral mode (#6265: it changes
/// the display without an edit or a revision), and the font database generation the app has seen
/// (#6283: `WordApp::watch_fonts` moves it when fonts are added or removed).
type LayoutKey = (u64, u64, MarkupKey, wordcraft_layout::NumeralMode, (String, String), u64);
/// The [`LayoutKey`] now.
fn layout_key(app: &WordApp) -> LayoutKey {
(app.session.document_id(), app.session.rev(), markup_key(app), app.session.resolved_filenames(), app.font_generation)
(app.session.document_id(), app.session.rev(), markup_key(app), app.session.view.numeral, app.session.resolved_filenames(), app.font_generation)
}
/// The output layout, kept in `cache` while what it is made from ([`LayoutKey`]) is unchanged.
@@ -496,6 +497,30 @@ mod tests {
}
}
/// Numeral display changes layout and pixels without changing the document revision
/// (#6265): the preview must not reuse either cache.
#[test]
fn preview_refreshes_layout_and_texture_when_the_numeral_mode_changes() {
let session = Session::new(wordcraft_doc::Document::from_text("2026 Report"));
let mut app = WordApp::new(session, Services::default());
let mut cache = None;
let rev = app.session.rev();
let mut previous = None;
for mode in ["arabic", "hindi", "arabic"] {
app.session.run("view.numeral", &json!({ "value": mode })).unwrap();
let layout = layout_of(&app, &mut cache);
assert!(Arc::ptr_eq(&layout, &layout_of(&app, &mut cache)), "unchanged layout is reused");
let revision = preview::inputs(&app);
assert_eq!(revision, preview::inputs(&app));
if let Some((old_layout, old_revision)) = previous.take() {
assert!(!Arc::ptr_eq(&layout, &old_layout));
assert_ne!(revision, old_revision, "the sheet is drawn again");
}
previous = Some((layout, revision));
assert_eq!(app.session.rev(), rev);
}
}
/// A one-page synthetic document in a fresh preview.
fn synthetic_app() -> (WordApp, egui::Context) {
let session = Session::new(wordcraft_doc::Document::from_text("Synthetic print preview"));
+64 -12
View File
@@ -8,7 +8,7 @@ use craft::ui::buttons::{Arrangement, Button, IconButton};
use craft::ui::contract::{ActivateOn, BodyCx, CollectionEvent, Gap, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::display::Divider;
use craft::ui::layout_components::Stack;
use craft::ui::list::ThumbAspect;
use craft::ui::list::{ThumbAspect, ThumbSize};
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::primitives::{HAlign, TextRun};
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
@@ -286,17 +286,69 @@ pub(super) fn insert(row: &mut RibbonRow<'_>, app: &mut WordApp) {
});
}
/// The recent and common characters as a grid of six per row; a click inserts the character, remembers it and closes
/// The characters the grid offers after the recent ones, with their Unicode names (UnicodeData.txt). No Unicode-names
/// crate is installed, and the one on crates.io is under Unicode-DFS-2016, which the licence allowlist lacks.
const DEFAULT_SYMBOLS: &[(char, &str)] = &[
('\u{A9}', "COPYRIGHT SIGN"),
('\u{AE}', "REGISTERED SIGN"),
('\u{2122}', "TRADE MARK SIGN"),
('\u{A7}', "SECTION SIGN"),
('\u{B6}', "PILCROW SIGN"),
('\u{20AC}', "EURO SIGN"),
('\u{A3}', "POUND SIGN"),
('\u{A5}', "YEN SIGN"),
('\u{B0}', "DEGREE SIGN"),
('\u{B1}', "PLUS-MINUS SIGN"),
('\u{2260}', "NOT EQUAL TO"),
('\u{2264}', "LESS-THAN OR EQUAL TO"),
('\u{2265}', "GREATER-THAN OR EQUAL TO"),
('\u{F7}', "DIVISION SIGN"),
('\u{D7}', "MULTIPLICATION SIGN"),
('\u{221E}', "INFINITY"),
('\u{B5}', "MICRO SIGN"),
('\u{3B1}', "GREEK SMALL LETTER ALPHA"),
('\u{3B2}', "GREEK SMALL LETTER BETA"),
('\u{3C0}', "GREEK SMALL LETTER PI"),
('\u{3A9}', "GREEK CAPITAL LETTER OMEGA"),
('\u{2211}', "N-ARY SUMMATION"),
('\u{221A}', "SQUARE ROOT"),
('\u{2192}', "RIGHTWARDS ARROW"),
('\u{2190}', "LEFTWARDS ARROW"),
('\u{2713}', "CHECK MARK"),
('\u{2605}', "BLACK STAR"),
('\u{2665}', "BLACK HEART SUIT"),
('\u{2014}', "EM DASH"),
('\u{2026}', "HORIZONTAL ELLIPSIS"),
];
/// A symbol's hover text: its Unicode name and code point (the code point alone, with its block, for a character
/// not named above), then its font when it has one.
pub(super) fn symbol_tip(glyph: &str, font: &str) -> String {
let mut chars = glyph.chars();
let tip = match (chars.next(), chars.next()) {
(Some(c), None) => {
let name = DEFAULT_SYMBOLS.iter().find(|(n, _)| *n == c).map(|(_, name)| *name);
let block = crate::dialogs_insert::subset_of(c);
match (name, block) {
(Some(name), _) => format!("{name} (U+{:04X})", c as u32),
(None, Some(block)) => format!("U+{:04X} ({block})", c as u32),
(None, None) => format!("U+{:04X}", c as u32),
}
}
_ => glyph.to_string(),
};
if font.is_empty() { tip } else { format!("{tip}, {font}") }
}
/// The recent and common characters as a compact grid; a click inserts the character, remembers it and closes
/// the menu.
fn symbol_grid(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
// Recently used symbols first (their font on hover), then common ones.
let mut items: Vec<(String, String)> = app.ui.recent_symbols.iter().map(|r| (r.ch.clone(), r.font.clone())).collect();
for c in [
"©", "®", "™", "§", "", "€", "£", "¥", "°", "±", "≠", "≤", "≥", "÷", "×", "∞", "µ", "α", "β", "π", "Ω", "∑", "√", "→", "←", "✓", "★", "♥",
"—", "…",
] {
if !items.iter().any(|(ch, f)| ch == c && f.is_empty()) {
items.push((c.to_string(), String::new()));
for (c, _) in DEFAULT_SYMBOLS {
let c = c.to_string();
if !items.iter().any(|(ch, f)| *ch == c && f.is_empty()) {
items.push((c, String::new()));
}
}
items.truncate(30);
@@ -304,20 +356,20 @@ fn symbol_grid(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp) {
.select(SelectMode::None)
.activate(ActivateOn::Click)
.caption(CaptionPlace::None)
.card_columns(6)
.content_cells()
// Small cells (#7165): a glyph needs no more room than the small thumbnail step.
.thumb_size(ThumbSize::Small)
// At most thirty symbols, all shown; the menu's body is the one scroll.
.natural_height(true)
.show_items(ui, &SymbolCells(items.len()), &mut |key, _| {
let (c, font) = items.get(*key).cloned().unwrap_or_default();
let glyph = c.clone();
let (glyph, tip) = (c.clone(), symbol_tip(&c, &font));
let tile = Tile::new(c).thumb(ThumbAspect::SQUARE, move |cx, rect| {
let run = TextRun::new(glyph.as_str()).align(HAlign::Center);
cx.with_draw(|d| {
d.text_on_centre_line(rect, &run);
});
});
if font.is_empty() { tile } else { tile.tooltip(font) }
tile.tooltip(tip)
});
for event in &out.response.events {
if let CollectionEvent::Activate(key) = event
+124 -73
View File
@@ -959,92 +959,109 @@ fn unimplemented_stub_ribbon_buttons_are_disabled() {
}
}
/// #7324, #7457: Table ribbon menu buttons (Styles, Borders, Select, Delete, AutoFit) bind their command IDs
/// so they disable when editing is protected or when no table is active.
#[test]
fn table_ribbon_menu_buttons_disable_when_unselected_or_protected() {
/// Is the ribbon button `name` disabled? (helpers for the table ribbon gate tests below.)
fn table_button_disabled(h: &Harness, name: &str) -> bool {
use egui::accesskit::Role;
h.query_all(By::new().role(Role::Button).label(name)).next().unwrap_or_else(|| panic!("button {name} not found")).accesskit_node().is_disabled()
}
let is_disabled = |h: &Harness, name: &str| {
h.query_all(By::new().role(Role::Button).label(name))
.next()
.unwrap_or_else(|| panic!("button {name} not found"))
.accesskit_node()
.is_disabled()
};
fn table_button_hint(h: &Harness, name: &str) -> String {
use egui::accesskit::Role;
h.query_all(By::new().role(Role::Button).label(name))
.next()
.unwrap_or_else(|| panic!("button {name} not found"))
.accesskit_node()
.description()
.map(|s| s.to_string())
.unwrap_or_default()
}
let description = |h: &Harness, name: &str| {
h.query_all(By::new().role(Role::Button).label(name))
.next()
.unwrap_or_else(|| panic!("button {name} not found"))
.accesskit_node()
.description()
.map(|s| s.to_string())
};
/// A 2x2 table app on `tab`; `protected` sets read-only protection.
fn table_tab_harness(tab: &str, protected: bool) -> Harness {
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
if protected {
app.session.doc.settings.protection = Some("readOnly".into());
}
tab_harness(app, tab)
}
// Configure Table Design & Table Layout as explicit ribbon tabs so they can be
// displayed even when the cursor is outside a table.
let make_table_tabs_app = |mut app: WordApp| {
/// #7324, #7457: without an active table the Table ribbon menu buttons disable. The Table tabs are
/// configured explicitly so they show with the cursor outside a table.
#[test]
fn table_ribbon_menu_buttons_disable_when_unselected() {
for tab in ["Table Design", "Table Layout"] {
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default());
app.session.ribbon.tabs = vec![
wordcraft_engine::ribbon::TabEntry { name: "Table Design".to_string(), custom: false, hidden: false, groups: Vec::new() },
wordcraft_engine::ribbon::TabEntry { name: "Table Layout".to_string(), custom: false, hidden: false, groups: Vec::new() },
];
app
};
let h = tab_harness(app, tab);
if tab == "Table Design" {
assert!(table_button_disabled(&h, "Styles"), "Styles button should be disabled when not in table");
assert!(table_button_disabled(&h, "Borders"), "Borders button should be disabled when not in table");
} else {
assert!(table_button_disabled(&h, "Select"), "Select button should be disabled when not in table");
assert!(table_button_disabled(&h, "Delete"), "Delete button should be disabled when not in table");
assert!(table_button_disabled(&h, "AutoFit"), "AutoFit button should be disabled when not in table");
assert!(
table_button_hint(&h, "Select").to_ascii_lowercase().contains("the cursor isn't in a table"),
"Select should indicate outside table in disabled hint"
);
}
}
}
// 1. Without a table active:
let app_no_table = make_table_tabs_app(WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default()));
let h_design_empty = tab_harness(app_no_table, "Table Design");
assert!(is_disabled(&h_design_empty, "Styles"), "Styles button should be disabled when not in table");
assert!(is_disabled(&h_design_empty, "Borders"), "Borders button should be disabled when not in table");
/// With an active, unprotected table the Table Design buttons are enabled.
#[test]
fn table_design_menu_buttons_enabled_in_table() {
let h = table_tab_harness("Table Design", false);
assert!(!table_button_disabled(&h, "Styles"), "Styles button should be enabled in table");
assert!(!table_button_disabled(&h, "Borders"), "Borders button should be enabled in table");
}
let app_no_table2 = make_table_tabs_app(WordApp::new(Session::new(wordcraft_doc::Document::from_text("Hello")), crate::Services::default()));
let h_layout_empty = tab_harness(app_no_table2, "Table Layout");
assert!(is_disabled(&h_layout_empty, "Select"), "Select button should be disabled when not in table");
assert!(is_disabled(&h_layout_empty, "Delete"), "Delete button should be disabled when not in table");
assert!(is_disabled(&h_layout_empty, "AutoFit"), "AutoFit button should be disabled when not in table");
assert!(
description(&h_layout_empty, "Select").as_deref().unwrap_or("").to_ascii_lowercase().contains("the cursor isn't in a table"),
"Select should indicate outside table in disabled hint"
);
/// With an active, unprotected table the Table Layout buttons are enabled and open their menus
/// (the controls for the shut-menu checks under protection).
#[test]
fn table_layout_menu_buttons_enabled_in_table() {
let mut h = table_tab_harness("Table Layout", false);
assert!(!table_button_disabled(&h, "Select"), "Select button should be enabled in table");
assert!(!table_button_disabled(&h, "Delete"), "Delete button should be enabled in table");
assert!(!table_button_disabled(&h, "AutoFit"), "AutoFit button should be enabled in table");
click_button(&mut h, "Delete");
assert!(h.query_all(menu_row("Delete Rows")).next().is_some(), "an enabled Delete opens its menu");
}
// 2. With an active table and no protection: buttons are enabled:
let mut app_table = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app_table.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
let h_design = tab_harness(app_table, "Table Design");
assert!(!is_disabled(&h_design, "Styles"), "Styles button should be enabled in table");
assert!(!is_disabled(&h_design, "Borders"), "Borders button should be enabled in table");
/// Positive control for the AutoFit shut-menu check under protection: an enabled AutoFit opens its menu.
#[test]
fn table_layout_autofit_opens_menu_in_table() {
let mut h = table_tab_harness("Table Layout", false);
click_button(&mut h, "AutoFit");
assert!(h.query_all(menu_row("AutoFit Window")).next().is_some(), "an enabled AutoFit opens its menu");
}
let mut app_table2 = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app_table2.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
let h_layout = tab_harness(app_table2, "Table Layout");
assert!(!is_disabled(&h_layout, "Select"), "Select button should be enabled in table");
assert!(!is_disabled(&h_layout, "Delete"), "Delete button should be enabled in table");
assert!(!is_disabled(&h_layout, "AutoFit"), "AutoFit button should be enabled in table");
/// Under read-only protection the Table Design buttons disable and say why.
#[test]
fn table_design_menu_buttons_disable_when_protected() {
let h = table_tab_harness("Table Design", true);
assert!(table_button_disabled(&h, "Styles"), "Styles button should be disabled under protection");
assert!(table_button_disabled(&h, "Borders"), "Borders button should be disabled under protection");
assert!(table_button_hint(&h, "Styles").contains("protected"), "Styles should indicate protection in disabled hint");
}
// 3. With an active table under document protection (read-only): mutating buttons are disabled:
let mut app_protected_design = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app_protected_design.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
app_protected_design.session.doc.settings.protection = Some("readOnly".into());
let h_prot_design = tab_harness(app_protected_design, "Table Design");
assert!(is_disabled(&h_prot_design, "Styles"), "Styles button should be disabled under protection");
assert!(is_disabled(&h_prot_design, "Borders"), "Borders button should be disabled under protection");
assert!(
description(&h_prot_design, "Styles").as_deref().unwrap_or("").contains("protected"),
"Styles should indicate protection in disabled hint"
);
let mut app_protected_layout = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app_protected_layout.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
app_protected_layout.session.doc.settings.protection = Some("readOnly".into());
let h_prot_layout = tab_harness(app_protected_layout, "Table Layout");
assert!(!is_disabled(&h_prot_layout, "Select"), "Select button should remain enabled under protection");
assert!(is_disabled(&h_prot_layout, "Delete"), "Delete button should be disabled under protection");
assert!(is_disabled(&h_prot_layout, "AutoFit"), "AutoFit button should be disabled under protection");
assert!(
description(&h_prot_layout, "Delete").as_deref().unwrap_or("").contains("protected"),
"Delete should indicate protection in disabled hint"
);
/// Under read-only protection the mutating Table Layout buttons disable, say why, and stay shut
/// when clicked (C2-5, #7824).
#[test]
fn table_layout_menu_buttons_disable_when_protected() {
let mut h = table_tab_harness("Table Layout", true);
assert!(!table_button_disabled(&h, "Select"), "Select button should remain enabled under protection");
assert!(table_button_disabled(&h, "Delete"), "Delete button should be disabled under protection");
assert!(table_button_disabled(&h, "AutoFit"), "AutoFit button should be disabled under protection");
assert!(table_button_hint(&h, "Delete").contains("protected"), "Delete should indicate protection in disabled hint");
click_button(&mut h, "Delete");
assert!(h.query_all(menu_row("Delete Rows")).next().is_none(), "a disabled Delete opens no menu");
click_button(&mut h, "AutoFit");
assert!(h.query_all(menu_row("AutoFit Window")).next().is_none(), "a disabled AutoFit opens no menu");
}
/// #7374: the Decorative Text / WordArt Styles dropdown menu renders compact tiles (~40×36 pt)
@@ -1322,3 +1339,37 @@ fn a_combo_field_reached_with_tab_shows_its_hint_after_a_delay() {
}
assert!(h.query_all_by_label("Font Size").count() >= 2, "hint must show after tooltip delay");
}
/// #7165: the Symbol drop-down's cells are compact (a thumbnail-small step, not a card) and the hover text names
/// the character, not just the glyph.
#[test]
fn symbol_menu_cells_are_compact_and_the_tooltip_names_the_character() {
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Text")), crate::Services::default());
let mut h = tab_harness(app, "Insert");
click_button(&mut h, "Symbol");
let cell_y = |h: &Harness| h.get_by_label("\u{A9}").rect().min.y;
let cell = h.get_by_label("\u{A9}").rect();
assert!(cell.width() <= 80.0 && cell.height() <= 80.0, "a symbol cell is compact, got {:?}", cell.size());
// Eight symbols fit one row, so the menu does not cover the page.
assert_eq!(h.get_by_label("\u{A5}").rect().min.y, cell_y(&h), "the eighth symbol is on the first row");
h.get_by_label("\u{A9}").hover();
crate::test_harness::frames(&mut h, 40);
assert!(h.query_by_label_contains("COPYRIGHT SIGN (U+00A9)").is_some(), "the tooltip names the character");
// A screen reader gets the name without hovering: the tile's label is the glyph, its description the name.
let desc = h.get_by_label("\u{A9}").accesskit_node().description().map(|d| d.to_string()).unwrap_or_default();
assert!(desc.contains("COPYRIGHT SIGN"), "the tile's accessible description names the character, got {desc:?}");
}
/// Characters outside the common list still say what they are: code point and block.
#[test]
fn symbol_tip_names_known_characters_and_falls_back_to_the_code_point() {
use super::insert::symbol_tip;
let named = symbol_tip("\u{A9}", "");
assert!(named.contains("COPYRIGHT SIGN") && named.contains("00A9"), "named character: {named}");
let with_font = symbol_tip("\u{3B1}", "Symbol");
assert!(with_font.contains("GREEK SMALL LETTER ALPHA") && with_font.contains("03B1") && with_font.contains("Symbol"), "{with_font}");
assert!(!named.contains("Symbol"), "no font, none named");
let unnamed = symbol_tip("\u{2602}", "");
assert!(unnamed.contains("2602") && unnamed.contains("Miscellaneous Symbols"), "unnamed character: {unnamed}");
assert_eq!(symbol_tip("", ""), "");
}
+22
View File
@@ -3393,6 +3393,28 @@ fn check_spelling_off_in_a_second_window_stays_off_in_every_window() {
assert!(!b.session.view.proofing && !b.session.prefs.check_spelling, "saved off, whichever window was drawn");
}
/// #7841: in dark mode the app draws its interface text with its own lighter curve, not egui's dark default, and
/// light mode keeps egui's light one.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn dark_interface_text_uses_the_app_s_lighter_curve() {
let ctx = crate::test_harness::context();
let mut a = app();
let curve = |a: &mut WordApp, theme: theme::Appearance| {
a.ui.theme = theme;
for _ in 0..2 {
crate::test_harness::pass(&ctx, a, egui::RawInput::default());
}
ctx.global_style().visuals.text_options.color_transfer_function
};
let dark = curve(&mut a, theme::Appearance::Dark);
let light = curve(&mut a, theme::Appearance::Light);
let lighter = egui::epaint::FontColorTransferFunction::Gamma(0.8);
assert_eq!(dark, lighter, "dark mode draws with the app's curve");
assert_eq!(light, egui::Visuals::light().text_options.color_transfer_function, "light mode keeps egui's");
assert_eq!(curve(&mut a, theme::Appearance::Dark), lighter, "back to dark gets the app's curve again");
}
/// #1861: the registered Interface Theme command drives the same setting as Options:
/// searchable in the registry, settable, toggling without a value, and surviving a restart.
#[test]
+10
View File
@@ -712,6 +712,16 @@ pub fn apply_animations(ctx: &egui::Context, on: bool) {
/// Coverage exponent for light-on-dark interface text on Linux and the BSDs (see [`visuals`]).
const DARK_TEXT_GAMMA: f32 = 0.8;
/// Gives egui's dark style our lighter light-on-dark text curve on Linux and the BSDs (see [`visuals`]). The craft
/// runtime's mode sync keeps an app's own curve for each mode (craft-libs#3589), so setting it once is enough (#7841).
pub fn set_dark_text_curve(ctx: &egui::Context) {
if cfg!(all(unix, not(target_os = "macos"))) {
ctx.style_mut_of(egui::Theme::Dark, |s| {
s.visuals.text_options.color_transfer_function = egui::epaint::FontColorTransferFunction::Gamma(DARK_TEXT_GAMMA);
});
}
}
/// egui's visuals for one of our palettes.
fn visuals(t: &Tokens) -> Visuals {
let mut v = if t.dark { Visuals::dark() } else { Visuals::light() };
File diff suppressed because one or more lines are too long
+2 -1
View File
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -31,7 +31,7 @@ Exact line spacing keeps the run font baseline around tall equations; automatic
| Line breaking (UAX #14 with Word's exceptions: no break after `/`, a break after `-` before a digit, before another `-` (a row of hyphens wraps at any hyphen), or before a slash and a letter (`Dataprotection-` / `/Secrecyviolation` in the #3408 report's Word PDF; `fitness-/1589` stays whole in the arabic_rice_benefits_article reference), no break between `.` and `(`) | ✅ | `layout::tests::no_line_break_right_after_a_slash`, `layout::tests::a_hyphen_before_digits_is_a_break_opportunity_like_word`, `layout::tests::a_hyphen_before_a_slash_is_a_break_opportunity_like_word`, `layout::tests::a_row_of_hyphens_wraps_at_any_hyphen_like_word`, `layout::tests::a_full_stop_before_a_parenthesis_is_no_break`, `layout::tests::a_bookmark_is_no_line_break_opportunity` | — |
| A break before a slash that starts a word (" /word" wraps whole; not after a no-break space) | 🟡 | `layout::tests::a_word_after_a_slash_wraps_whole`, `layout::tests::a_no_break_space_before_a_slash_still_holds`; behaviour from the #2963 report, not compared with Word yet | — |
| Narrow table cells | ✅ | `layout::tests::narrow_cells_keep_their_width`: usable widths below 12 pt wrap without expansion; oversized glyphs still make progress | 0 |
| Justification, Word 2013+ space shrinking (compat mode 15) | ✅ | #109; spaces before a line's first character (paragraph indented with spaces, after a line break or a tab, a bookmark, hidden text or a floating object's anchor before them) keep their width in justified and distributed lines, `layout::tests::leading_spaces_keep_their_width_in_justified_lines` | — |
| Justification, Word 2013+ space shrinking (compat mode 15) | ✅ | #109, #5847. A line with a tab shrinks too, counting only the spaces after its last tab, measured in Word for Mac (`layout::tests::justified_line_with_a_tab_shrinks_only_the_spaces_after_it`); spaces before a line's first character (paragraph indented with spaces, after a line break or a tab, a bookmark, hidden text or a floating object's anchor before them) keep their width in justified and distributed lines (`layout::tests::leading_spaces_keep_their_width_in_justified_lines`) | — |
| Spaces at the end of a line hang past the right margin instead of wrapping; the caret after them stays at the margin, in the body and in headers and footers | ✅ | `layout::tests::caret_after_hanging_spaces_stays_at_the_margin` (#2146): a letter typed after them wraps to the next line | — |
| Complex scripts (Myanmar, Khmer, Indic): shaped per script run with OpenType fallback fonts, one cluster per syllable, Myanmar wraps between syllables | 🟡 | `layout::tests::complex` (#604). Khmer, Thai and Lao still wrap only at spaces (need a dictionary) | 4–8 |
| Cursive joining (Arabic, Syriac, Mongolian, N'Ko…) across runs: a letter takes its form from the text shown beside it, across a change of formatting, past a vowel sign in a run of its own and past hidden or tracked-deleted text left out of the view; a tab, break, object or drop cap still stops the join | ✅ | `layout::tests::bidi::letters_join_across_a_change_of_formatting`, `letters_join_past_text_left_out_of_the_layout`, `letters_join_past_a_mark_in_a_run_of_its_own`, `letters_stay_apart_where_nothing_joins_them` (#4093); not compared with Word on this machine | 0 |
@@ -558,6 +558,7 @@ The front-of-text opt-out is retained from the earlier implementation; this patc
| 2026-11-02 | trivial | Beyond Word, for ODT documents: a table's own space above and below (`TableProps::space_before`/`space_after`) moves the text around it, and a header (footer) taller than its margin keeps its spacing between it and the body (`SectionProps::header_gap`/`footer_gap`; Word keeps none, so DOCX documents are unchanged) (`tests::a_tables_own_space_above_and_below_moves_the_text`, `tests::body_starts_right_below_a_tall_header`) |
| 2026-11-02 | trivial | A page break before the paragraph in a table's first row moves the whole table to the next page, as in Word (it was ignored); emphasis marks (Font › Emphasis mark) are drawn over or under each character and make the line taller |
| 2026-11-12 | minor | Added layout.fitOnePage: heuristic search over discrete font half-point steps and spacing compression with anti-clutter safeguards (line-spacing floor and font-size floor) to condense multi-page documents by one page while preserving hierarchy |
| 2026-11-07 | trivial | A justified line with a tab shrinks its spaces to fit more text, counting only the spaces after the line's last tab, measured in Word for Mac; WordCraft never shrank a line with a tab, so a numbered paragraph's first line wrapped a word early (#5847) |
| 2026-10-31 | trivial | Web addresses: no line break after the `?` of a query (`/?type=`) or after a slash before an underscore (`/portal/_back`). Word for Mac 16.93 kept such an address whole and moved it to the next line; WordCraft broke it there (UAX #14 allows both). With the address moved along the line one word at a time (60 paragraphs, Times New Roman 12pt), WordCraft's lines now match Word's line for line; 23 (query) and 19 (underscore) paragraphs broke inside the address before. A `?` keeps its break before anything but an ASCII letter, digit or underscore (CJK text), and a path after a space (`caption /_back`) wraps whole. `layout::tests::no_line_break_inside_a_query_address`, `a_path_after_a_space_wraps_whole`, `a_question_mark_in_cjk_text_keeps_its_break` |
Maintenance on 2026-10-12 retains current tracked-deletion, endnote, footer-total, text-box
+2 -1
View File
File diff suppressed because one or more lines are too long