mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-28 08:45:52 -06:00
Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a9fa89fb2 | ||
|
|
8b293b64ad | ||
|
|
d1c9c8c034 | ||
|
|
06499e39aa | ||
|
|
5796c665b9 | ||
|
|
e74e627a38 | ||
|
|
e9286c9487 | ||
|
|
b7057e56f6 | ||
|
|
784e4c3c35 | ||
|
|
188be727b7 | ||
|
|
05dc3214ea | ||
|
|
72ca96a27c | ||
|
|
f83d554322 | ||
|
|
0f4e80aedd | ||
|
|
bab08b77e1 | ||
|
|
2b407facd0 | ||
|
|
b7819874c8 | ||
|
|
9cf6a33374 | ||
|
|
29bb5a4f44 | ||
|
|
aae46e1274 | ||
|
|
9d78c95517 | ||
|
|
6ea92c6b93 | ||
|
|
7905692c1f | ||
|
|
7416d36aeb | ||
|
|
9e68fdb76a | ||
|
|
d63de66920 | ||
|
|
bee50afd8f | ||
|
|
a1a3b53f74 | ||
|
|
8ff9bdb1a1 | ||
|
|
694ac7810d | ||
|
|
1441c64970 | ||
|
|
3b94750945 | ||
|
|
376411a22b | ||
|
|
932f5b4748 | ||
|
|
011a46c677 | ||
|
|
4239458948 | ||
|
|
b4219f9745 | ||
|
|
37e5849e58 |
@@ -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 }}
|
||||
@@ -74,5 +74,6 @@ WordCraft is a Rust word processor targeting Microsoft Word parity, for macOS, W
|
||||
- Attribution: `ATTRIBUTION.md`, a row per asset file, checked by `cargo xtask assets`. Icons are our own SVG set in `crates/ui-egui/icons/` (draw new icons there); sample content is in `crates/engine/src/sample.rs` and `cmd/design.rs`.
|
||||
- Fonts and language data come from other repositories as optional build inputs: craft-fonts through `CRAFT_FONTS_DIR`, and craft-i18n's `language-data/` through `CRAFT_I18N_DIR` (pinned by `craft-i18n.rev`; CI checks it out). Without craft-i18n the app builds with fallback spelling and no pattern hyphenation, so proofing tests need it. Proprietary font requests use installed fonts or the open substitutes in `crates/fonts/src/word.rs`. Layout tests use the fixed fonts in `assets/fonts/` ([docs/testing.md](docs/testing.md)).
|
||||
- Run: `cargo run --release -p wordcraft -- --sample --control 7981` starts the app with a sample document and the control channel. It takes JSON lines on `127.0.0.1:7981`: authenticate once per connection with the token from `~/.config/wordcraft/control-key.local-7981` (macOS: `~/Library/Application Support/WordCraft/`), `{"id":1,"method":"auth","params":{"token":"…"}}`, then send requests without a token; methods are in `crates/ui-egui/src/control.rs`, docs in `docs/control-protocol.md` (Token). Headless screenshots: `cargo run --release -p wordcraft-ui-egui --example ui_shot -- script.jsonl`. CLI: `wordcraft-cli convert|run|commands|parity`. MCP: `wordcraft-cli mcp --automation-read-root DIR --automation-write-root DIR` (both required; `--connect` is refused until the app confines its control channel, #3695), see `docs/mcp.md`.
|
||||
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog feature `headless: yes` only when its command is in the engine registry that `wordcraft-cli` and the MCP server load (never a `ui.*` id). A missing feature takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `crates/engine/src/catalog.rs`, or reads `unknown`. When a command lands, delete its mark; `headless_marks_are_current` fails on a stale one.
|
||||
- Notes and progress: `plan/` is an optional gitignored notebook. Committed: `ROADMAP.md` (progress log), `docs/gaps.md`, `docs/roadmap.md`, `docs/target-app-parity.md`, `docs/architecture.md` and the parity checklists.
|
||||
- Contributor credits: `docs/contributors.md`.
|
||||
|
||||
@@ -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, ` ` 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.
|
||||
|
||||
@@ -889,6 +889,17 @@ fn parity_markdown(p: &Value) -> String {
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
s += &format!("| {} | {} | {} |\n", t["tab"].as_str().unwrap_or(""), t["live"], t["total"]);
|
||||
}
|
||||
let h = &p["headless"];
|
||||
s += &format!(
|
||||
"\n**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no (window {}, os {}, engine-gap {}), {} partial, {} unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.\n",
|
||||
h["yes"],
|
||||
h["no"]["window"].as_u64().unwrap_or(0) + h["no"]["os"].as_u64().unwrap_or(0) + h["no"]["engine-gap"].as_u64().unwrap_or(0),
|
||||
h["no"]["window"],
|
||||
h["no"]["os"],
|
||||
h["no"]["engine-gap"],
|
||||
h["partial"],
|
||||
h["unknown"]
|
||||
);
|
||||
s += "\n## Missing\n\n";
|
||||
for t in p["tabs"].as_array().cloned().unwrap_or_default() {
|
||||
let m = t["missing"].as_array().cloned().unwrap_or_default();
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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
@@ -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);
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -532,6 +532,98 @@ Tools|Templates|Templates and Add-ins|tools.templates
|
||||
Tools|Views|Full Screen View|view.fullScreenView
|
||||
";
|
||||
|
||||
/// RFC-0052 hand marks for catalog features with no engine command: `id|headless|reach|why`.
|
||||
///
|
||||
/// `headless` is `no` or `partial`, `reach` is `window` (needs a desktop window, dialog or
|
||||
/// pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could
|
||||
/// be an engine command, isn't one yet). `yes` is never written here: a feature is `yes` only when
|
||||
/// its id is in the engine registry that `wordcraft-cli` and the MCP server load, and a mark on such
|
||||
/// an id is stale (`headless_errors`). A missing feature with no mark is `unknown`.
|
||||
pub const HEADLESS: &str = "\
|
||||
tools.dictate|no|os|speech recognition service
|
||||
insert.onlinePicture|no|os|online image search service
|
||||
insert.model3d|no|engine-gap|3-D model files could be inserted by a command
|
||||
insert.screenshot|no|os|screen capture of other windows
|
||||
addins.get|no|os|add-in store service
|
||||
insert.video|no|os|online video service
|
||||
insert.inkEquation|no|window|drawn with a pen or pointer
|
||||
draw.inkToMath|no|os|handwriting recognition service
|
||||
review.translate|no|os|online translation service
|
||||
review.blockAuthors|no|os|co-authoring service
|
||||
view.readLayout|no|window|Read Mode window layout
|
||||
";
|
||||
|
||||
/// One feature's RFC-0052 `headless:` value and, for `no`/`partial`, its `reach:` and reason.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Headless {
|
||||
pub value: &'static str,
|
||||
pub reach: Option<&'static str>,
|
||||
pub why: &'static str,
|
||||
}
|
||||
|
||||
const REACHES: [&str; 3] = ["window", "os", "engine-gap"];
|
||||
|
||||
/// Parsed `HEADLESS`-format marks: (id, value, reach, why). A malformed line is an error.
|
||||
pub fn headless_marks(src: &'static str) -> Result<Vec<(&'static str, Headless)>, String> {
|
||||
let mut out = Vec::new();
|
||||
for line in src.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let f: Vec<&'static str> = line.splitn(4, '|').collect();
|
||||
let [id, value, reach, why] = f[..] else {
|
||||
return Err(format!("headless mark `{line}`: want `id|headless|reach|why`"));
|
||||
};
|
||||
if !matches!(value, "no" | "partial") {
|
||||
return Err(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
|
||||
}
|
||||
if !REACHES.contains(&reach) {
|
||||
return Err(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap"));
|
||||
}
|
||||
if out.iter().any(|(m, _)| *m == id) {
|
||||
return Err(format!("headless mark `{id}` is written twice"));
|
||||
}
|
||||
out.push((id, Headless { value, reach: Some(reach), why }));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The `headless:` value of a catalog feature: `yes` when the engine registry has its id, else its
|
||||
/// hand mark, else `unknown`.
|
||||
pub fn headless_of(id: &str, live: bool, marks: &[(&'static str, Headless)]) -> Headless {
|
||||
if live {
|
||||
return Headless { value: "yes", reach: None, why: "" };
|
||||
}
|
||||
marks.iter().find(|(m, _)| *m == id).map(|(_, h)| *h).unwrap_or(Headless { value: "unknown", reach: None, why: "" })
|
||||
}
|
||||
|
||||
/// Problems with the marks against the catalog and the registry's ids: unknown ids, and marks on
|
||||
/// ids the engine registry has (they would hide a `yes`).
|
||||
pub fn headless_errors(src: &'static str, catalog: &[(&str, &str, &str, &str)], live: impl Fn(&str) -> bool) -> Vec<String> {
|
||||
let marks = match headless_marks(src) {
|
||||
Ok(m) => m,
|
||||
Err(e) => return vec![e],
|
||||
};
|
||||
let mut errs = Vec::new();
|
||||
for (id, _) in &marks {
|
||||
if !catalog.iter().any(|e| e.3 == *id) {
|
||||
errs.push(format!("headless mark `{id}` is not a catalog id"));
|
||||
} else if live(id) {
|
||||
errs.push(format!("headless mark `{id}` is stale: the engine registry has it, so it is `yes`"));
|
||||
}
|
||||
}
|
||||
errs
|
||||
}
|
||||
|
||||
/// Headless counts in the RFC-0052 summary shape.
|
||||
fn headless_summary(values: &[Headless]) -> Value {
|
||||
let count = |v: &str| values.iter().filter(|h| h.value == v).count();
|
||||
let no = |r: &str| values.iter().filter(|h| h.value == "no" && h.reach == Some(r)).count();
|
||||
json!({
|
||||
"yes": count("yes"),
|
||||
"no": {"window": no("window"), "os": no("os"), "engine-gap": no("engine-gap")},
|
||||
"partial": count("partial"),
|
||||
"unknown": count("unknown"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Catalog entries: (tab, group, feature, id).
|
||||
pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)> {
|
||||
CATALOG
|
||||
@@ -546,9 +638,13 @@ pub fn entries() -> Vec<(&'static str, &'static str, &'static str, &'static str)
|
||||
/// Parity summary: per tab and overall, with the missing features.
|
||||
pub fn parity(reg: &Registry) -> Value {
|
||||
let e = entries();
|
||||
let marks = headless_marks(HEADLESS).unwrap_or_default();
|
||||
let mut values = Vec::with_capacity(e.len());
|
||||
let mut tabs: Vec<(&str, usize, usize, Vec<String>)> = Vec::new();
|
||||
for (tab, group, label, id) in &e {
|
||||
let have = reg.get(id).is_some();
|
||||
let h = headless_of(id, have, &marks);
|
||||
values.push(h);
|
||||
let t = match tabs.iter_mut().find(|t| t.0 == *tab) {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
@@ -564,7 +660,8 @@ pub fn parity(reg: &Registry) -> Value {
|
||||
if have {
|
||||
t.1 += 1;
|
||||
} else {
|
||||
t.3.push(format!("{group} › {label} (`{id}`)"));
|
||||
let reach = h.reach.map(|r| format!(", reach: {r} ({})", h.why)).unwrap_or_default();
|
||||
t.3.push(format!("{group} › {label} (`{id}`): headless: {}{reach}", h.value));
|
||||
}
|
||||
}
|
||||
let live = tabs.iter().map(|t| t.1).sum::<usize>();
|
||||
@@ -573,6 +670,7 @@ pub fn parity(reg: &Registry) -> Value {
|
||||
"live": live,
|
||||
"total": total,
|
||||
"percent": if total == 0 { 0.0 } else { (live as f64 * 1000.0 / total as f64).round() / 10.0 },
|
||||
"headless": headless_summary(&values),
|
||||
"tabs": tabs.iter().map(|t| json!({"tab": t.0, "live": t.1, "total": t.2, "missing": t.3})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
@@ -597,6 +695,44 @@ mod tests {
|
||||
assert!(pct >= 90.4, "parity {pct}%");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_marks_are_current() {
|
||||
let reg = crate::cmd::registry();
|
||||
let errs = headless_errors(HEADLESS, &entries(), |id| reg.get(id).is_some());
|
||||
assert!(errs.is_empty(), "{errs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_yes_comes_only_from_the_registry() {
|
||||
let marks = headless_marks("a.b|no|window|pointer\n").unwrap();
|
||||
assert_eq!(headless_of("a.b", true, &marks).value, "yes", "a live id is yes whatever the mark says");
|
||||
assert_eq!(headless_of("a.b", false, &marks).reach, Some("window"));
|
||||
assert_eq!(headless_of("c.d", false, &marks).value, "unknown");
|
||||
assert!(headless_marks("a.b|yes|window|x\n").is_err(), "a hand-written yes is refused");
|
||||
assert!(headless_marks("a.b|no|desk|x\n").is_err(), "reach must be window, os or engine-gap");
|
||||
assert!(headless_marks("a.b|no\n").is_err());
|
||||
assert!(headless_marks("a.b|no|os|x\na.b|partial|os|y\n").is_err(), "one mark per id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_errors_flag_stale_and_unknown_marks() {
|
||||
let cat = [("T", "G", "F", "a.b"), ("T", "G", "H", "c.d")];
|
||||
let errs = headless_errors("a.b|no|os|x\nz.z|no|os|y\n", &cat, |id| id == "a.b");
|
||||
assert!(errs.iter().any(|e| e.contains("`a.b` is stale")), "{errs:?}");
|
||||
assert!(errs.iter().any(|e| e.contains("`z.z` is not a catalog id")), "{errs:?}");
|
||||
assert!(headless_errors("bad\n", &cat, |_| false).len() == 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parity_counts_every_feature_once_in_the_headless_summary() {
|
||||
let p = parity(&crate::cmd::registry());
|
||||
let h = &p["headless"];
|
||||
let n = |v: &Value| v.as_u64().unwrap_or(0);
|
||||
let no = n(&h["no"]["window"]) + n(&h["no"]["os"]) + n(&h["no"]["engine-gap"]);
|
||||
assert_eq!(n(&h["yes"]) + no + n(&h["partial"]) + n(&h["unknown"]), n(&p["total"]));
|
||||
assert_eq!(n(&h["yes"]), n(&p["live"]), "every live feature is an engine command here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_mode_view_menu_is_catalogued() {
|
||||
let e = entries();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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 (§ion, 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();
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
@@ -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(¶(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(¶(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(¢er_unconstrained);
|
||||
let pl_center_overfull = first_pl(¶(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(¶(&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(¶(&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(¶(&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(¶(
|
||||
&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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -3,18 +3,21 @@
|
||||
//! `styles.copyFrom`, `styles.delete`, `styles.rename`), so agents get the same result without
|
||||
//! the dialogs.
|
||||
|
||||
use craft::behavior::{EditEvent, Selection, SelectionChange, item_source::keyed};
|
||||
use craft::behavior::{ColumnWidth, EditEvent, Selection, SelectionChange, item_source::keyed};
|
||||
use craft::host::PickRequest;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, request_rename};
|
||||
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::layout::CellAlign;
|
||||
use craft::ui::layout_components::{Grid, Stack};
|
||||
use craft::ui::list::{List, ListRow};
|
||||
use craft::ui::notices::Notice;
|
||||
use craft::ui::patterns::form_dialogs::{FormCx, PathRow};
|
||||
use craft::ui::runtime::env::{Env, Label};
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::style::SurfaceKind;
|
||||
use egui::{Context, Ui};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -24,6 +27,15 @@ use super::styles::{action, label};
|
||||
use crate::WordApp;
|
||||
|
||||
const ORGANIZER_KEY: &str = "organizer";
|
||||
/// The Organizer's columns: each takes what it holds, and a list holds at least `LIST_WIDTH` (a fill column takes no more
|
||||
/// than its content in a dialog that sizes to its content, so an empty list was a few pixels wide).
|
||||
const COLUMNS: [ColumnWidth; 3] = [ColumnWidth::Content; 3];
|
||||
/// The least width of a list, in points.
|
||||
const LIST_WIDTH: f32 = 200.0;
|
||||
/// The rows each list shows before it scrolls.
|
||||
const LIST_ROWS: u16 = 12;
|
||||
/// The other file's list has its name above it, so it shows one row fewer to end level with the first.
|
||||
const OTHER_ROWS: u16 = LIST_ROWS - 1;
|
||||
|
||||
/// The Templates and Add-ins dialog's fields.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
@@ -236,50 +248,69 @@ impl OrganizerDialog {
|
||||
|
||||
fn body(&mut self, ui: &mut Ui) {
|
||||
let reason = browse_reason(ui);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let mut selection = Selection::single(self.left.clone());
|
||||
let mine = &self.mine;
|
||||
let source = keyed(mine, |st| text_of(st, "id"));
|
||||
let out = List::new(label(tl!("Document")))
|
||||
.select(SelectMode::Single)
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.rename(true)
|
||||
.can_rename(|key: &String| {
|
||||
mine.iter().find(|x| text_of(x, "id") == *key).is_some_and(|x| !x.get("builtIn").and_then(Value::as_bool).unwrap_or(true))
|
||||
})
|
||||
.id_salt("mine")
|
||||
.show_items(ui, &source, &mut |_, icx| {
|
||||
let Some(st) = mine.get(icx.at) else { return ListRow::spacer() };
|
||||
ListRow::new(label(text_of(st, "name"))).lead_text(label(glyph(&text_of(st, "type"))), label("¶"))
|
||||
});
|
||||
for event in out.events {
|
||||
match event {
|
||||
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => {
|
||||
if let Some(key) = keys.last() {
|
||||
self.left = key.clone();
|
||||
let mine_id = ui.scope_id().with("organizer_mine");
|
||||
// Three columns as the old dialog had: this document's styles, Copy / Delete / Rename, the other file's styles.
|
||||
Grid::new(&COLUMNS).cells(CellAlign::Top).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
ui.set_min_width(LIST_WIDTH);
|
||||
let mut selection = Selection::single(self.left.clone());
|
||||
let mine = &self.mine;
|
||||
let source = keyed(mine, |st| text_of(st, "id"));
|
||||
let out = List::new(label(tl!("Document")))
|
||||
.surface(SurfaceKind::Frame)
|
||||
.select(SelectMode::Single)
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.rename(true)
|
||||
.can_rename(|key: &String| {
|
||||
mine.iter().find(|x| text_of(x, "id") == *key).is_some_and(|x| !x.get("builtIn").and_then(Value::as_bool).unwrap_or(true))
|
||||
})
|
||||
.id(mine_id)
|
||||
.min_rows(LIST_ROWS)
|
||||
.max_rows(LIST_ROWS)
|
||||
.show_items(ui, &source, &mut |_, icx| {
|
||||
let Some(st) = mine.get(icx.at) else { return ListRow::spacer() };
|
||||
ListRow::new(label(text_of(st, "name"))).lead_text(label(glyph(&text_of(st, "type"))), label("¶"))
|
||||
});
|
||||
for event in out.events {
|
||||
match event {
|
||||
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => {
|
||||
if let Some(key) = keys.last() {
|
||||
self.left = key.clone();
|
||||
}
|
||||
}
|
||||
CollectionEvent::Rename(EditEvent::Commit { after, .. }) => {
|
||||
self.requests.push(Request::Rename { style: after.key, name: after.name });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
CollectionEvent::Rename(EditEvent::Commit { after, .. }) => {
|
||||
self.requests.push(Request::Rename { style: after.key, name: after.name });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if action(ui, "copy", label(tl!("Copy")), !self.right.is_empty(), None) {
|
||||
self.requests.push(Request::Copy);
|
||||
}
|
||||
if action(ui, "delete", label(tl!("Delete")), !self.left_builtin(), None) {
|
||||
self.requests.push(Request::Delete(self.left.clone()));
|
||||
}
|
||||
let name = std::path::Path::new(&self.file).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "—".into());
|
||||
Field::new(label(name)).show(ui, |ui, _| {
|
||||
});
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
if action(ui, "copy", label(tl!("Copy")), !self.right.is_empty(), None) {
|
||||
self.requests.push(Request::Copy);
|
||||
}
|
||||
if action(ui, "delete", label(tl!("Delete")), !self.left_builtin(), None) {
|
||||
self.requests.push(Request::Delete(self.left.clone()));
|
||||
}
|
||||
// The list's own rename field takes the name in place.
|
||||
if action(ui, "rename", label(tl!("Rename…")), !self.left_builtin(), None) {
|
||||
request_rename(ui.ctx(), mine_id, &self.left);
|
||||
}
|
||||
});
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
ui.set_min_width(LIST_WIDTH);
|
||||
let name = std::path::Path::new(&self.file).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "—".into());
|
||||
Text::new(label(name)).show(ui);
|
||||
let mut selection = Selection::single(self.right.clone());
|
||||
let other = &self.other;
|
||||
let source = keyed(other, |(n, _)| n.clone());
|
||||
let out = List::new(label(tl!("Template")))
|
||||
.surface(SurfaceKind::Frame)
|
||||
.select(SelectMode::Single)
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.id_salt("other")
|
||||
.min_rows(OTHER_ROWS)
|
||||
.max_rows(OTHER_ROWS)
|
||||
.show_items(ui, &source, &mut |_, icx| {
|
||||
let Some((n, ty)) = other.get(icx.at) else { return ListRow::spacer() };
|
||||
ListRow::new(label(n)).lead_text(label(glyph(ty)), label("¶"))
|
||||
@@ -291,12 +322,13 @@ impl OrganizerDialog {
|
||||
self.right = key.clone();
|
||||
}
|
||||
}
|
||||
let picked = template_row(label(tl!("Template")), Bind::bound(&mut self.file), reason.clone()).show(ui).picked;
|
||||
if let Some(path) = picked {
|
||||
self.requests.push(Request::Load(path));
|
||||
}
|
||||
});
|
||||
});
|
||||
// The other file's path and Browse stand under both lists, at the dialog's full width.
|
||||
let picked = template_row(label(tl!("Template")), Bind::bound(&mut self.file), reason.clone()).show(ui).picked;
|
||||
if let Some(path) = picked {
|
||||
self.requests.push(Request::Load(path));
|
||||
}
|
||||
if !self.message.is_empty() {
|
||||
Notice::new(craft::theme::variant::Tone::Bad, label(&self.message)).show(ui);
|
||||
}
|
||||
|
||||
@@ -191,11 +191,11 @@ const MARGIN_SIDES: [(&str, &str); 4] = [("top", "Top"), ("left", "Left"), ("bot
|
||||
fn open_cell_margins(app: &mut WordApp, ctx: &Context, parent: Option<DialogId>) -> Option<DialogId> {
|
||||
let margins = cell_margins_pt(app)?;
|
||||
let fields = DialogFields::from_pairs(MARGIN_SIDES.iter().zip(margins).map(|((key, _), v)| (*key, v)));
|
||||
let kind = crate::options::unit_kind(app.session.units());
|
||||
let units = crate::options::lengths(app.session.units());
|
||||
let dialog = HostedParamDialog::new(ctx, "tableCellMargins", fields, move |fields| {
|
||||
let params: Vec<Param> = MARGIN_SIDES
|
||||
.iter()
|
||||
.map(|(key, label)| Param::number(*key, tl!(label).to_string(), 0.0, 1.0, 2).bounds(Some(0.0), Some(144.0)).unit(kind))
|
||||
.map(|(key, label)| Param::number(*key, tl!(label).to_string(), 0.0, units.shown.step(), 2).bounds(Some(0.0), Some(144.0)).length(units))
|
||||
.collect();
|
||||
ParamDialog::command("tableCellMargins", tl!("Cell Margins").to_string(), params).values(Bind::bound(fields)).alt_resets(false)
|
||||
});
|
||||
|
||||
@@ -2283,3 +2283,109 @@ fn modal_dialog_with_open_popup_does_not_shake_on_inside_click_but_shakes_on_out
|
||||
let key2 = chrome::nudge_id(&h.ctx, id2);
|
||||
assert!(h.ctx.data(|d| d.get_temp::<f64>(key2)).is_none(), "reopened dialog starts still");
|
||||
}
|
||||
|
||||
/// #7970: Cell Margins shows the table's points in the interface unit (0.19 cm, not 5.4 cm), and OK without
|
||||
/// an edit leaves the table's margins as they were.
|
||||
#[test]
|
||||
fn cell_margins_dialog_shows_points_in_the_interface_unit_and_ok_changes_nothing() {
|
||||
let mut app = app_with("");
|
||||
let _ = app.run("insert.table", json!({"rows": 1, "cols": 1}));
|
||||
app.session.prefs.units = Some(wordcraft_geom::Unit::Centimeters);
|
||||
let mut h = app_harness(app);
|
||||
h.run_steps(2);
|
||||
let (tp, _, _) = h.state().session.sel.focus.path.cell().unwrap();
|
||||
let margins =
|
||||
|h: &egui_kittest::Harness<'_, WordApp>| h.state().session.doc.table(h.state().session.sel.focus.story, &tp).unwrap().props.cell_margins;
|
||||
let before = margins(&h);
|
||||
let _ = h.state_mut().run("ui.dialog", json!({"name": "tableCellMargins"}));
|
||||
h.run_steps(3);
|
||||
let left = h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Left").value().unwrap_or_default();
|
||||
let shown: f64 = left.trim_end_matches(|c: char| !c.is_ascii_digit()).replace(',', ".").parse().unwrap_or(f64::NAN);
|
||||
assert!(shown < 1.0, "5.4 pt is about 0.19 cm, not the point count: {left:?}");
|
||||
let id = id_of(h.state(), "tableCellMargins");
|
||||
let ctx = h.ctx.clone();
|
||||
let _ = h.state_mut().dialog_host.confirm_by_id(&ctx, id);
|
||||
h.run_steps(4);
|
||||
assert_eq!(margins(&h), before, "OK without an edit writes no margins");
|
||||
}
|
||||
|
||||
/// #7970: a width typed into Cell Margins in the interface unit reaches the table in points (1 cm is about 28 pt).
|
||||
#[test]
|
||||
fn cell_margins_dialog_converts_a_typed_length_back_to_points() {
|
||||
let mut app = app_with("");
|
||||
let _ = app.run("insert.table", json!({"rows": 1, "cols": 1}));
|
||||
app.session.prefs.units = Some(wordcraft_geom::Unit::Centimeters);
|
||||
let mut h = app_harness(app);
|
||||
h.run_steps(2);
|
||||
let (tp, _, _) = h.state().session.sel.focus.path.cell().unwrap();
|
||||
let _ = h.state_mut().run("ui.dialog", json!({"name": "tableCellMargins"}));
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(egui::accesskit::Role::SpinButton, "Left").click();
|
||||
h.run_steps(3);
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
|
||||
h.event(egui::Event::Paste("1".into()));
|
||||
h.run_steps(3);
|
||||
h.key_press(egui::Key::Tab);
|
||||
h.run_steps(3);
|
||||
let id = id_of(h.state(), "tableCellMargins");
|
||||
let ctx = h.ctx.clone();
|
||||
let _ = h.state_mut().dialog_host.confirm_by_id(&ctx, id);
|
||||
h.run_steps(4);
|
||||
let left = h.state().session.doc.table(h.state().session.sel.focus.story, &tp).unwrap().props.cell_margins.map(|m| m[1]);
|
||||
assert!(left.is_some_and(|l| (l - 28.35).abs() < 0.5), "1 cm is about 28.35 pt: {left:?}");
|
||||
}
|
||||
|
||||
/// #7980: the Organizer shows this document's styles and the other file's side by side, with Copy, Delete and
|
||||
/// Rename between them, all inside the dialog.
|
||||
#[test]
|
||||
fn organizer_shows_both_lists_and_its_buttons() {
|
||||
use egui::accesskit::Role;
|
||||
let mut h = app_harness(app_with(""));
|
||||
h.run_steps(2);
|
||||
let _ = h.state_mut().run("ui.dialog", json!({"name": "organizer"}));
|
||||
h.run_steps(4);
|
||||
let rect = |h: &egui_kittest::Harness<'_, WordApp>, role, name: &str| h.get_by_role_and_label(role, name).rect();
|
||||
let mine = rect(&h, Role::List, "Document");
|
||||
let other = rect(&h, Role::List, "Template");
|
||||
assert!(mine.is_positive() && other.is_positive() && mine.right() <= other.left(), "the lists stand side by side: {mine:?} {other:?}");
|
||||
// Each list is wider than the button column between them, empty (no other file) or not.
|
||||
let rename = rect(&h, Role::Button, "Rename…");
|
||||
assert!(mine.width() > rename.width() && other.width() > rename.width(), "the lists are wider than the buttons: {mine:?} {other:?} {rename:?}");
|
||||
// The ribbon has its own Copy: the one that counts stands between the lists.
|
||||
for name in ["Copy", "Delete", "Rename…"] {
|
||||
let between = h
|
||||
.query_all(egui_kittest::kittest::By::new().role(Role::Button).label(name))
|
||||
.any(|b| b.rect().left() >= mine.right() - 1.0 && b.rect().right() <= other.left() + 1.0);
|
||||
assert!(between, "{name} stands between the lists {mine:?} {other:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Part of #7980: the Organizer's two lists have a visible frame, as before the port; without it an empty list is a
|
||||
/// blank patch.
|
||||
#[test]
|
||||
fn the_organizer_lists_are_framed() {
|
||||
use egui::accesskit::Role;
|
||||
fn rects<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::epaint::RectShape>) {
|
||||
match shape {
|
||||
egui::Shape::Vec(inner) => inner.iter().for_each(|s| rects(s, out)),
|
||||
egui::Shape::Rect(r) => out.push(r),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut h = app_harness(app_with(""));
|
||||
h.run_steps(2);
|
||||
let _ = h.state_mut().run("ui.dialog", json!({"name": "organizer"}));
|
||||
h.run_steps(4);
|
||||
let mut seen = Vec::new();
|
||||
h.output().shapes.iter().for_each(|c| rects(&c.shape, &mut seen));
|
||||
for label in ["Document", "Template"] {
|
||||
let list = h.get_by_role_and_label(Role::List, label).rect();
|
||||
assert!(
|
||||
seen.iter().any(|r| r.stroke.width > 0.0
|
||||
&& r.stroke.color.a() > 0
|
||||
&& r.rect.contains_rect(list.shrink(2.0))
|
||||
&& list.expand(2.0).contains_rect(r.rect)),
|
||||
"the list {label:?} {list:?} has a border"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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("", ""), "");
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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
File diff suppressed because one or more lines are too long
@@ -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
|
||||
|
||||
+14
-12
@@ -32,35 +32,37 @@ Generated by `cargo xtask parity` (`wordcraft-cli parity --markdown`): the word-
|
||||
| Editing | 41 | 41 |
|
||||
| Tools | 7 | 7 |
|
||||
|
||||
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 510 yes, 12 no (window 3, os 8, engine-gap 1), 0 partial, 0 unknown.** A feature is `headless: yes` when its command is in the engine registry that `wordcraft-cli` and the MCP server load, so every live feature above is `yes`; the missing ones carry the hand mark from `HEADLESS` in `crates/engine/src/catalog.rs`, or `unknown`.
|
||||
|
||||
## Missing
|
||||
|
||||
### Home
|
||||
|
||||
- Voice › Dictate (`tools.dictate`)
|
||||
- Voice › Dictate (`tools.dictate`): headless: no, reach: os (speech recognition service)
|
||||
|
||||
### Insert
|
||||
|
||||
- Illustrations › Online Pictures (`insert.onlinePicture`)
|
||||
- Illustrations › 3D Models (`insert.model3d`)
|
||||
- Illustrations › Screenshot (`insert.screenshot`)
|
||||
- Add-ins › Get Add-ins (`addins.get`)
|
||||
- Media › Online Video (`insert.video`)
|
||||
- Symbols › Ink Equation (`insert.inkEquation`)
|
||||
- Illustrations › Online Pictures (`insert.onlinePicture`): headless: no, reach: os (online image search service)
|
||||
- Illustrations › 3D Models (`insert.model3d`): headless: no, reach: engine-gap (3-D model files could be inserted by a command)
|
||||
- Illustrations › Screenshot (`insert.screenshot`): headless: no, reach: os (screen capture of other windows)
|
||||
- Add-ins › Get Add-ins (`addins.get`): headless: no, reach: os (add-in store service)
|
||||
- Media › Online Video (`insert.video`): headless: no, reach: os (online video service)
|
||||
- Symbols › Ink Equation (`insert.inkEquation`): headless: no, reach: window (drawn with a pen or pointer)
|
||||
|
||||
### Draw
|
||||
|
||||
- Convert › Ink to Math (`draw.inkToMath`)
|
||||
- Convert › Ink to Math (`draw.inkToMath`): headless: no, reach: os (handwriting recognition service)
|
||||
|
||||
### Review
|
||||
|
||||
- Language › Translate (`review.translate`)
|
||||
- Protect › Block Authors (`review.blockAuthors`)
|
||||
- Language › Translate (`review.translate`): headless: no, reach: os (online translation service)
|
||||
- Protect › Block Authors (`review.blockAuthors`): headless: no, reach: os (co-authoring service)
|
||||
|
||||
### Read Mode
|
||||
|
||||
- View › Layout (`view.readLayout`)
|
||||
- View › Layout (`view.readLayout`): headless: no, reach: window (Read Mode window layout)
|
||||
|
||||
### Equation
|
||||
|
||||
- Tools › Ink Equation (`insert.inkEquation`)
|
||||
- Tools › Ink Equation (`insert.inkEquation`): headless: no, reach: window (drawn with a pen or pointer)
|
||||
|
||||
|
||||
+2
-1
File diff suppressed because one or more lines are too long
@@ -11,7 +11,7 @@ sonar.python.coverage.reportPaths=python-coverage.xml
|
||||
# S4790 (weak hash): SHA-1 is a start-key and "SHA1/1K" checksum algorithm that ODF package
|
||||
# encryption (ODF 1.3 Part 2 §4.16) names, and older office suites wrote it. It is needed to open
|
||||
# those files, not chosen for new security: WordCraft writes a SHA-256 start key and checksum.
|
||||
sonar.issue.ignore.multicriteria=odt_sha1
|
||||
sonar.issue.ignore.multicriteria=odt_sha1,validate_py_paths
|
||||
sonar.issue.ignore.multicriteria.odt_sha1.ruleKey=rust:S4790
|
||||
sonar.issue.ignore.multicriteria.odt_sha1.resourceKey=crates/formats/src/odt/crypt.rs
|
||||
|
||||
@@ -22,3 +22,9 @@ sonar.issue.ignore.multicriteria.odt_sha1.resourceKey=crates/formats/src/odt/cry
|
||||
# os_window, control-key). process_identity.rs is Windows-only (the taskbar AUMID) and cannot run
|
||||
# on the Linux runner either.
|
||||
sonar.coverage.exclusions=packaging/**,apps/wordcraft/src/main.rs,apps/wordcraft-cli/src/main.rs,apps/wordcraft/src/process_identity.rs
|
||||
|
||||
# S8707 (path traversal): the crates/validate *.py scripts are developer tools run by hand to
|
||||
# regenerate checked-in files; reading and writing the paths given on their command line is
|
||||
# their purpose, and nothing passes them untrusted input.
|
||||
sonar.issue.ignore.multicriteria.validate_py_paths.ruleKey=pythonsecurity:S8707
|
||||
sonar.issue.ignore.multicriteria.validate_py_paths.resourceKey=crates/validate/**/*.py
|
||||
|
||||
Reference in New Issue
Block a user