Compare commits

...
Author SHA1 Message Date
Dylan M. Taylor 97ee78977e fix(mailings): collapse delimiter counter guard 2026-11-15 10:15:08 -05:00
Dylan M. Taylor 3bf5520721 Mailings: bound delimiter storage and JSON serialization before allocation 2026-11-15 09:30:35 -05:00
Dylan M. Taylor 7221277ebe Mailings: refuse over-budget normalized recipients before padding or cloning 2026-11-15 09:28:33 -05:00
Mat Strange 9ac8dd94e1 Mailings: import bounded CSV parsing from #4055
Source: 0f84914edc. Preserve current multiline delimiter detection; integration follows separately.
2026-11-15 09:20:18 -05:00
Valentin Klein bc0e51ee4d Interface size: Auto is capped to what fits the screen, Ctrl+Shift+0 returns to Auto (#4030) (#5203)
Fixes #4030

On a small screen (an 11-inch 1366x768 panel) the system can report a very large display scale. The Auto interface size followed it blindly, so the window and ribbon came out far bigger than the screen and File > Options, where the size is set, could not be reached.

What this changes:
- Auto interface size is now capped so a window of at least 900x460 points still fits the screen (about 152% on 1366x768). Scales that already fit (for example 1920x1080 at 100-150%, or 1366x768 at up to 150%) are unchanged. If the screen size is unknown there is no cap.
- A size chosen in File > Options is still taken as is. If a large size pushes the options out of reach, Ctrl+Shift+0 (Cmd+Shift+0 on Mac) returns to Auto from anywhere. Ctrl+Alt+0 is not used because it is AltGr+0 on some layouts and would type a character.
- `ui.interfaceSize` and the "Auto (n%)" label in Options report the capped value. The cap is never saved to `ui.json`.
- Tests: the cap for several screen sizes, the shortcut, AltGr+0 still typing, and the reported percent. Docs: ui-parity, control-protocol, ROADMAP progress log.

Not covered:
- The root cause of the oversized scale (X11 DPI detection) is handled by #721 and #3240. This change is separate and works with or without them.
- A manually chosen large size can still push controls off screen, but there is now a way back.
- Not tested on a real 1366x768 screen.

`cargo xtask ci` passed locally on the pushed code; GitHub CI has not run yet.

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **New Features**
  * Auto interface sizing now scales down on smaller displays to keep a window of at least 900×460 points within the screen. Sizes selected in Options remain uncapped, and the minimum Auto scale is 100%.
  * Press Ctrl+Shift+0 (⌘⇧0 on Mac) to restore Auto sizing. When Auto sizing is capped, the displayed zoom percentage reflects the screen-fit limit; the cap does not change the saved size.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-15 12:12:27 +01:00
batistalucasv ed66198574 .gitattributes: normalise text on add so CRLF cannot be committed again (#6543)
`cargo fmt --check` passes on CRLF (verified: exit 0, empty output), so the gate cannot see a commit that rewrites line endings. `#6537` did exactly that: 50 files, 35,102 lines, all CRLF, while declaring a one-line test change.

## Change

Adds the normalisation the repository lacks — `.gitattributes` only pins `craft-i18n.rev` today:

```
# Text lives in the repository with LF. A Windows checkout once committed 50 files with CRLF
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
* text=auto

craft-i18n.rev text eol=lf
```

`craft-i18n.rev` stays last so the specific rule still wins.

## Dependency

The repair landed first: #6541 merged as `eae8363e`, and `git grep -lI $'\r'` on that head finds **0** text files. This branch merges that `main` in `01617884`, so the rule now applies to a tree that is already LF.

`text=auto` is not an absolute enforcement gate. It normalises text on add, and it does not rewrite a blob already stored with CRLF: plain `git add` on such a file leaves `git ls-files --eol` at `i/mixed`, and only `git add --renormalize` rewrites it to `i/lf`. That is why the repair had to land first, and why this is a guard for future commits, not a fix for the past.

## Why it is safe

- Every text file in `main` is already LF (`git grep -lI $'\r'` = 0).
- No `.bat`/`.cmd` or CRLF fixture exists; the `.ps1` files under `packaging/windows/` are already LF in the repository.
- `cargo fmt --check` clean and `cargo test -p wordcraft-engine --lib` 1460 passed, unchanged.

## Why two PRs

#6541 was the repair; this is the guard, and it is a repository policy change rather than part of the fix, so it is separate and optional. If a repo-wide rule is more than you want, the narrower form is one pattern per line:

```
*.rs text eol=lf
*.toml text eol=lf
*.md text eol=lf
*.properties text eol=lf
```

Thanks for the syntax correction: the single-line fallback I wrote earlier was not valid attribute syntax.

@FredApps — the dependency is settled and this branch is on the new `main`. Ready for approval when you have a moment.
2026-11-15 12:11:56 +01:00
Nine e9750c5cb7 Add Bosnian interface language (#4804)
Register Latin Bosnian as an interface language, with catalog-backed locale, plural and font regressions. Preserve the existing system-locale detector; POSIX script-modifier handling is outside this change.

Original contribution by @nine-codes.
2026-11-15 00:31:44 -06:00
3d5a153e3d Keep TOC entries for tab-numbered headings on one line (#6738)
Fixes #6486

Co-authored-by: cute-johnny <269855522+cute-johnny@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 02:23:52 +01:00
Mex 52d17a91df M14: identify WordCraft correctly in the iframe title example (#6717)
Use word processor as the accessible iframe description instead of image editor.
2026-11-14 21:40:06 +01:00
23 changed files with 771 additions and 63 deletions
+5 -1
View File
@@ -1 +1,5 @@
craft-i18n.rev text eol=lf
# Text lives in the repository with LF. A Windows checkout once committed 50 files with CRLF
# (#6537) and `cargo fmt --check` still passed, so the gate could not see it. Normalise on add.
* text=auto
craft-i18n.rev text eol=lf
+1 -1
View File
@@ -124,7 +124,7 @@ Every screenshot below is WordCraft itself, rendered offscreen by its own UI tes
| **References** | Table of contents, footnotes and endnotes, citations and bibliography (APA, MLA, Chicago, IEEE), captions, table of figures, cross-references, index, table of authorities |
| **Review** | Spelling and grammar with suggestions (English and Polish, by each run's language), thesaurus, word count, comments in margin balloons or a pane, track changes, accept/reject, compare documents, restrict editing, accessibility checker, document inspector |
| **Mailings** | Mail merge from CSV, merge fields, address block, greeting line, rules, preview, finish to a document; envelopes and labels |
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) or Slovenščina (follows the system language by default) |
| **View** | Print layout, web layout, draft, read mode, focus, zoom, one/multiple pages, page width, Navigation pane, rulers, gridlines, dark mode; interface in English, 简体中文, 繁體中文, 日本語, Português (Brasil), Español, Українська, Српски / Srpski, Eesti, Türkçe, Русский, Italiano, Deutsch, Polski, Čeština, Magyar, Français, Български, Tiếng Việt, 한국어, Svenska, Hrvatski, Nederlands, Dansk, Română, العربية (mirrored) Slovenščina or Bosanski (follows the system language by default) |
| **Files** | .docx read/write, legacy 97-2003 .doc import, PDF export, .odt, .rtf, .html, .md, .tex, .txt import/export, page images |
The honest picture, area by area, is in [ROADMAP.md](ROADMAP.md), the
+2 -1
View File
File diff suppressed because one or more lines are too long
+230 -36
View File
@@ -4,7 +4,7 @@ use super::{CmdError, CmdResult, Session, Value, json, p};
/// The field separator: whichever of `,` `;` and tab the first non-blank record (outside quotes) uses most.
fn csv_separator(text: &str) -> char {
let mut quoted = false;
let mut unquoted = String::new();
let mut counts = [0usize; 3];
// A quoted header may span physical lines; infer from the first complete record.
for c in text.split_inclusive(['\n', '\r']).skip_while(|line| line.trim().is_empty()).flat_map(str::chars) {
if c == '"' {
@@ -13,28 +13,42 @@ fn csv_separator(text: &str) -> char {
if c == '\n' || c == '\r' {
break;
}
unquoted.push(c);
if let Some(i) = [',', ';', '\t'].iter().position(|candidate| *candidate == c)
&& let Some(count) = counts.get_mut(i)
{
*count = count.saturating_add(1);
}
}
}
[',', ';', '\t'].into_iter().max_by_key(|c| unquoted.matches(*c).count()).unwrap_or(',')
[',', ';', '\t'].into_iter().zip(counts).max_by_key(|(_, count)| *count).map_or(',', |(c, _)| c)
}
/// Ends the current row: kept when it has any non-empty field, otherwise dropped.
fn push_csv_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>) {
if row.iter().any(|x| !x.is_empty()) {
rows.push(std::mem::take(row));
} else {
row.clear();
}
/// What a CSV may hold while it is read: the parser refuses a list that is over these, so a
/// hostile file is never built and then cut.
#[derive(Clone, Copy)]
pub struct CsvLimits {
/// Most columns in a record.
pub fields: usize,
/// Most cells in the list: its records times its widest record.
pub cells: usize,
/// Most bytes of cell text in all.
pub text: usize,
}
/// Parse CSV (RFC 4180-ish: quotes, doubled quotes, commas/semicolons/tabs).
pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
///
/// The limits are kept while the list is read, not after it: a record wider than
/// `limits.fields`, a list of more than `limits.cells` cells, or more than `limits.text` bytes
/// of cell text is refused, rather than built and then cut.
fn parse_csv_limited(text: &str, limits: &CsvLimits) -> Result<Vec<Vec<String>>, CmdError> {
let sep = csv_separator(text);
let mut rows = Vec::new();
let mut row = Vec::new();
let mut cell = String::new();
let mut q = false;
// The widest record read so far, and the bytes of cell text read so far.
let mut widest = 0usize;
let mut text_bytes = 0usize;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if q {
@@ -51,29 +65,86 @@ pub fn parse_csv(text: &str) -> Vec<Vec<String>> {
} else if c == '"' {
q = true;
} else if c == sep {
row.push(std::mem::take(&mut cell));
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
} else if c == '\n' || c == '\r' {
if c == '\r' && chars.peek() == Some(&'\n') {
chars.next();
}
row.push(std::mem::take(&mut cell));
push_csv_row(&mut rows, &mut row);
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
end_row(&mut rows, &mut row, &mut widest, limits)?;
} else {
cell.push(c);
}
if rows.len() > 100_000 {
break;
// The text read so far: the finished cells and the one being read.
if text_bytes.saturating_add(cell.len()) > limits.text {
return Err(CmdError::Failed(format!("the CSV can't have more than {} of text", text_size(limits.text))));
}
if rows.len() > MAX_RECORDS + 1 {
return Err(CmdError::Failed("the CSV has too many records".into()));
}
}
row.push(cell);
push_csv_row(&mut rows, &mut row);
rows
// The last cell, when the file doesn't end with a line break.
end_cell(&mut row, &mut cell, &mut text_bytes, limits)?;
end_row(&mut rows, &mut row, &mut widest, limits)?;
Ok(rows)
}
/// A finished cell joins the record: the record's width stays inside the limit.
fn end_cell(row: &mut Vec<String>, cell: &mut String, text_bytes: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> {
*text_bytes = text_bytes.saturating_add(cell.len());
row.push(std::mem::take(cell));
if row.len() > limits.fields {
return Err(CmdError::Failed(format!("the CSV can't have more than {} columns", limits.fields)));
}
Ok(())
}
/// A finished record joins the list (an empty one is dropped). The list costs its records times
/// its widest record — a recipient list pads every record to the header's width — so a list
/// over the limit is refused here, while it is read.
fn end_row(rows: &mut Vec<Vec<String>>, row: &mut Vec<String>, widest: &mut usize, limits: &CsvLimits) -> Result<(), CmdError> {
if row.iter().any(|x| !x.is_empty()) {
*widest = (*widest).max(row.len());
rows.push(std::mem::take(row));
} else {
row.clear();
}
if rows.len().saturating_mul(*widest) > limits.cells {
return Err(CmdError::Failed(format!("the CSV can't have more than {} cells (its records times its widest record)", limits.cells)));
}
Ok(())
}
/// A byte budget, said the way a reader says it.
fn text_size(bytes: usize) -> String {
if bytes >= 1 << 20 { format!("{} MB", bytes >> 20) } else { format!("{bytes} bytes") }
}
/// Most records and fields a recipient list keeps.
const MAX_RECORDS: usize = 100_000;
const MAX_FIELDS: usize = 1_000;
const MAX_CELLS: usize = 2_000_000;
const MAX_TEXT_BYTES: usize = 64 << 20;
const RECIPIENT_LIMITS: CsvLimits = CsvLimits { fields: MAX_FIELDS, cells: MAX_CELLS, text: MAX_TEXT_BYTES };
/// Refuse excessive CSV input instead of returning a silently truncated list.
pub fn parse_csv(text: &str) -> Result<Vec<Vec<String>>, CmdError> {
parse_csv_limited(text, &RECIPIENT_LIMITS)
}
// A sparse list is padded and cloned: charge its normalized shape BEFORE allocating it.
fn check_shape(records: usize, fields: usize, max_cells: usize) -> Result<(), CmdError> {
if records > MAX_RECORDS || fields > MAX_FIELDS || records.checked_mul(fields).is_none_or(|n| n > max_cells) {
return Err(CmdError::Failed("the recipient list exceeds its record, field or aggregate cell limit".into()));
}
Ok(())
}
fn spend_text(left: &mut usize, n: usize) -> Result<(), CmdError> {
*left = left.checked_sub(n).ok_or_else(|| CmdError::Failed("the recipient list exceeds its text budget".into()))?;
Ok(())
}
pub(super) fn cell(x: &Value) -> String {
match x {
@@ -83,11 +154,54 @@ pub(super) fn cell(x: &Value) -> String {
}
}
// Serialize non-string JSON cells through a bounded sink, not to_string() before charging.
fn budget_cell(value: &Value, left: &mut usize) -> Result<String, CmdError> {
match value {
Value::Null => Ok(String::new()),
Value::String(text) => {
spend_text(left, text.len())?;
Ok(text.clone())
}
_ => {
struct Sink {
bytes: Vec<u8>,
limit: usize,
}
impl std::io::Write for Sink {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
if bytes.len() > self.limit.saturating_sub(self.bytes.len()) {
return Err(std::io::Error::other("recipient text budget"));
}
self.bytes.try_reserve(bytes.len()).map_err(std::io::Error::other)?;
self.bytes.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut sink = Sink { bytes: Vec::new(), limit: *left };
serde_json::to_writer(&mut sink, value).map_err(|_| CmdError::Failed("the recipient list exceeds its text budget".into()))?;
spend_text(left, sink.bytes.len())?;
String::from_utf8(sink.bytes).map_err(|_| CmdError::Failed("invalid recipient text".into()))
}
}
}
/// A recipient table from `rows` (objects keyed by field, or arrays in `fields` order). Without
/// `fields`, the columns are the objects' keys.
fn table_from_rows(fields: Option<&Vec<Value>>, arr: &[Value]) -> Result<(Vec<String>, Vec<Vec<String>>), CmdError> {
let mut left = MAX_TEXT_BYTES;
let headers: Vec<String> = match fields {
Some(f) => f.iter().take(MAX_FIELDS).map(|h| cell(h).trim().to_string()).collect(),
Some(f) => {
check_shape(0, f.len(), MAX_CELLS)?;
let mut headers = Vec::new();
for h in f {
let text = budget_cell(h, &mut left)?.trim().to_string();
headers.push(text);
}
headers
}
None => {
if arr.iter().any(Value::is_array) {
return Err(CmdError::Params("`fields` is required when `rows` are arrays".into()));
@@ -95,7 +209,9 @@ fn table_from_rows(fields: Option<&Vec<Value>>, arr: &[Value]) -> Result<(Vec<St
let mut headers: Vec<String> = Vec::new();
for o in arr.iter().filter_map(Value::as_object) {
for k in o.keys() {
if !headers.contains(k) && headers.len() < MAX_FIELDS {
if !headers.contains(k) {
check_shape(0, headers.len().saturating_add(1), MAX_CELLS)?;
spend_text(&mut left, k.len())?;
headers.push(k.clone());
}
}
@@ -103,21 +219,34 @@ fn table_from_rows(fields: Option<&Vec<Value>>, arr: &[Value]) -> Result<(Vec<St
headers
}
};
let rows = arr
.iter()
.take(MAX_RECORDS)
.filter_map(|r| match r {
Value::Array(cells) => Some((0..headers.len()).map(|i| cells.get(i).map(cell).unwrap_or_default()).collect()),
Value::Object(o) => Some(headers.iter().map(|h| o.get(h).map(cell).unwrap_or_default()).collect()),
_ => None,
})
.collect();
let count = arr.iter().filter(|v| v.is_array() || v.is_object()).count();
check_shape(count, headers.len(), MAX_CELLS)?;
let mut rows = Vec::new();
for value in arr {
let mut row = Vec::new();
if !value.is_array() && !value.is_object() {
continue;
}
for (i, h) in headers.iter().enumerate() {
let v = match value {
Value::Array(a) => a.get(i),
Value::Object(o) => o.get(h),
_ => None,
};
let text = match v {
Some(v) => budget_cell(v, &mut left)?,
None => String::new(),
};
row.push(text);
}
rows.push(row);
}
Ok((headers, rows))
}
/// Skip unquoted blank prefix lines only when a text recipient list has a header.
/// Headerless lists and the shared CSV reader keep whitespace records.
fn recipient_csv(text: &str, headers: bool) -> Vec<Vec<String>> {
fn recipient_csv(text: &str, headers: bool) -> Result<Vec<Vec<String>>, CmdError> {
let prefix = text
.split_inclusive(['\n', '\r'])
.take_while(|line| headers && line.trim().is_empty())
@@ -131,7 +260,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
table_from_rows(v.get("fields").and_then(Value::as_array), arr)?
} else {
let all = if let Some(c) = p::str(v, "csv") {
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))
recipient_csv(c, p::bool(v, "headers").unwrap_or(true))?
} else {
let (bytes, ext) = if let Some(d) = p::str(v, "data") {
let b = crate::cmd::insert::base64_decode(d.trim()).ok_or_else(|| CmdError::Params("`data` isn't valid base64".into()))?;
@@ -188,7 +317,7 @@ pub(super) fn recipients(s: &mut Session, v: &Value) -> CmdResult {
sheet = json!(chosen);
rows
} else {
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))
recipient_csv(&decode(&bytes, v)?, p::bool(v, "headers").unwrap_or(true))?
}
};
header_split(all, p::bool(v, "headers").unwrap_or(true))?
@@ -243,14 +372,79 @@ fn header_split(mut all: Vec<Vec<String>>, headers: bool) -> Result<(Vec<String>
}
let fields = if headers {
let first = all.remove(0);
wordcraft_formats::sheet::field_names(&first[..first.len().min(MAX_FIELDS)])
check_shape(0, first.len(), MAX_CELLS)?;
wordcraft_formats::sheet::field_names(&first)
} else {
let width = all.iter().map(Vec::len).max().unwrap_or(0).min(MAX_FIELDS);
let width = all.iter().map(Vec::len).max().unwrap_or(0);
check_shape(0, width, MAX_CELLS)?;
(1..=width).map(|i| format!("Column {i}")).collect()
};
all.truncate(MAX_RECORDS);
check_shape(all.len(), fields.len(), MAX_CELLS)?;
let mut left = MAX_TEXT_BYTES;
for h in &fields {
spend_text(&mut left, h.len())?;
}
for row in &all {
for text in row.iter().take(fields.len()) {
spend_text(&mut left, text.len())?;
}
}
for r in &mut all {
r.resize(fields.len(), String::new());
}
Ok((fields, all))
}
#[cfg(test)]
mod budget_tests {
use super::*;
#[test]
fn sparse_rows_are_charged_at_their_padded_width() {
let limits = CsvLimits { fields: 3, cells: 8, text: 100 };
assert!(parse_csv_limited("a,b,c\nx\nx\n", &limits).is_err());
assert!(check_shape(3, 3, 8).is_err());
assert!(check_shape(2, 3, 6).is_ok());
assert!(check_shape(usize::MAX, usize::MAX, usize::MAX).is_err());
}
#[test]
fn width_text_and_record_limits_refuse_instead_of_truncating() {
let limits = CsvLimits { fields: 2, cells: 20, text: 4 };
assert!(parse_csv_limited("a,b,c", &limits).is_err());
assert!(parse_csv_limited("abcde", &limits).is_err());
assert!(parse_csv_limited("a\nb\n", &limits).is_ok());
assert!(parse_csv(&"x\n".repeat(MAX_RECORDS + 2)).is_err());
}
#[test]
fn rejected_csv_and_json_keep_the_existing_list() {
let mut session = Session::new(wordcraft_doc::Document::from_text("Hello"));
recipients(&mut session, &json!({"csv": "Name\nKeep"})).unwrap();
let fields: Vec<String> = (0..MAX_FIELDS).map(|i| format!("F{i}")).collect();
let count = MAX_CELLS / MAX_FIELDS + 1;
let csv = format!("{}\n{}", fields.join(","), "x\n".repeat(count));
assert!(recipients(&mut session, &json!({"csv": csv})).is_err());
let rows: Vec<Value> = (0..count).map(|_| json!({})).collect();
assert!(recipients(&mut session, &json!({"fields": fields, "rows": rows})).is_err());
assert_eq!(session.merge.headers, vec!["Name"]);
assert_eq!(session.merge.rows, vec![vec!["Keep"]]);
assert_eq!(session.merge.source, session.merge.rows);
}
#[test]
fn complex_json_text_is_bounded_during_serialization() {
let value = json!({"nested": ["abcdefgh", {"tail": true}]});
let mut left = 5;
assert!(budget_cell(&value, &mut left).is_err());
let mut left = 100;
let text = budget_cell(&value, &mut left).unwrap();
assert_eq!(text, value.to_string());
assert_eq!(left, 100 - text.len());
}
#[test]
fn delimiter_counting_preserves_ties_and_multiline_quotes() {
assert_eq!(csv_separator("A,B;C\n1,2;3"), ';');
assert_eq!(csv_separator("A;B\tC\n1;2\t3"), '\t');
assert_eq!(csv_separator("\n\"A,\nB\";C\nx;y"), ';');
let limits = CsvLimits { fields: 2, cells: 8, text: 4 };
assert!(parse_csv_limited(&"x".repeat(100_000), &limits).is_err());
}
}
+5
View File
@@ -1,5 +1,10 @@
use super::*;
// Keep existing delimiter/parity assertions exercising the now-fallible public parser.
fn parse_csv(text: &str) -> Vec<Vec<String>> {
super::parse_csv(text).unwrap()
}
#[test]
fn csv_parsing() {
let r = parse_csv("Name,City\n\"Smith, Ann\",Paris\r\nBo,\"Oslo \"\"N\"\"\"\n\n");
+25 -8
View File
@@ -67,13 +67,15 @@ pub fn toc_instr(v: &Value) -> String {
s
}
/// A TOC entry: the paragraph it points at, its level (0-based), its text, and the leading page
/// breaks of that paragraph (its page is where the text after them lands).
/// A TOC entry: the paragraph it points at, its level (0-based), its text, the leading page
/// breaks of that paragraph (its page is where the text after them lands), and, for a number
/// followed by a tab, how far the heading's text starts after where its number starts.
struct TocEntry {
path: Path,
level: u8,
text: String,
lead: usize,
number_gap: Option<f32>,
}
/// The headings of the body, in document order, as (body block, level 1–9, text, leading page
@@ -117,9 +119,13 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
.and_then(|n| counters.next_label(&s.doc.numbering, n.num, n.level))
.filter(|(label, def)| !label.is_empty() && !matches!(def.format, NumFormat::Bullet | NumFormat::None))
.map(|(label, def)| match def.suffix {
LevelSuffix::Tab => format!("{label}\t"),
LevelSuffix::Space => format!("{label} "),
LevelSuffix::Nothing => label,
LevelSuffix::Tab => {
let start = def.indent - def.hanging;
let gap = def.tab.filter(|t| *t > start).unwrap_or(def.indent) - start;
(format!("{label}\t"), Some(gap).filter(|g| g.is_finite() && *g > 0.0))
}
LevelSuffix::Space => (format!("{label} "), None),
LevelSuffix::Nothing => (label, None),
});
let style = p.props.style.as_deref().unwrap_or("Normal");
if style.starts_with("TOC") {
@@ -144,8 +150,9 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
if let Some(l) = by_style.or(by_outline).or(if hidden { None } else { by_heading }) {
let t = p.plain_text().replace(['\u{000C}', '\n', '\t'], " ").trim().to_string();
if !t.is_empty() {
let text = number.map_or_else(|| t.clone(), |n| format!("{n}{t}"));
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead });
let text = number.as_ref().map_or_else(|| t.clone(), |(n, _)| format!("{n}{t}"));
let number_gap = number.as_ref().and_then(|(_, g)| *g);
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead, number_gap });
}
}
if let Some(id) = &tc {
@@ -159,7 +166,7 @@ fn toc_entries(s: &Session, f: &FieldCode) -> Vec<TocEntry> {
let l = c.arg('l').and_then(|l| l.trim().parse::<u8>().ok()).unwrap_or(1).clamp(1, 9);
let text = c.args.first().map(|t| t.trim().to_string()).unwrap_or_default();
if (id.is_empty() || *id == kind) && (tc_levels.0..=tc_levels.1).contains(&l) && !text.is_empty() {
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off });
v.push(TocEntry { path: path.clone(), level: l - 1, text, lead: off, number_gap: None });
}
}
}
@@ -595,6 +602,16 @@ fn regenerate_toc(s: &mut Session, leader: Option<TabLeader>, tabs: &[(String, V
para.mark = CharProps::default();
if e.text.contains('\t') {
para.props.tabs = tabs.iter().find(|(style, _)| Some(style) == para.props.style.as_ref()).map(|(_, tabs)| tabs.clone());
// Without a stop for the number (LibreOffice's Contents styles have only the page
// number's right stop), its tab would run to the page number: the entry gets a
// left stop as far after its indent as the heading's text is after its number.
let style = s.doc.styles.resolve_para(&para.props);
let has_stop =
style.tabs.iter().any(|t| t.pos < width - 1.0 && matches!(t.align, TabAlign::Left | TabAlign::Center | TabAlign::Decimal));
if let (None, false, Some(gap)) = (&para.props.tabs, has_stop, e.number_gap) {
let pos = style.indent_left.max(0.0) + gap;
para.props.tabs = (pos < width - 1.0).then(|| vec![TabStop { pos, align: TabAlign::Left, leader: TabLeader::None }]);
}
}
if show_page && sep.contains('\t') {
let right = TabStop { pos: width - 0.5, align: TabAlign::Right, leader };
+1 -1
View File
@@ -348,7 +348,7 @@ pub(super) fn customize_ribbon(s: &mut Session, v: &Value) -> CmdResult {
pub(super) fn spreadsheet_rows(v: &Value) -> Result<Vec<Vec<String>>, CmdError> {
// The CSV fallback is for an absent `values`; an explicit null is a malformed argument.
let Some(values) = v.get("values") else {
return Ok(crate::cmd::mailings::parse_csv(p::str(v, "csv").unwrap_or("A,B,C\n1,2,3\n4,5,6")));
return crate::cmd::mailings::parse_csv(p::str(v, "csv").unwrap_or("A,B,C\n1,2,3\n4,5,6"));
};
let list = values.as_array().ok_or_else(|| CmdError::Params("`values` must be an array of rows".into()))?;
if list.is_empty() || list.len() > 1000 {
+55
View File
@@ -103,3 +103,58 @@ fn an_odt_bibliography_updates_from_its_citations_sources() {
assert!(text.iter().any(|t| t.contains("Kilns and Fire")), "{text:?}");
assert!(!text.iter().any(|t| t.contains("stale")), "{text:?}");
}
/// #6486: LibreOffice numbers headings through its outline style, the number followed by a tab,
/// and its Contents styles carry only the right-aligned dotted stop for the page number. After
/// Update Table, the tab after an entry's number stops near the number, not at the page-number
/// stop: the title stays at the left and each entry stays on one line.
#[test]
fn an_odt_toc_with_numbered_headings_keeps_its_entries_on_one_line() {
let outline = |level: u8, cm: f32| {
format!(
r#"<text:outline-level-style text:level="{level}" style:num-format="1" style:num-suffix="." text:display-levels="{level}"><style:list-level-properties text:list-level-position-and-space-mode="label-alignment"><style:list-level-label-alignment text:label-followed-by="listtab" text:list-tab-stop-position="{cm}cm" fo:text-indent="-{cm}cm" fo:margin-left="{cm}cm"/></style:list-level-properties></text:outline-level-style>"#
)
};
let contents = |n: u8, indent: f32| {
format!(
r#"<style:style style:name="Contents_20_{n}" style:display-name="Contents {n}" style:family="paragraph"><style:paragraph-properties fo:margin-left="{indent}cm"><style:tab-stops><style:tab-stop style:position="16.99cm" style:type="right" style:leader-style="dotted" style:leader-text="."/></style:tab-stops></style:paragraph-properties></style:style>"#
)
};
let styles = format!(
r#"<office:document-styles {NS}><office:styles>{}{}<text:outline-style style:name="Outline">{}{}</text:outline-style></office:styles><office:automatic-styles><style:page-layout style:name="pm1"><style:page-layout-properties fo:page-width="21.001cm" fo:page-height="29.7cm" fo:margin-left="2cm" fo:margin-right="2cm" fo:margin-top="2cm" fo:margin-bottom="2cm"/></style:page-layout></office:automatic-styles><office:master-styles><style:master-page style:name="Standard" style:page-layout-name="pm1"/></office:master-styles></office:document-styles>"#,
contents(1, 0.0),
contents(2, 0.499),
outline(1, 0.762),
outline(2, 1.016)
);
let content = format!(
r#"<office:document-content {NS}><office:body><office:text>
<text:table-of-content text:name="T"><text:table-of-content-source text:outline-level="2"/><text:index-body><text:p text:style-name="Contents_20_1">1. Planning<text:tab/>1</text:p><text:p text:style-name="Contents_20_2">1.1. Budget<text:tab/>1</text:p></text:index-body></text:table-of-content>
<text:h text:outline-level="1">Planning</text:h><text:p>Text.</text:p>
<text:h text:outline-level="2">Budget</text:h><text:p>More text.</text:p>
</office:text></office:body></office:document-content>"#
);
let mut z = craft_zip::Writer::new();
for (name, data) in [("mimetype", "application/vnd.oasis.opendocument.text"), ("styles.xml", styles.as_str()), ("content.xml", content.as_str())]
{
z.add(name, data.as_bytes(), craft_zip::Compression::Stored).unwrap();
}
let mut s = Session::new(io::open_bytes("toc.odt", &z.finish().unwrap()).unwrap());
s.run("references.updateToc", &json!({})).unwrap();
let layout = s.layout();
let mut checked = 0;
for (i, b) in s.doc.body.iter().enumerate() {
let Some(p) = b.as_para().filter(|p| p.props.style.as_deref().is_some_and(|st| st.starts_with("TOC") && st != "TOCHeading")) else {
continue;
};
let Some(tab) = p.text.find('\t') else { continue };
let pos = |off| wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path::top(i), off };
let title = layout.caret(&pos(tab + 1)).unwrap();
let end = layout.caret(&pos(p.len())).unwrap();
assert!(p.plain_text().contains("Planning") || p.plain_text().contains("Budget"), "{:?}", p.text);
assert_eq!((title.page, title.top), (end.page, end.top), "{:?} wraps", p.text);
assert!(title.x < 200.0, "{:?}: the title starts at {}", p.text, title.x);
checked += 1;
}
assert_eq!(checked, 2);
}
+30 -1
View File
@@ -131,6 +131,8 @@ impl WordApp {
fonts_frames: 0,
applied_theme: None,
native_scale: 1.0,
auto_scale_limit: f32::INFINITY,
monitor_zoom: 1.0,
legacy_interface_size: None,
// Inert until the app binary calls `watch_desktop_theme`.
desktop_theme: desktop_theme::DesktopTheme::default(),
@@ -301,7 +303,25 @@ impl WordApp {
{
self.ui.interface_size = theme::migrate_legacy_interface_size(old, native);
}
let zoom = self.ui.interface_size.zoom_factor(self.native_scale);
// Auto never draws larger than the screen holds (#4030): a system that guesses 3× on a
// 1366x768 panel would put the window's controls off screen. The zoom is shared by every
// window, so the smallest screen of all the open windows sets the cap. A viewport's
// `monitor_size` is in points of the zoom in force before a pending change applied, so
// its pixels are that size times `monitor_zoom` and the window's own native scale; each window's allowed zoom is its own, the smallest is shared.
let monitors: Vec<_> = self
.windows
.viewport_ids()
.into_iter()
.filter_map(|v| {
ctx.input_for(v, |i| {
let info = i.viewport();
Some(((info.monitor_size?.x, info.monitor_size?.y), info.native_pixels_per_point?))
})
})
.collect();
self.auto_scale_limit = theme::auto_scale_limit_over(monitors, self.monitor_zoom, self.native_scale);
self.monitor_zoom = ctx.zoom_factor();
let zoom = self.ui.interface_size.zoom_factor_within(self.native_scale, self.auto_scale_limit);
if ctx.zoom_factor() != zoom {
ctx.set_zoom_factor(zoom);
}
@@ -410,6 +430,15 @@ impl WordApp {
/// Pane's Tab keys and dropped files are read in the first UI pass
/// ([`WordApp::handle_ui_input_events`]).
pub(crate) fn window_input(&mut self, ctx: &egui::Context) {
// The way back when a large interface size has pushed File › Options off screen (#4030).
// A modal dialog keeps the keys (Customize Keyboard records them), and a command the user
// bound to the chord runs instead.
if !self.modal_open()
&& self.session.keymap.resolve(&self.session.registry, "Mod+Shift+0").is_none()
&& ctx.input_mut(super::consume_reset_interface_size)
{
let _ = self.run("ui.interfaceSize", serde_json::json!({"value": "auto"}));
}
if self.windows.native() && ctx.input_mut(|i| i.consume_shortcut(&QUIT)) {
self.quit();
}
+1 -1
View File
@@ -667,7 +667,7 @@ impl WordApp {
}
}
let size = self.ui.interface_size;
json!({"auto": size.is_auto(), "percent": size.drawn_percent(self.native_scale)})
json!({"auto": size.is_auto(), "percent": size.drawn_percent_within(self.native_scale, self.auto_scale_limit)})
}
"ui.animations" => {
// `system` (follow the system's animation setting), `on` or `off`; no value reads
+4 -1
View File
@@ -70,7 +70,7 @@ pub struct LangInfo {
/// The languages WordCraft offers, when their catalogs are embedded. English first: it is the
/// fallback and the source language.
pub static LANGUAGES: [LangInfo; 28] = [
pub static LANGUAGES: [LangInfo; 29] = [
LangInfo { code: "en", prefer_hans: false, editing_lang: None },
// Simplified Chinese; `zh`, `zh-CN`, `zh-SG` and `zh-Hans-*` resolve here (the crate's matching).
LangInfo { code: "zh-hans", prefer_hans: true, editing_lang: None },
@@ -129,6 +129,9 @@ pub static LANGUAGES: [LangInfo; 28] = [
LangInfo { code: "ar", prefer_hans: false, editing_lang: None },
// Slovenian; `sl`, `sl-SI` and `sl_SI.UTF-8` resolve here.
LangInfo { code: "sl", prefer_hans: false, editing_lang: None },
// Bosnian, Latin script; `bs`, `bs-BA`, `bs_BA.UTF-8` and `bs-Latn-BA` resolve here. Cyrillic
// Bosnian (`bs-Cyrl-*`) has no catalog, so it stays in English.
LangInfo { code: "bs", prefer_hans: false, editing_lang: None },
];
/// Interface languages written right to left. Their catalogs are written in typing order and
+69
View File
@@ -1143,6 +1143,75 @@ fn bundled_interface_fonts_cover_slovenian_letters() {
assert!(!lang("sl").uses_cjk());
}
/// Bosnian (Latin script) follows `bs-BA` system locales and a saved choice, and choosing it leaves
/// the document as it was. Cyrillic Bosnian has no catalog: a script is never crossed.
#[test]
fn bosnian_locales_and_saved_preference_work_without_changing_the_document() {
needs_catalogs!();
let bs = lang("bs");
for tag in ["bs", "bs-BA", "bs_BA.UTF-8", "BS-ba", "bs-Latn-BA"] {
assert_eq!(lang_from_tag(tag), Some(bs), "{tag}");
}
assert_eq!(lang_from_tag("bs-Cyrl-BA"), None, "Cyrillic Bosnian has no catalog");
assert_eq!(first_supported([UNSUPPORTED, "bs-BA", "en-US"]), Some(bs));
let mut app = crate::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let before = serde_json::to_value(&app.session.doc).unwrap();
let result = app.run("ui.language", serde_json::json!({"value": "BS"})).unwrap();
assert_eq!(result["effective"], "bs");
assert_eq!(app.ui.language, "bs");
assert!(result["available"].as_array().unwrap().iter().any(|l| l["code"] == "bs" && l["name"] == "Bosanski"));
assert_eq!(serde_json::to_value(&app.session.doc).unwrap(), before);
let saved = serde_json::to_string(&app.ui).unwrap();
let restored: crate::UiState = serde_json::from_str(&saved).unwrap();
assert_eq!(Lang::from_pref(&restored.language), bs);
assert_eq!(bs.editing_lang(), None, "WordCraft doesn't proof Bosnian, so documents stay in its default");
assert!(!bs.uses_cjk());
}
/// Bosnian counts take CLDR's three forms through the embedded catalog: `one` for 1, 21, 101 (not
/// 11), `few` for 2–4, 22–24 (not 12–14) and `other` for the rest.
#[test]
fn bosnian_plurals_take_one_few_other() {
needs_catalogs!();
let bs = lang("bs");
let count = |n| I18N.trn_plain(bs.lang, n, "{n} item", "{n} items");
for (n, want) in [
(1, "1 stavka"),
(21, "21 stavka"),
(101, "101 stavka"),
(2, "2 stavke"),
(4, "4 stavke"),
(22, "22 stavke"),
(0, "0 stavki"),
(5, "5 stavki"),
(11, "11 stavki"),
(12, "12 stavki"),
(14, "14 stavki"),
(111, "111 stavki"),
] {
assert_eq!(count(n), want, "{n}");
}
}
/// The bundled interface faces draw every Bosnian letter (č ć đ š ž), every other accented letter
/// the catalog uses, and its punctuation, without a system fallback.
#[test]
fn bundled_interface_fonts_cover_bosnian_letters() {
let db = wordcraft_fonts::FontDb::with_font_dirs(Vec::new());
needs_catalogs!();
let extra = ['č', 'ć', 'đ', 'š', 'ž', 'Č', 'Ć', 'Đ', 'Š', 'Ž', '„', '”', '–', '…'];
// Every accented Latin letter the catalog uses (Latin-1 and Latin Extended-A), and the above.
let accented = |c: &char| ('\u{C0}'..='\u{17F}').contains(c) && c.is_alphabetic();
let chars: std::collections::HashSet<char> = translations("bs").iter().flat_map(|e| e.chars()).filter(accented).chain(extra).collect();
for (family, style) in [("Inter", "Regular"), ("Inter", "Medium"), ("Inter", "SemiBold"), ("JetBrains Mono", "Regular")] {
let face = db.face(family, style);
assert_eq!(face.family, family, "must use the bundled interface face");
for ch in &chars {
assert_ne!(face.glyph_for(*ch), 0, "{family} {style} lacks {ch}");
}
}
}
/// The "Open" paragraph-spacing preset is roomy spacing, not the file verb: only a `spacing` row
/// translates it.
#[test]
+24
View File
@@ -449,6 +449,24 @@ pub const DEFAULT_TAB: &str = "Home";
/// ⌘Q, which only the Mac sends: quit.
const QUIT: egui::KeyboardShortcut = egui::KeyboardShortcut::new(egui::Modifiers::MAC_CMD, egui::Key::Q);
/// Ctrl+Shift+0 (⌘⇧0): back to the Auto interface size (#4030). Not Ctrl+Alt+0, which is AltGr+0
/// on some layouts and types a character there (#3424).
const RESET_INTERFACE_SIZE: egui::KeyboardShortcut =
egui::KeyboardShortcut::new(egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), egui::Key::Num0);
/// Consume Ctrl+Shift+0 (⌘⇧0), matched on the key the layout types and exactly these modifiers.
/// Where Shift+0 types `=` (German, Swiss and Nordic layouts) the press is Ctrl+Shift+=, which
/// stays Superscript; an extra Alt (AltGr+Shift+0) doesn't match.
fn consume_reset_interface_size(input: &mut egui::InputState) -> bool {
let mut found = false;
input.events.retain(|e| {
let hit = matches!(e, egui::Event::Key { key: egui::Key::Num0, pressed: true, modifiers, .. }
if modifiers.matches_exact(RESET_INTERFACE_SIZE.modifiers));
found |= hit;
!hit
});
found
}
/// Most recent documents kept (File › Options › Advanced offers 0–50, as Word does).
pub const MAX_RECENT: usize = 50;
/// Most custom dictionary words read back from `ui.json`.
@@ -730,6 +748,12 @@ pub struct WordApp {
/// The display scale (native pixels per point) seen in the last frame, 1.0 before the first;
/// `ui.interfaceSize` reports the size Auto draws at with it.
native_scale: f32,
/// The most pixels per point Auto may draw at on this screen ([`theme::auto_scale_limit`], #4030).
auto_scale_limit: f32,
/// The zoom factor in force during the previous frame's `logic`: egui-winit turns each
/// window's monitor size into points with the zoom of the frame before a pending change is
/// applied, so the physical size is that size times this zoom ([`theme::auto_scale_limit_over`]).
monitor_zoom: f32,
/// A pre-#822 interface size (percent on top of the display scale) waiting for the first frame
/// that knows the display's scale, to become the absolute size it drew at
/// ([`theme::migrate_legacy_interface_size`]).
+2 -2
View File
@@ -771,8 +771,8 @@ fn interface_size_picker(app: &mut WordApp, ui: &mut Ui) {
let native = ui.ctx().native_pixels_per_point().unwrap_or(1.0);
// The template keeps the percent sign outside its placeholder, so `fmt` isolates the number
// without it and a right-to-left line draws "(%200)": the sign goes inside the isolate.
let auto = crate::i18n::fmt(tl!("Auto ({percent}%)"), &[("percent", &InterfaceSize::AUTO.drawn_percent(native).to_string())])
.replace("\u{2069}%", "%\u{2069}");
let drawn = InterfaceSize::AUTO.drawn_percent_within(native, app.auto_scale_limit);
let auto = crate::i18n::fmt(tl!("Auto ({percent}%)"), &[("percent", &drawn.to_string())]).replace("\u{2069}%", "%\u{2069}");
let selected = size.percent().map_or_else(|| auto.clone(), |pct| format!("{pct}%"));
ui.horizontal(|ui| {
let label = ui.label(tl!("Interface size:"));
+183
View File
@@ -6220,6 +6220,189 @@ fn interface_size_survives_an_unusable_display_scale() {
assert_eq!(InterfaceSize::AUTO.drawn_percent(f32::MAX), u16::MAX);
}
/// #4030: a system that reports a huge scale (an 11-inch 1366x768 panel on X11) must not make Auto
/// draw an interface larger than the screen holds; the controls stay on screen.
#[test]
fn auto_interface_size_is_capped_to_what_fits_the_screen() {
use theme::{AUTO_MIN_POINTS, InterfaceSize, auto_scale_limit};
let limit = auto_scale_limit(Some((1366.0, 768.0)));
assert!((1.0..1.6).contains(&limit), "{limit}");
// Scales that fit are left as the system reports them.
for (screen, natives) in [((1920.0, 1080.0), [1.0, 1.25, 1.5]), ((1366.0, 768.0), [1.0, 1.25, 1.5])] {
let limit = auto_scale_limit(Some(screen));
for native in natives {
assert_eq!(f32::from(InterfaceSize::AUTO.drawn_percent_within(native, limit)), native * 100.0, "{screen:?} {native}");
}
}
assert!((auto_scale_limit(Some((1920.0, 1080.0))) - 2.13).abs() < 0.01);
for native in [2.0, 3.17] {
let drawn = f32::from(InterfaceSize::AUTO.drawn_percent_within(native, limit)) / 100.0;
assert!(1366.0 / drawn >= AUTO_MIN_POINTS.0 - 3.0 && 768.0 / drawn >= AUTO_MIN_POINTS.1 - 3.0, "{native}: {drawn}");
}
// A scale that already fits, an unknown screen and junk are left alone.
assert_eq!(InterfaceSize::AUTO.drawn_percent_within(1.25, limit), 125);
assert_eq!(auto_scale_limit(None), f32::INFINITY);
assert_eq!(auto_scale_limit(Some((f32::NAN, 768.0))), f32::INFINITY);
assert_eq!(InterfaceSize::AUTO.drawn_percent_within(3.0, auto_scale_limit(None)), 300);
// A screen below the minimum is never scaled under 100 %; a 4K screen at 2x is untouched.
assert_eq!(auto_scale_limit(Some((640.0, 480.0))), 1.0);
assert_eq!(InterfaceSize::AUTO.drawn_percent_within(2.0, auto_scale_limit(Some((3840.0, 2160.0)))), 200);
// A chosen size is the user's and is not capped.
assert_eq!(InterfaceSize::from_percent(300.0).unwrap().drawn_percent_within(3.0, limit), 300);
}
/// #4030: the zoom is shared, so the smallest screen of all the open windows caps Auto, and a
/// monitor size made with the zoom before a change still gives the same physical screen.
#[test]
fn auto_cap_follows_the_smallest_window_screen_and_the_zoom_of_its_points() {
use theme::auto_scale_limit_over;
let small = auto_scale_limit_over([((1366.0, 768.0), 1.0)], 1.0, 1.0);
let large = auto_scale_limit_over([((3840.0, 2160.0), 1.0)], 1.0, 1.0);
assert!(small < large);
assert_eq!(auto_scale_limit_over([((3840.0, 2160.0), 1.0), ((1366.0, 768.0), 1.0)], 1.0, 1.0), small);
// A 1366x768 panel at native scale 3: the points are 455x256 at zoom 1, 304x171 at zoom 1.5.
// The pixels, and so the cap, don't depend on which zoom made the points.
let a = auto_scale_limit_over([((1366.0 / 3.0, 768.0 / 3.0), 3.0)], 1.0, 3.0);
let b = auto_scale_limit_over([((1366.0 / 4.5, 768.0 / 4.5), 3.0)], 1.5, 3.0);
assert!((a - b).abs() < 1e-4 && (a - small).abs() < 1e-4, "{a} {b} {small}");
assert_eq!(auto_scale_limit_over([], 1.0, 1.0), f32::INFINITY);
}
/// #4030: with a 1x window on a large screen and a 3x window on a 1366x768 panel, the shared zoom
/// is the one the 3x window needs, so both windows draw within their own screen.
#[test]
fn auto_cap_keeps_every_window_within_its_own_screen_when_scales_differ() {
use theme::{AUTO_MIN_POINTS, InterfaceSize, auto_scale_limit, usable_scale};
let windows = [((3840.0, 2160.0), 1.0_f32), ((1366.0 / 3.0, 768.0 / 3.0), 3.0)];
for root in [1.0_f32, 3.0] {
let limit = theme::auto_scale_limit_over(windows, 1.0, root);
let zoom = InterfaceSize::AUTO.zoom_factor_within(root, limit);
for ((w, h), own) in windows {
let pixels_per_point = usable_scale(own) * zoom;
let (px_w, px_h) = (w * own, h * own);
assert!(pixels_per_point <= auto_scale_limit(Some((px_w, px_h))) + 1e-4, "root {root}, window {own}: {pixels_per_point}");
assert!(
px_w / pixels_per_point >= AUTO_MIN_POINTS.0 - 1.0 && px_h / pixels_per_point >= AUTO_MIN_POINTS.1 - 1.0,
"root {root}, window {own}"
);
}
}
}
/// #4030: the cap shows in `ui.interfaceSize` and is never saved; Ctrl+Shift+0 returns to Auto
/// while Ctrl+Alt+0 (AltGr+0, which types `}` on a German layout) neither resets nor swallows it.
#[cfg(not(target_os = "macos"))]
#[test]
fn reset_interface_size_shortcut_and_capped_report() {
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app(),
);
for _ in 0..6 {
h.step();
}
{
let a = h.state_mut();
a.native_scale = 3.0;
a.auto_scale_limit = 1.5;
assert_eq!(a.run("ui.interfaceSize", json!({})).unwrap(), json!({"auto": true, "percent": 150}));
assert!(!serde_json::to_string(&a.ui).unwrap().contains("150"), "the cap is not saved");
a.run("ui.interfaceSize", json!({"percent": 300})).unwrap();
}
let altgr = egui::Modifiers { alt: true, ctrl: true, shift: false, mac_cmd: false, command: true };
h.event(egui::Event::Key { key: egui::Key::Num0, physical_key: None, pressed: true, repeat: false, modifiers: altgr });
h.event(egui::Event::ModifiersChanged(altgr));
h.event(egui::Event::Text("}".into()));
h.step();
assert_eq!(h.state().ui.interface_size.percent(), Some(300), "AltGr+0 doesn't reset");
assert_eq!(h.state().session.doc.plain_text(wordcraft_doc::StoryRef::Body), "}", "AltGr+0 types the character");
let chord = egui::Modifiers { alt: false, ctrl: true, shift: true, mac_cmd: false, command: true };
h.event(egui::Event::Key { key: egui::Key::Num0, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: chord });
h.step();
assert!(h.state().ui.interface_size.is_auto(), "Ctrl+Shift+0 returns to Auto");
// AltGr+Shift+0, where the layout leaves the key a zero, doesn't reset either.
h.state_mut().run("ui.interfaceSize", json!({"percent": 300})).unwrap();
let altgr_shift = egui::Modifiers { alt: true, ctrl: true, shift: true, mac_cmd: false, command: true };
h.event(egui::Event::Key { key: egui::Key::Num0, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: altgr_shift });
h.step();
assert_eq!(h.state().ui.interface_size.percent(), Some(300), "AltGr+Shift+0 doesn't reset");
// With File › Options open, the place a too-large size pushes off screen, the chord resets.
h.state_mut().run("ui.backstage", json!({"value": true})).unwrap();
h.state_mut().ui.backstage_page = "options".into();
h.step();
h.event(egui::Event::Key { key: egui::Key::Num0, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: chord });
h.step();
assert!(h.state().ui.interface_size.is_auto(), "Ctrl+Shift+0 returns to Auto from File › Options");
// A modal dialog keeps the keys: Customize Keyboard records the chord instead.
h.state_mut().run("ui.backstage", json!({"value": false})).unwrap();
h.state_mut().run("ui.interfaceSize", json!({"percent": 300})).unwrap();
h.state_mut().run("ui.dialog", json!({"name": "customizeKeyboard"})).unwrap();
h.step();
h.event(egui::Event::Key { key: egui::Key::Num0, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: chord });
h.step();
assert_eq!(h.state().ui.interface_size.percent(), Some(300), "no reset while a modal dialog is open");
}
/// #4030 review: where Shift+0 types `=` (German, Swiss and Nordic layouts) egui-winit reports `=`
/// as the key and the zero only as the physical key. That press is Ctrl+Shift+=, Superscript, as
/// on main; it doesn't reset the interface size.
#[cfg(not(target_os = "macos"))]
#[test]
fn ctrl_shift_equals_on_the_zero_key_stays_superscript() {
let mut a = app();
a.run("document.setText", json!({"text": "x"})).unwrap();
a.run("select.all", json!({})).unwrap();
a.run("ui.interfaceSize", json!({"percent": 300})).unwrap();
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
for _ in 0..6 {
h.step();
}
let chord = egui::Modifiers { alt: false, ctrl: true, shift: true, mac_cmd: false, command: true };
h.event(egui::Event::Key { key: egui::Key::Equals, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: chord });
h.step();
assert_eq!(h.state().ui.interface_size.percent(), Some(300), "Ctrl+Shift+= doesn't reset");
let pos = wordcraft_doc::Pos { story: wordcraft_doc::StoryRef::Body, path: wordcraft_doc::Path::top(0), off: 0 };
let props = h.state().session.doc.para_at(&pos).map(|p| p.props_of_char(0).clone()).unwrap_or_default();
assert_eq!(props.vert_align, Some(wordcraft_doc::props::VertAlign::Superscript), "Ctrl+Shift+= runs Superscript");
}
/// #4030 review: a Ctrl+Shift+0 the user binds in Customize Keyboard runs their command instead
/// of resetting the interface size.
#[cfg(not(target_os = "macos"))]
#[test]
fn a_bound_ctrl_shift_0_beats_the_interface_size_reset() {
let mut a = app();
a.run("ui.interfaceSize", json!({"percent": 300})).unwrap();
a.session.keymap = wordcraft_engine::keymap::KeyMap::from_value(&json!({"assigned": {"Mod+Shift+0": "view.focus"}}));
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
a,
);
for _ in 0..6 {
h.step();
}
let chord = egui::Modifiers { alt: false, ctrl: true, shift: true, mac_cmd: false, command: true };
h.event(egui::Event::Key { key: egui::Key::Num0, physical_key: Some(egui::Key::Num0), pressed: true, repeat: false, modifiers: chord });
h.step();
assert_eq!(h.state().ui.interface_size.percent(), Some(300), "the size stays");
assert!(h.state().session.view.focus_mode, "the user's binding runs");
}
/// #115: System follows the OS appearance (light when unknown); the manual choices ignore it.
#[test]
fn interface_theme_resolves_against_the_os_appearance() {
+41 -1
View File
@@ -125,11 +125,51 @@ impl InterfaceSize {
/// The size the interface is drawn at on that display, in percent (screen pixels per point × 100).
pub fn drawn_percent(self, native: f32) -> u16 {
let drawn = usable_scale(native) * self.zoom_factor(native) * 100.0;
self.drawn_percent_within(native, f32::INFINITY)
}
/// [`InterfaceSize::zoom_factor`] on a screen that [`auto_scale_limit`] caps at `limit` pixels
/// per point: Auto never draws larger than that.
pub fn zoom_factor_within(self, native: f32, limit: f32) -> f32 {
match self.0 {
None => (limit / usable_scale(native)).min(1.0),
Some(_) => self.zoom_factor(native),
}
}
/// [`InterfaceSize::drawn_percent`] within [`auto_scale_limit`]'s cap.
pub fn drawn_percent_within(self, native: f32, limit: f32) -> u16 {
let drawn = usable_scale(native) * self.zoom_factor_within(native, limit) * 100.0;
drawn.round().clamp(0.0, f32::from(u16::MAX)) as u16
}
}
/// The smallest window, in points, the interface is laid out for under Auto.
pub const AUTO_MIN_POINTS: (f32, f32) = (900.0, 460.0);
/// The largest pixels-per-point Auto may draw at on a screen of `screen_px` pixels (#4030): the
/// one that still leaves [`AUTO_MIN_POINTS`], so the ribbon and the window's controls stay on
/// screen. Never below 1.0, and unlimited when the screen size is unknown.
pub fn auto_scale_limit(screen_px: Option<(f32, f32)>) -> f32 {
screen_px
.filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0)
.map_or(f32::INFINITY, |(w, h)| (w / AUTO_MIN_POINTS.0).min(h / AUTO_MIN_POINTS.1).max(1.0))
}
/// [`auto_scale_limit`] for the several windows that share one zoom, expressed as pixels per point
/// at the scale `native` (the one [`InterfaceSize::zoom_factor_within`] divides by). Each window
/// is a monitor size in points and its own native scale; `zoom` is the zoom factor those points
/// were made with, so the size in pixels is the three multiplied. Every window must stay within
/// its own screen, so the allowed zoom is worked out per window and the smallest one is shared.
/// Unlimited when no screen is known.
pub fn auto_scale_limit_over(monitors: impl IntoIterator<Item = ((f32, f32), f32)>, zoom: f32, native: f32) -> f32 {
let shared_zoom = monitors
.into_iter()
.map(|((w, h), own)| auto_scale_limit(Some((w * zoom * own, h * zoom * own))) / usable_scale(own))
.fold(f32::INFINITY, f32::min);
shared_zoom * usable_scale(native)
}
/// The display's scale, or 1.0 when egui doesn't know it (or reports nonsense).
pub fn usable_scale(native: f32) -> f32 {
if native.is_finite() && native > 0.0 { native } else { 1.0 }
+2
View File
@@ -196,6 +196,8 @@ impl WordApp {
fonts_frames: _,
applied_theme: _,
native_scale: _,
auto_scale_limit: _,
monitor_zoom: _,
legacy_interface_size: _,
desktop_theme: _,
desktop_dark: _,
+12
View File
@@ -187,6 +187,18 @@ impl Windows {
}
}
/// The viewports the open windows draw in, the root's included.
pub(crate) fn viewport_ids(&self) -> Vec<ViewportId> {
let mut ids = vec![ViewportId::ROOT];
for w in &self.open {
let v = self.viewport(w.key);
if !ids.contains(&v) {
ids.push(v);
}
}
ids
}
/// The title View › Window › Switch Windows gives the window, as the frame started.
fn menu_title(&self, key: u64) -> Option<&str> {
self.menu.title(self.get(key)?.id?)
+1 -1
View File
@@ -84,7 +84,7 @@ let apps move windows, so there Arrange All and Side by Side only resize.
| Method | Params | Result |
|---|---|---|
| `engine.execute` | `command`, `params`, `doc?` | the command's result (any id from `engine.commands`, including UI commands `ui.tab`, `ui.dialog` (`{"name": dialog, "part"?: table style part}`; `part` opens New / Modify Table Style (`newTableStyle` / `modifyTableStyle`) on that part: `wholeTable`, `headerRow`, `firstColumn`, `bandedRows`, `nwCell`… as `table.modifyStyle` names them), `ui.backstage`, `ui.zotero.*` (see `docs/zotero.md`), `ui.language` (`{"value": "auto"\|"en"\|"zh-hans"\|"zh-hant"\|"ja"\|"pt-br"\|"es"\|"uk"\|"sr"\|"sr-latn"\|"et"\|"tr"\|"ru"\|"pl"\|"de"\|"it"\|"cs"\|"hu"\|"fr"}`), `ui.theme` (`{"value": "system"\|"light"\|"dark"}`; `system` follows the OS appearance, light when it reports none), `ui.interfaceSize` (`{"value": "auto"}` or `{"percent": 50–300}`, clamped; no value reads it; `auto` keeps the system display scale, a percentage is absolute, so 100 is one screen pixel per point (#822); the result's `percent` is the size drawn at and `auto` whether it follows the system; document zoom stays `view.zoom`), `ui.animations` (`{"value": "system"\|"on"\|"off"}`; no value reads it; `system` follows the system's animation setting, which the desktop app reads on Windows, macOS, Linux and the BSDs and the web app from `prefers-reduced-motion`, and means on where the system doesn't say; the result's `enabled` is what the setting comes to and `system` what the system reports, `null` when it doesn't say), `ui.fileBrowser` (desktop: `{"purpose": "document"\|"picture"\|"recipients"\|"save"}` opens WordCraft's own file browser, for when the system file dialog doesn't show up, #576), `ui.saveAsTemplate` (File › Save As › Save as Word Template: the Save dialog for a `.dotx`, starting in the user templates folder; the result's `dir` is that folder, `null` on the web, #2852), `ui.caretAnimation` (`{"value": true\|false}`; no value reads it; off, the caret jumps and blinks on and off instead of gliding and fading), `ui.startScreen` (`{"value": true\|false}`; no value reads it; on, the default, the desktop and web apps start on File › Home when launched with nothing to open, #766), `ui.alignmentGuides` (`{"value": true\|false}`; no value reads it; on, the default, moving a picture or shape snaps it to the page, the margins and other objects, with guide lines while dragging; Alt moves freely), `ui.quickAccessToolbar` (`{"value": true\|false}`; no value toggles it; false takes the Quick Access Toolbar out of the title bar, as its menu's Hide Quick Access Toolbar does, and true brings it back, #1945), `ui.displayServer` (`{"value": "auto"\|"wayland"\|"x11"}`; no value reads it; File › Options › Advanced › Linux display server, which the desktop app reads on Linux and the BSDs at its next launch; `WORDCRAFT_WAYLAND` overrides it, #2184), `ui.scrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; mouse-wheel scroll speed, #6146), `ui.touchpadScrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; scales touchpad scrolling on Wayland: slow 2×, normal 4×, fast 8×; on macOS: 0.5×, 1×, 2×; File › Options › Advanced › Scrolling › Touchpad scroll speed, #6146), `ui.statusCount` (`{"value": "words"\|"characters"\|"charactersNoSpaces"}`; no value reads it; what the status bar's count shows — words (the default), characters with spaces, or characters without spaces — kept between runs, #2797), `ui.recentRemove` (`{"path": entry}` takes that document off the recent list — `path` must be an entry on the list; on the desktop the new list is saved right away: the result's `saved` is true then, false with `saveError` when the write failed (the removal still holds for this run) and null where the host keeps no preferences (the web app, or preferences switched off), #2716), `ui.recentClear` (`{}` clears the whole list; the result reports `removed`, the new `recent` and `saved` as above), `ui.focusRibbon` (`{"value": true\|false}`; no value toggles it; in Focus, true drops the ribbon down over the page, as the bar's ⋯ does, and false puts it away, as a click on the page does; outside Focus it stays put away, #1678), `ui.contextMenu` (opens the page's context menu below the caret, as Shift+F10 does), `ui.paneDock` (`{"pane": "navigation"\|"clipboard"\|"styles"\|"styleInspector"\|"accessibility"\|"altText"\|"formatShape"\|"restrictEditing"\|"comments"\|"smartArtText", "dock"?: "left"\|"right"\|"float", "before"?: pane\|null}`; no `dock` reads it; docks or floats a task pane as its menu does, kept between runs; Styles is `view.stylesPaneDock`, #1756; `before` puts the pane directly before that pane in the order, outside it on their edge, as a drop over a docked pane's outer third does, and `null` after every pane; the order is kept between runs)…) |
| `engine.execute` | `command`, `params`, `doc?` | the command's result (any id from `engine.commands`, including UI commands `ui.tab`, `ui.dialog` (`{"name": dialog, "part"?: table style part}`; `part` opens New / Modify Table Style (`newTableStyle` / `modifyTableStyle`) on that part: `wholeTable`, `headerRow`, `firstColumn`, `bandedRows`, `nwCell`… as `table.modifyStyle` names them), `ui.backstage`, `ui.zotero.*` (see `docs/zotero.md`), `ui.language` (`{"value": "auto"\|"en"\|"zh-hans"\|"zh-hant"\|"ja"\|"pt-br"\|"es"\|"uk"\|"sr"\|"sr-latn"\|"et"\|"tr"\|"ru"\|"pl"\|"de"\|"it"\|"cs"\|"hu"\|"fr"}`), `ui.theme` (`{"value": "system"\|"light"\|"dark"}`; `system` follows the OS appearance, light when it reports none), `ui.interfaceSize` (`{"value": "auto"}` or `{"percent": 50–300}`, clamped; no value reads it; `auto` keeps the system display scale, capped so a window of at least 900x460 points fits the screen (#4030), a percentage is absolute, so 100 is one screen pixel per point (#822); the result's `percent` is the size drawn at and `auto` whether it follows the system; document zoom stays `view.zoom`), `ui.animations` (`{"value": "system"\|"on"\|"off"}`; no value reads it; `system` follows the system's animation setting, which the desktop app reads on Windows, macOS, Linux and the BSDs and the web app from `prefers-reduced-motion`, and means on where the system doesn't say; the result's `enabled` is what the setting comes to and `system` what the system reports, `null` when it doesn't say), `ui.fileBrowser` (desktop: `{"purpose": "document"\|"picture"\|"recipients"\|"save"}` opens WordCraft's own file browser, for when the system file dialog doesn't show up, #576), `ui.saveAsTemplate` (File › Save As › Save as Word Template: the Save dialog for a `.dotx`, starting in the user templates folder; the result's `dir` is that folder, `null` on the web, #2852), `ui.caretAnimation` (`{"value": true\|false}`; no value reads it; off, the caret jumps and blinks on and off instead of gliding and fading), `ui.startScreen` (`{"value": true\|false}`; no value reads it; on, the default, the desktop and web apps start on File › Home when launched with nothing to open, #766), `ui.alignmentGuides` (`{"value": true\|false}`; no value reads it; on, the default, moving a picture or shape snaps it to the page, the margins and other objects, with guide lines while dragging; Alt moves freely), `ui.quickAccessToolbar` (`{"value": true\|false}`; no value toggles it; false takes the Quick Access Toolbar out of the title bar, as its menu's Hide Quick Access Toolbar does, and true brings it back, #1945), `ui.displayServer` (`{"value": "auto"\|"wayland"\|"x11"}`; no value reads it; File › Options › Advanced › Linux display server, which the desktop app reads on Linux and the BSDs at its next launch; `WORDCRAFT_WAYLAND` overrides it, #2184), `ui.scrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; mouse-wheel scroll speed, #6146), `ui.touchpadScrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; scales touchpad scrolling on Wayland: slow 2×, normal 4×, fast 8×; on macOS: 0.5×, 1×, 2×; File › Options › Advanced › Scrolling › Touchpad scroll speed, #6146), `ui.statusCount` (`{"value": "words"\|"characters"\|"charactersNoSpaces"}`; no value reads it; what the status bar's count shows — words (the default), characters with spaces, or characters without spaces — kept between runs, #2797), `ui.recentRemove` (`{"path": entry}` takes that document off the recent list — `path` must be an entry on the list; on the desktop the new list is saved right away: the result's `saved` is true then, false with `saveError` when the write failed (the removal still holds for this run) and null where the host keeps no preferences (the web app, or preferences switched off), #2716), `ui.recentClear` (`{}` clears the whole list; the result reports `removed`, the new `recent` and `saved` as above), `ui.focusRibbon` (`{"value": true\|false}`; no value toggles it; in Focus, true drops the ribbon down over the page, as the bar's ⋯ does, and false puts it away, as a click on the page does; outside Focus it stays put away, #1678), `ui.contextMenu` (opens the page's context menu below the caret, as Shift+F10 does), `ui.paneDock` (`{"pane": "navigation"\|"clipboard"\|"styles"\|"styleInspector"\|"accessibility"\|"altText"\|"formatShape"\|"restrictEditing"\|"comments"\|"smartArtText", "dock"?: "left"\|"right"\|"float", "before"?: pane\|null}`; no `dock` reads it; docks or floats a task pane as its menu does, kept between runs; Styles is `view.stylesPaneDock`, #1756; `before` puts the pane directly before that pane in the order, outside it on their edge, as a drop over a docked pane's outer third does, and `null` after every pane; the order is kept between runs)…) |
| `engine.commands` | — | every command: id, label, location, shortcut, params, enabled |
| `document.inspect` | `text?`, `doc?` | blocks (text, style, runs, lists, tables), parts, sections, selection, pages |
| `ui.inspect` | — | UI state, view, dialog, window size, page rects on screen, caret, comment balloons (`balloons`: id + screen rect; `balloon`: the selected one), perf; `windows`: the other windows as the drawn window sees them (`available`, `others`, `sideBySide`, `syncScroll`); `document`: the active document's id; `documents`: the open documents (`id`, `title`, `path`, `dirty`, `active`) |
+67
View File
@@ -0,0 +1,67 @@
# Bosnian interface
> **Last reviewed:** 2026-10-29 · **Last updated:** 2026-10-29 · **Change:** major (first version) · **Target:** WordCraft 0.7.0
Choose **File › Options › Interface language › Bosanski**, or follow a Bosnian system display
language (`bs-BA`, `bs_BA.UTF-8`, `bs-Latn-BA`). The catalog code is `bs`; `ui.language` with
`{"value":"bs"}` selects it explicitly, and `WORDCRAFT_LANGUAGE=bs-BA` does the same for a headless
screenshot or a launch while the preference is `auto`. Document text, command ids, CLI/MCP/control
responses and file paths do not change.
The catalog is craft-i18n's `locales/bs/wordcraft.tsv` (storytold/craft-i18n, 2,508 entries) over the
shared `locales/bs/common.tsv`. Both are embedded from the
craft-i18n commit pinned in `craft-i18n.rev` (1e51542…), which includes them. The
catalog is written from the meaning of the English labels; no proprietary translation resources were
consulted. It is an AI-assisted draft that a native speaker has not yet reviewed.
## Conventions
- Latin script, ijekavian, standard Bosnian vocabulary where the neighbouring languages differ:
*historija*, *sačuvaj*, *tačka*, *hiljada*, *sedmica*, *datoteka*, *postavke*. Cyrillic Bosnian
(`bs-Cyrl-*`) has no catalog and stays in English.
- Commands and buttons use the imperative (`Sačuvaj`, `Umetni fusnotu`, `Prihvati`); ribbon groups
and panes are nouns (`Pasus`, `Stilovi`, `Navigacijsko okno`).
- Messages address the user with the polite plural (`Unesite lozinku`).
- Only the first word of a label is capitalised.
- `@plural` rows use Bosnian's three CLDR forms, `one|few|other` (`{n} stavka|{n} stavke|{n}
stavki`); the `craft-i18n` crate picks the form from CLDR's rules.
- Quotation marks „…”; placeholders, a trailing `…` and the spaces around joined fragments match the
English.
## Terminology
| Source | Bosnian |
|---|---|
| File / Home / Insert / Draw / Design / Layout | Datoteka / Početna / Umetni / Crtaj / Dizajn / Raspored |
| References / Mailings / Review / View / Help | Reference / Pošiljke / Pregled izmjena / Prikaz / Pomoć |
| Font / Paragraph / Styles | Font / Pasus / Stilovi |
| Header / Footer / Heading | Zaglavlje / Podnožje / Naslov |
| Footnotes / Endnotes / Caption | Fusnote / Krajnje bilješke / Natpis |
| Table of Contents / Index | Sadržaj / Indeks |
| Citations / Citation Style / Bibliography | Citati / Stil citiranja / Bibliografija |
| Track Changes / Accept / Reject | Praćenje promjena / Prihvati / Odbij |
| Comment / Show Markup | Komentar / Prikaži oznake |
| Mail Merge | Spajanje pošte |
| Sections / Section Break | Odjeljci / Prelom odjeljka |
| Undo / Redo | Poništi / Ponovi |
| Ribbon / Navigation Pane / Quick Access Toolbar | Traka / Navigacijsko okno / Traka za brzi pristup |
| Bold / Italic / Underline / Strikethrough | Podebljano / Kurziv / Podvučeno / Precrtano |
| Hyphenation | Rastavljanje riječi |
| Watermark | Vodeni žig |
| Save / Save As / Open / Print | Sačuvaj / Sačuvaj kao / Otvori / Štampaj |
| Read Mode | Način čitanja |
| Text Box | Okvir za tekst |
## Verification and remaining scope
Tests in `crates/ui-egui/src/i18n/tests.rs` check locale selection (Cyrillic Bosnian excluded), the
saved preference, that choosing Bosnian leaves the document unchanged, and the bundled fonts'
coverage of č, ć, đ, š, ž and the catalog's punctuation. The shared checks (catalog validation and
the missing-translation report, `cargo xtask i18n-report`) include Bosnian automatically. Bosnian
spelling, grammar and hyphenation are not included. Native speaker review is welcome.
## Revision history
| Date | Change | Summary |
|---|---|---|
| 2026-10-29 | major | First version: Bosnian (`bs`) interface language, conventions and terminology |
+7 -5
View File
@@ -1,6 +1,6 @@
# Localization parity with Microsoft Word
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** trivial (Arabic: the Home tab's Styles gallery reads from the right, its arrows at the left (#5566); readiness unchanged); previously trivial (table sort and formulas read the Panamanian balboa's `B/.` around a number (`B/. 1,250.50`, `1,250.50 B/.`), as Word does, matched only at the ends of the text so `1/.5` stays a fraction); previously trivial (Arabic: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously minor (Options › Language redesign: Your languages, Add a language…, Set as default; the Dictionaries folder moved from Proofing); previously trivial (Language packs: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (Language lists: every installed and available Language pack's language can be chosen in Set Proofing Language, installed ones in Review › Language and the status bar; craft-i18n.rev at 9d6d54d: region names and the Language (Region) template in 35 locales, craft-i18n#145); previously trivial (craft-i18n.rev at cde4900: rows for Options › Language, the missing-pack bar and 28 Language pack language names in 35 locales, craft-i18n#136); previously trivial (craft-proof pin: French elision suggestions first, ca-ES-valencia reads the ca-valencia pack); previously minor (Arabic `ar` interface: craft-i18n catalog, mirrored shell, font fallback, #1195; 28 languages); previously trivial (Language packs: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland)); previously trivial (Language packs: language-packs-1 is published and pinned, 61 packs; the language requests it covers); previously minor (Language packs: languages beyond English install their spelling dictionary and hyphenation as a pack from File › Options › Language or the missing-pack bar; the default build embeds English Language data only) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Bosnian interface: `bs` in the language list, `bs-BA` system locales, catalog in storytold/craft-i18n); previously trivial (Arabic: the Home tab's Styles gallery reads from the right, its arrows at the left (#5566); readiness unchanged); previously trivial (table sort and formulas read the Panamanian balboa's `B/.` around a number (`B/. 1,250.50`, `1,250.50 B/.`), as Word does, matched only at the ends of the text so `1/.5` stays a fraction); previously trivial (Arabic: the dialogs of the mirrored Arabic interface read right to left: label-and-field rows, tables (list columns, the Models table), tile galleries and the Add/Remove arrows follow the reading direction, through one `rtl::Table` helper that draws exactly as before in English; no ranked gap closed, readiness estimates unchanged); previously minor (Options › Language redesign: Your languages, Add a language…, Set as default; the Dictionaries folder moved from Proofing); previously trivial (Language packs: the missing-pack bar works on a fresh install and counts the caret's language); previously trivial (Language lists: every installed and available Language pack's language can be chosen in Set Proofing Language, installed ones in Review › Language and the status bar; craft-i18n.rev at 9d6d54d: region names and the Language (Region) template in 35 locales, craft-i18n#145); previously trivial (craft-i18n.rev at cde4900: rows for Options › Language, the missing-pack bar and 28 Language pack language names in 35 locales, craft-i18n#136); previously trivial (craft-proof pin: French elision suggestions first, ca-ES-valencia reads the ca-valencia pack); previously minor (Arabic `ar` interface: craft-i18n catalog, mirrored shell, font fallback, #1195; 28 languages); previously trivial (Language packs: language-packs-2 is published and pinned: 75 packs, adding Danish, German (Germany, Austria, Switzerland), Esperanto, Estonian, Persian, Croatian, Hungarian, Norwegian (Bokmål, Nynorsk), Dutch and Swedish (Sweden, Finland)); previously trivial (Language packs: language-packs-1 is published and pinned, 61 packs; the language requests it covers); previously minor (Language packs: languages beyond English install their spelling dictionary and hyphenation as a pack from File › Options › Language or the missing-pack bar; the default build embeds English Language data only) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4
Interface languages, script support and proofing per language. How translation works (adding a
language, the embedded catalogs): `crates/ui-egui/src/i18n.rs`. The catalogs, their format and
@@ -21,8 +21,8 @@ native-speaker review (human).
## What WordCraft ships (measured)
- **28 interface languages**: English plus `zh-hans`, `zh-hant`, `ja`, Korean `ko` (#1216), `uk`, `es`, `pt-br`,
Serbian `sr`/`sr-latn` (#250), Estonian `et`, Turkish `tr`, Russian `ru`, Italian `it` (#594), German `de` (#574), Polish `pl`, Czech `cs`, Hungarian `hu`, French `fr`, Bulgarian `bg`, Vietnamese `vi` (#1434), Swedish `sv` (#1219), Croatian `hr` (#1271), Romanian `ro`, Slovenian `sl`, Dutch `nl`, Danish `da` (#2722) and Arabic `ar` (#1195). Catalogs have 2,061–2,730 entries
- **29 interface languages**: English plus `zh-hans`, `zh-hant`, `ja`, Korean `ko` (#1216), `uk`, `es`, `pt-br`,
Serbian `sr`/`sr-latn` (#250), Estonian `et`, Turkish `tr`, Russian `ru`, Italian `it` (#594), German `de` (#574), Polish `pl`, Czech `cs`, Hungarian `hu`, French `fr`, Bulgarian `bg`, Vietnamese `vi` (#1434), Swedish `sv` (#1219), Croatian `hr` (#1271), Romanian `ro`, Slovenian `sl`, Dutch `nl`, Danish `da` (#2722) Arabic `ar` (#1195) and Bosnian `bs`. Catalogs have 2,061–2,730 entries
each; Polish has every key of every other catalog, including the built-in style names and the equation gallery, except the citation style names only Hungarian, Bulgarian, Swedish, Romanian and Slovenian translate so far. A missing translation falls back to English and never fails a test or
build. `cargo xtask i18n-report`, part of `cargo xtask ci`, prints per language the interface
strings its catalog lacks: everything the interface audit saw looked up, the ribbon tabs, command
@@ -72,8 +72,8 @@ shared items below.
| Vietnamese | vi | 2,448 entries; every key of the reference catalogs (#1434); 98% of extracted, ~95% of visible | most | Latin ✅ | no | partial | 0–1 (review) |
| Romanian | ro | 2,674 entries; every key of the other catalogs; AI-assisted draft | most | Latin ✅ (ă â î ș ț in the bundled faces) | no | partial | 0–1 (review) |
Other shipped languages: **20** — Traditional Chinese (`zh-hant`), Ukrainian (`uk`), Serbian
Cyrillic and Latin (`sr`, `sr-latn`, #250), Estonian (`et`), Turkish (`tr`), Russian (`ru`), Italian (`it`, #594), Polish (`pl`), Czech (`cs`), Hungarian (`hu`), French (`fr`), Bulgarian (`bg`), Vietnamese (`vi`, #1434), Swedish (`sv`, #1219), Croatian (`hr`, #1271), Romanian (`ro`), Slovenian (`sl`), Dutch (`nl`) and Danish (`da`, #2722), all partial.
Other shipped languages: **21** — Traditional Chinese (`zh-hant`), Ukrainian (`uk`), Serbian
Cyrillic and Latin (`sr`, `sr-latn`, #250), Estonian (`et`), Turkish (`tr`), Russian (`ru`), Italian (`it`, #594), Polish (`pl`), Czech (`cs`), Hungarian (`hu`), French (`fr`), Bulgarian (`bg`), Vietnamese (`vi`, #1434), Swedish (`sv`, #1219), Croatian (`hr`, #1271), Romanian (`ro`), Slovenian (`sl`), Dutch (`nl`), Danish (`da`, #2722) and Bosnian (`bs`), all partial.
Swedish (`sv-SE` and `sv-FI` system locales, `{"value":"sv"}`) has 2,504 entries. Counts use
count-neutral wording (`{words} ord`: the noun is the same in the singular and the plural). The
catalog is an AI-assisted draft whose terminology and running app were reviewed by a native
@@ -97,6 +97,7 @@ hyphenated by the Bulgarian syllable rules (#826); Bulgarian spelling and gramma
Slovenian (`sl-SI` system locales, `{"value":"sl"}`) has 2,614 entries: every key of every other
catalog. Counts use count-neutral wording (`Besede: 21`); terminology: [`localization-sl.md`](localization-sl.md).
Slovenian proofing is not included.
Bosnian (`bs-BA` system locales, `{"value":"bs"}`) is Latin script; Cyrillic Bosnian stays in English. Its craft-i18n catalog has 2,508 WordCraft entries plus the shared catalog, with `one|few|other` plural rows. The catalog is an AI-assisted draft not yet reviewed by a native speaker; Bosnian proofing is not included; terminology: [`localization-bs.md`](localization-bs.md).
Hungarian follows `hu-HU` system locales and `{"value":"hu"}`, with a complete catalog of 2,419 entries: every key of
the Russian catalog, built-in style names shown translated, plus the citation style names. Hungarian proofing is not included; terminology and conventions:
[`localization-hu.md`](localization-hu.md).
@@ -275,6 +276,7 @@ WordCraft keeps 2,54 cm).
| Date | Change | Summary |
|---|---|---|
| 2026-10-29 | minor | Bosnian interface (`bs`, Latin script): listed in `LANGUAGES`, `bs-BA` system locales, saved preference and bundled-font tests; catalog in storytold/craft-i18n (`locales/bs/wordcraft.tsv`); no Bosnian proofing |
| 2026-11-06 | trivial | Arabic: the Home tab's Styles gallery reads from the right: Normal is the rightmost tile and the scroll arrows and More sit at the gallery's left end, as the rest of the mirrored ribbon (#5566); left to right is unchanged; regression test `the_styles_gallery_reads_from_the_right_in_a_right_to_left_interface` |
| 2026-11-05 | trivial | Arabic letters join across a change of formatting and past hidden or deleted text (#4093) |
| 2026-11-04 | trivial | Table sort and formulas read the Panamanian balboa's `B/.` around a number (`B/. 1,250.50`, `1,250.50 B/.`), as Word does; `B/.1,250.50` and `B/ 1,250.50` stay text, matching Word 16.0, and the sign is matched only at the ends of the text, so `1/.5` is unchanged |
+3 -2
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -55,7 +55,7 @@ Local test: `python3 -m http.server 8765` inside the folder, then open http://lo
```html
<iframe
src="https://example.com/wordcraft/"
title="WordCraft image editor"
title="WordCraft word processor"
style="width: 100%; height: 720px; border: 0;"
allow="fullscreen; clipboard-read; clipboard-write"
allowfullscreen>