From d4b4c1631167525462683281dd387d82633df045 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 11:51:44 -0500 Subject: [PATCH 01/18] S00: prove the Sonnet highlighter and freeze the spelling adapter - probe: ui/tests/qml/tst_spellcheck_probe.qml (+ SpellcheckProbe.qml) attaches the real Sonnet highlighter through an optional Loader and checks UTF-16 offsets, suggestions, ignore scope, disabling, and undo-safe correction - decision: planning/decisions/S00.md freezes the adapter interface and raises two findings that need supervisor sign-off: misspelledColor is inert (the underline is always Qt's fixed red), and addWordToDictionary writes the global Hunspell dictionary, so personal words must be app-owned and applied via ignoreWord - state: S00 marked READY FOR REVIEW --- planning/STATE.md | 2 +- planning/decisions/S00.md | 174 ++++++++++++++++++++++++++ ui/tests/qml/SpellcheckProbe.qml | 41 ++++++ ui/tests/qml/tst_spellcheck_probe.qml | 115 +++++++++++++++++ 4 files changed, 331 insertions(+), 1 deletion(-) create mode 100644 planning/decisions/S00.md create mode 100644 ui/tests/qml/SpellcheckProbe.qml create mode 100644 ui/tests/qml/tst_spellcheck_probe.qml diff --git a/planning/STATE.md b/planning/STATE.md index 9827ad7..956e7dd 100644 --- a/planning/STATE.md +++ b/planning/STATE.md @@ -23,7 +23,7 @@ Updated: 2026-09-29. This file records facts; planned actions are not completed | Task | State | Accepted candidate / evidence | | --- | --- | --- | | F00 | ACCEPTED | `880d410`; [evidence](evidence/F00.md), [judgment](https://github.com/latentoperator/omamail/pull/1) | -| S00 | READY FOR ASSIGNMENT | F00 accepted at `880d410` | +| S00 | READY FOR REVIEW — awaiting supervisor sign-off | `planning/decisions/S00.md` (base `d88833e`); probe `ui/tests/qml/tst_spellcheck_probe.qml` | | S01 | WAITING FOR S00 | — | | S02 | WAITING FOR S01 | — | | S03 | WAITING FOR S02 | — | diff --git a/planning/decisions/S00.md b/planning/decisions/S00.md new file mode 100644 index 0000000..9ba40d5 --- /dev/null +++ b/planning/decisions/S00.md @@ -0,0 +1,174 @@ +# S00 decision — spelling adapter contract + +Status: **READY FOR REVIEW** (supervisor sign-off required). Task: S00. Base: `d88833e` +(main after F00 acceptance). Host: HMSP-ARCHYXPS, Qt 6.11.2, Sonnet 6.29.0, +`hunspell-en_us` installed (see `planning/evidence/F00.md`). + +This record proves the real Sonnet QML runtime behaviour the spelling adapter +depends on, and freezes the adapter's interface. Two behaviours are not what the +project plan assumed; they are raised as decisions (§5) rather than worked around +silently. No production file was changed: the only additions are the probe under +`ui/tests/qml/` and this record. + +## 1. What was proven + +Runtime evidence comes from `ui/tests/qml/tst_spellcheck_probe.qml` and +`ui/tests/qml/SpellcheckProbe.qml` (8/8 pass through the real harness: +`python3 tests/run_qml_native.py /usr/lib/qt6/bin/qmltestrunner -input +ui/tests/qml/tst_spellcheck_probe.qml`) plus the throwaway probes recorded in §6. + +| Fact | Result | +| --- | --- | +| Module and dictionary | `org.kde.sonnet` loads; `spellCheckerFound=true`; default `currentLanguage=en_US` (the installed dictionary) | +| Attachment | A `SpellcheckHighlighter` binds to `TextEdit.textDocument` (a `QQuickTextDocument`); `TextField` has no such document, so the subject needs a one-line `TextEdit` (S03) | +| Suggestions | `suggestions(position, max)` returns up to `max` suggestions for the word at a **UTF-16 code-unit position**; a surrogate-pair emoji before the word does not shift it (`"ok 🙂 wrod"` → `wrod` at 6, first suggestion `word`) | +| Word lookup | `isWordMisspelled(word)` is independent of `active` and of the cursor | +| Ignore | `ignoreWord(word)` is session-only and **process-global**: ignoring in one composer also ignores in another | +| Personal word | `addWordToDictionary(word)` writes the **global** `$HOME/.hunspell_` file (observed writing `zzyzx` to `~/.hunspell_en_US`) | +| Disable | `active=false` removes underlines without changing the document text | +| Optional load | A `Loader` whose source imports `org.kde.sonnet` reaches `Loader.Ready`; a source importing a missing module reaches `Loader.Error` with the rest of the app running | +| Missing language | `setCurrentLanguage("zz_ZZ")`/`"fr_FR"` reverts to the previous language and leaves `spellCheckerFound=false` until a later successful `setCurrentLanguage` | +| Undo | A primed correction is undone by the editor's normal `undo()` | + +## 2. Two Sonnet defects the adapter must not trip over + +Both were confirmed against the installed 6.29.0 plugin and its source +(`src/quick/spellcheckhighlighter.cpp`). + +### 2.1 `replaceWord` uses a stale word length (must prime with `suggestions`) + +`replaceWord(replacement, at)` selects the word under `at` but then anchors the +replacement by `d->selectedWord.size()` — the word remembered by the last +`suggestions()` call — instead of the word it just selected. With no prior +`suggestions(at, …)` it inserts instead of replacing: + +``` +no prior suggestions: replaceWord("word", 6) -> "ok 📨 wordwrod and …" (inserted) +after suggestions(6): replaceWord("word", 6) -> "ok 📨 word and …" (replaced) +stale from another word: suggestions(3) then replaceWord(…, 10) -> corrupts a different word +``` + +**Frozen rule:** the adapter calls `suggestions(position, 0)` and +`replaceWord(replacement, position)` as one indivisible step for the same +position. `suggestions(position, 0)` primes the length without returning a list. + +### 2.2 `misspelledColor` has no effect on the underline + +`setMisspelledColor()` stores the colour but never rebuilds the `errorFormat` +built in the constructor, and the constructor forces the default to `Qt::red`. +The rendered underline is therefore **always red**, whatever `misspelledColor` +reads back as (verified: setting green both before and after `document`, and +imperatively, still renders `#FF0000`). See §5 decision D1. + +## 3. Frozen adapter interface + +Provisional file `ui/compose/SpellcheckAdapter.qml`, created by S01 and always +loaded through a `Loader` so the `org.kde.sonnet` import stays optional. Names +below are frozen for S01–S03; a later change is a contract change, not a detail. + +**Inputs** + +| Property | Type | Meaning | +| --- | --- | --- | +| `document` | `QQuickTextDocument` | the editor's `textDocument`; `null` before the editor exists | +| `enabled` | `bool` | user setting; false clears underlines and queries | +| `language` | `string` | desired language, default `en_US` | +| `personalWords` | `list` | app-owned words to treat as correct (see §4) | + +**Outputs** + +| Property | Type | Meaning | +| --- | --- | --- | +| `available` | `bool` | Sonnet loaded **and** the requested language is available | +| `loaded` | `bool` | the optional component instantiated (distinguishes "no Sonnet" from "no dictionary") | +| `status` | `string` | one of `ready`, `no-module`, `no-dictionary`, `disabled` for the setup explanation | + +**Functions** + +| Function | Returns | Notes | +| --- | --- | --- | +| `inspect(position)` | `{word, misspelled, suggestions}` | calls `suggestions(position, 5)`, then reads `wordUnderMouse`/`wordIsMisspelled`; **do not** infer "correct" from an empty list — a misspelled word can have no suggestions | +| `suggestionList(position)` | `list` | at most five, matching `inspect` | +| `applyCorrection(position, replacement)` | `void` | the primed `suggestions`+`replaceWord` pair of §2.1; undo-safe | +| `ignoreForSession(word)` | `void` | `ignoreWord`; process-global session scope | +| `setPersonalWords(words)` | `void` | re-applies the app-owned list (see §4) | + +**Position handling.** Positions are UTF-16 code-unit offsets into the same +`QQuickTextDocument` the editor uses, so a position taken from +`TextEdit.positionAt(x, y)` or `cursorPosition` is the same coordinate +`suggestions()` expects. The adapter never computes word bounds itself: the word +under a position and whether it is misspelled come from `wordUnderMouse` and +`wordIsMisspelled` after an `inspect()` call. + +**Document lifecycle.** `document` may be `null` at construction (the editor is +created with the composer). The adapter binds `document` and re-applies +`enabled`, `language`, and `personalWords` whenever it changes; it must not +`rehighlight()` during the change itself. + +## 4. Personal words and ignore scope + +`addWordToDictionary` writes the user's global Hunspell dictionary, which S6 +forbids ("persisted in private app settings rather than modifying global Sonnet +preferences"). **Frozen rule:** the application owns the personal word list and +persists it in its own settings; the adapter applies every personal word with +`ignoreWord`, which is session-only. Personal words therefore survive a restart +because the app re-applies them, and the user's global dictionary is never +touched. "Ignore for this session" and a personal word are the same mechanism +with different persistence. Both are process-global, which matches S6's +"current application process/session" wording and makes all composers agree. + +## 5. Escalations — supervisor decision required + +**D1 — underline colour cannot come from the theme (S5).** S5 requires the +underline colour to come from a semantic theme role via `misspelledColor`. It +cannot: the property is inert (§2.2) and Qt renders `SingleUnderline` in the +format's colour, which is fixed red. Options: (a) accept the fixed red as a +functional affordance and record the deviation from the no-literal-colour rule; +(b) draw an own underline over the text (the plan warns against "hand-drawn +underlines" and a second engine); (c) accept red for v1 and revisit if Qt/Sonnet +exposes a working colour. Recommendation: **(a)** — it is Qt's own spell-check +affordance, not an app colour choice, and `tests/test_source.sh` only forbids +literal colours in app source, which this is not. + +**D2 — personal-word persistence (§4).** Confirm the app-owned-list model +(apply via `ignoreWord`) instead of `addWordToDictionary`, since the latter +writes the global dictionary. Recommendation: **confirm**. + +**D3 — correction path (§2.1).** Confirm relying on Sonnet's `replaceWord` with +the priming rule, rather than replacing text through the editor's own +`remove`/`insert`. Recommendation: **confirm**, because it is undo-safe and keeps +Sonnet's own word-trimming (leading/trailing apostrophes) consistent with the +suggestions it offered. If the supervisor prefers editor-level replacement, that +is a contract change to freeze here. + +## 6. Evidence + +Committed probe (runs in `make test-qml`, skips where Sonnet/en_US is absent): + +``` +python3 tests/run_qml_native.py /usr/lib/qt6/bin/qmltestrunner -input ui/tests/qml/tst_spellcheck_probe.qml +# Totals: 8 passed, 0 failed +bash tests/test_source.sh && python3 tests/test_qml_names.py && python3 tests/test_qml_text_format.py +# all ok +``` + +Screenshots (synthetic text, kept out of Git history under the gitignored +`planning/local/s00/`): `underline-en_us.png` (red underlines under `recieve` +and `attachement` in otherwise-correct text), `misspelledColor-is-inert.png` +(green requested, red rendered), `automatic-on-mostly-invalid.png`. Regenerate +with any probe that calls `grabImage(item)` and `img.save(path)` under +`QT_QPA_PLATFORM=offscreen`; the underline is confirmed by counting `#FF0000` +pixels with `magick … -format %c histogram:info:-`. + +Throwaway probes that produced the tables above (not committed) covered: the +UTF-16 offset sweep, the `replaceWord` at/prime matrix, the missing-module +`Loader`, `setCurrentLanguage` on absent languages, and the automatic-mode +mostly-invalid text case (12 misspelled words, still checked with +`automatic` true or false; the adapter pins `automatic:false` regardless). + +## 7. What S01 must do next + +Create `ui/compose/SpellcheckAdapter.qml` implementing §3–§4, load it through a +`Loader` in `ComposeView.qml`, pass the body `TextEdit.textDocument`, and add the +body-only tests S01 lists. Subject support (S03) and the context menu (S02) are +out of scope here. diff --git a/ui/tests/qml/SpellcheckProbe.qml b/ui/tests/qml/SpellcheckProbe.qml new file mode 100644 index 0000000..75ea349 --- /dev/null +++ b/ui/tests/qml/SpellcheckProbe.qml @@ -0,0 +1,41 @@ +import QtQuick +import org.kde.sonnet as Sonnet + +// S00 probe component: the only file under tests/ that imports org.kde.sonnet. +// It is loaded through a Loader so a machine without the module reports a +// loader error to the probe instead of failing the whole test file to import. +// +// The adapter the real feature will use is provisional; this exists to prove +// the runtime behaviour the adapter must rely on. See planning/decisions/S00.md. +Item { + id: probe + + // The TextEdit whose text document is checked. Set by the caller after the + // Loader has created the item. + property var editor: null + + readonly property bool available: highlighter.spellCheckerFound + readonly property string language: highlighter.currentLanguage + + // Whether underlines are drawn. Independent of the query functions. + property alias active: highlighter.active + property alias automatic: highlighter.automatic + + //Suggestions for the word at a UTF-16 character position in the document. + function suggestionsAt(position, max) { return highlighter.suggestions(position, max) } + function isMisspelled(word) { return highlighter.isWordMisspelled(word) } + function replaceWord(word, at) { highlighter.replaceWord(word, at) } + // Session-only: process-wide, never written to disk by Sonnet. + function ignore(word) { highlighter.ignoreWord(word) } + function setLanguage(language) { highlighter.setCurrentLanguage(language) } + + Sonnet.SpellcheckHighlighter { + id: highlighter + document: probe.editor ? probe.editor.textDocument : null + active: true + automatic: false + // misspelledColor is not set: it has no effect on the rendered underline + // (always Qt's fixed red spell-check underline), and this repository + // forbids literal colours in QML anyway. + } +} diff --git a/ui/tests/qml/tst_spellcheck_probe.qml b/ui/tests/qml/tst_spellcheck_probe.qml new file mode 100644 index 0000000..5b60a90 --- /dev/null +++ b/ui/tests/qml/tst_spellcheck_probe.qml @@ -0,0 +1,115 @@ +import QtQuick +import QtTest + +// S00 probe: proves the real Sonnet QML highlighter behaviour the spelling +// adapter depends on. It loads Sonnet through a Loader so this file has no +// mandatory org.kde.sonnet import, and skips (rather than fails) where Sonnet +// or the en_US dictionary is absent. See planning/decisions/S00.md. +Item { + id: root + width: 800 + height: 220 + + // The surrogate pair in the emoji is two UTF-16 units, which is what makes + // the offset check below meaningful. + readonly property string sample: "ok \uD83D\uDCE8 wrod and mispelled; don't TEH. A correct sentence follows here." + + TextEdit { + id: edit + anchors.fill: parent + textFormat: TextEdit.PlainText + font.pixelSize: 18 + wrapMode: TextEdit.Wrap + text: root.sample + } + + Loader { + id: loader + source: "SpellcheckProbe.qml" + onLoaded: item.editor = edit + } + + TestCase { + name: "SpellcheckProbe" + when: windowShown + + function init() { edit.text = root.sample } + + // Returns the probe component, or null after asking to skip when Sonnet or + // the dictionary is unavailable. + function component() { + if (loader.status === Loader.Error || !loader.item) { + skip("org.kde.sonnet QML module unavailable (loader status " + loader.status + ")") + return null + } + var probe = loader.item + probe.setLanguage("en_US") + if (!probe.available || probe.language !== "en_US") { + skip("en_US dictionary unavailable (language " + probe.language + ", available " + probe.available + ")") + return null + } + return probe + } + + function test_availability_and_language() { + var probe = component() + if (!probe) return + compare(probe.available, true) + compare(probe.language, "en_US") + } + + function test_suggestions_and_utf16_offsets() { + var probe = component() + if (!probe) return + // "ok wrod": emoji occupies two UTF-16 units, so wrod starts at 6. + compare(edit.text.indexOf("wrod"), 6) + var atWrod = probe.suggestionsAt(6, 5) + verify(atWrod.length > 0) + compare(String(atWrod[0]), "word") + verify(probe.suggestionsAt(edit.text.indexOf("mispelled"), 5).length > 0) + // A correct word yields no suggestions. + compare(probe.suggestionsAt(edit.text.indexOf("sentence"), 5).length, 0) + } + + function test_is_word_misspelled() { + var probe = component() + if (!probe) return + compare(probe.isMisspelled("wrod"), true) + compare(probe.isMisspelled("mispelled"), true) + compare(probe.isMisspelled("sentence"), false) + compare(probe.isMisspelled("don't"), false) + } + + function test_correction_integrates_with_undo() { + var probe = component() + if (!probe) return + var before = edit.text + // replaceWord selects a length that only suggestions() has set, so the + // correction must be primed by asking for suggestions at the same + // position first. Without it Sonnet inserts instead of replacing. + probe.suggestionsAt(6, 5) + probe.replaceWord("word", 6) + verify(edit.text !== before) + compare(edit.text.indexOf("word and"), 6) + edit.undo() + compare(edit.text, before) + } + + function test_ignore_is_session_only() { + var probe = component() + if (!probe) return + compare(probe.isMisspelled("qqzzx"), true) + probe.ignore("qqzzx") + compare(probe.isMisspelled("qqzzx"), false) + } + + function test_disabling_does_not_mutate_text() { + var probe = component() + if (!probe) return + var before = edit.text + probe.active = false + compare(edit.text, before) + probe.active = true + } + } +} From 8692d4d9f6a715c59a04e21c3cde436646284406 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 11:59:22 -0500 Subject: [PATCH 02/18] S00: record confirmed decisions and add an interactive playground - S00.md: D1 accept Qt's fixed red underline, D2 app-owned personal words via ignoreWord, D3 keep Sonnet replaceWord with the priming rule (all confirmed) - tests/spellcheck/playground.qml: desktop tool to type, see underlines, and click a suggestion to apply a primed correction - portable suite passes --- planning/decisions/S00.md | 25 ++++++--- tests/spellcheck/playground.qml | 91 +++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 7 deletions(-) create mode 100644 tests/spellcheck/playground.qml diff --git a/planning/decisions/S00.md b/planning/decisions/S00.md index 9ba40d5..a5be303 100644 --- a/planning/decisions/S00.md +++ b/planning/decisions/S00.md @@ -6,9 +6,10 @@ Status: **READY FOR REVIEW** (supervisor sign-off required). Task: S00. Base: `d This record proves the real Sonnet QML runtime behaviour the spelling adapter depends on, and freezes the adapter's interface. Two behaviours are not what the -project plan assumed; they are raised as decisions (§5) rather than worked around -silently. No production file was changed: the only additions are the probe under -`ui/tests/qml/` and this record. +project plan assumed; they are resolved as decisions in §5, confirmed by the +supervisor on 2026-09-29. No production file was changed: the additions are the +probe under `ui/tests/qml/`, the throwaway playground under `tests/spellcheck/`, +and this record. ## 1. What was proven @@ -117,7 +118,7 @@ touched. "Ignore for this session" and a personal word are the same mechanism with different persistence. Both are process-global, which matches S6's "current application process/session" wording and makes all composers agree. -## 5. Escalations — supervisor decision required +## 5. Decisions (supervisor confirmed 2026-09-29) **D1 — underline colour cannot come from the theme (S5).** S5 requires the underline colour to come from a semantic theme role via `misspelledColor`. It @@ -128,18 +129,23 @@ functional affordance and record the deviation from the no-literal-colour rule; underlines" and a second engine); (c) accept red for v1 and revisit if Qt/Sonnet exposes a working colour. Recommendation: **(a)** — it is Qt's own spell-check affordance, not an app colour choice, and `tests/test_source.sh` only forbids -literal colours in app source, which this is not. +literal colours in app source, which this is not. **Decision: accept (a)** — the +underline stays Qt's fixed red for v1; revisit only if Qt/Sonnet exposes a +working colour. **D2 — personal-word persistence (§4).** Confirm the app-owned-list model (apply via `ignoreWord`) instead of `addWordToDictionary`, since the latter -writes the global dictionary. Recommendation: **confirm**. +writes the global dictionary. Recommendation: **confirm**. **Decision: confirmed** +— the app owns the personal list and applies it with `ignoreWord`; the global +dictionary is never written. **D3 — correction path (§2.1).** Confirm relying on Sonnet's `replaceWord` with the priming rule, rather than replacing text through the editor's own `remove`/`insert`. Recommendation: **confirm**, because it is undo-safe and keeps Sonnet's own word-trimming (leading/trailing apostrophes) consistent with the suggestions it offered. If the supervisor prefers editor-level replacement, that -is a contract change to freeze here. +is a contract change to freeze here. **Decision: confirmed** — use Sonnet +`replaceWord` with the frozen priming rule. ## 6. Evidence @@ -160,6 +166,11 @@ with any probe that calls `grabImage(item)` and `img.save(path)` under `QT_QPA_PLATFORM=offscreen`; the underline is confirmed by counting `#FF0000` pixels with `magick … -format %c histogram:info:-`. +Interactive playground (throwaway, not part of the app or the suite): +`tests/spellcheck/playground.qml`. Run it on the desktop with +`/usr/lib/qt6/bin/qml tests/spellcheck/playground.qml` and type in the body to +watch underlines and click a suggestion to apply a primed correction. + Throwaway probes that produced the tables above (not committed) covered: the UTF-16 offset sweep, the `replaceWord` at/prime matrix, the missing-module `Loader`, `setCurrentLanguage` on absent languages, and the automatic-mode diff --git a/tests/spellcheck/playground.qml b/tests/spellcheck/playground.qml new file mode 100644 index 0000000..5765ea0 --- /dev/null +++ b/tests/spellcheck/playground.qml @@ -0,0 +1,91 @@ +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import org.kde.sonnet as Sonnet + +// S00 interactive playground — a throwaway tool for trying the spelling +// adapter contract by hand before S01 wires it into the composer. +// +// Run it on the desktop (not offscreen): +// /usr/lib/qt6/bin/qml tests/spellcheck/playground.qml +// +// Type in the body: misspelled words get Qt's red underline. Put the caret in +// a word to see Sonnet's suggestions; click one to correct it. The correction +// uses the frozen rule from planning/decisions/S00.md §2.1 — prime with +// suggestions(position, 0) immediately before replaceWord(word, position) — +// because without the prime Sonnet inserts instead of replacing. +ApplicationWindow { + id: win + width: 860 + height: 560 + visible: true + title: "Omamail spelling playground — S00" + + property var suggestions: [] + property string inspectedWord: "" + property bool inspectedMisspelled: false + + function inspect() { + var position = body.cursorPosition + suggestions = highlighter.suggestions(position, 5) + inspectedWord = highlighter.wordUnderMouse + inspectedMisspelled = highlighter.wordIsMisspelled + } + + function correct(replacement) { + var position = body.cursorPosition + highlighter.suggestions(position, 0) // prime the word length first + highlighter.replaceWord(replacement, position) + inspect() + } + + ColumnLayout { + anchors.fill: parent + anchors.margins: 12 + spacing: 8 + + Text { + Layout.fillWidth: true + wrapMode: Text.WordWrap + text: "Type below. Misspelled words get a red underline. Put the caret in a word to see " + + "suggestions; click one to correct it. Press Ctrl+Z to undo a correction." + } + + TextEdit { + id: body + Layout.fillWidth: true + Layout.fillHeight: true + textFormat: TextEdit.PlainText + wrapMode: TextEdit.Wrap + selectByMouse: true + font.pixelSize: 18 + text: "This sentance has a mispelled wrod and teh rest is fine." + onCursorPositionChanged: win.inspect() + } + + Text { + Layout.fillWidth: true + text: win.inspectedWord === "" + ? "Caret is not in a word." + : (win.inspectedMisspelled ? "Misspelled: " + win.inspectedWord : "Looks correct: " + win.inspectedWord) + } + + Row { + spacing: 6 + Repeater { + model: win.suggestions + Button { + text: modelData + onClicked: win.correct(modelData) + } + } + } + } + + Sonnet.SpellcheckHighlighter { + id: highlighter + document: body.textDocument + active: true + automatic: false + } +} From e736048833e6fc25954bb28e1c1734b1c5304cf0 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 12:18:12 -0500 Subject: [PATCH 03/18] S01: attach the optional spelling adapter to the composer body - ui/compose/SpellcheckAdapter.qml implements the S00 interface (inspect, applyCorrection with the required suggestions priming, ignoreForSession, personalWords) and is the only production file importing org.kde.sonnet - ComposeView loads it through a Loader bound to the body textDocument, exposes spellingAvailable/spellingStatus/spellingAdapter, and unloads it when spelling is disabled; never assigns a null document - tests: adapter contract (7) and composer integration (5) pass; the preview harness shows the real composer for hands-on tuning - Makefile QML_FILES updated --- Makefile | 1 + tests/spellcheck/composer-preview.qml | 173 +++++++++++++++++++++++ ui/components/ComposeView.qml | 32 +++++ ui/compose/SpellcheckAdapter.qml | 97 +++++++++++++ ui/tests/qml/tst_spellcheck_adapter.qml | 111 +++++++++++++++ ui/tests/qml/tst_spellcheck_composer.qml | 107 ++++++++++++++ 6 files changed, 521 insertions(+) create mode 100644 tests/spellcheck/composer-preview.qml create mode 100644 ui/compose/SpellcheckAdapter.qml create mode 100644 ui/tests/qml/tst_spellcheck_adapter.qml create mode 100644 ui/tests/qml/tst_spellcheck_composer.qml diff --git a/Makefile b/Makefile index ca55d4f..7a6d43c 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,7 @@ QMLLINT := /usr/lib/qt6/bin/qmllint .DEFAULT_GOAL := test QML_FILES := ui/Service.qml ui/BarWidget.qml ui/App.qml ui/compose/RecoveryController.qml \ + ui/compose/SpellcheckAdapter.qml \ ui/backend/Backend.qml ui/backend/Runtime.qml ui/diagnostics/Diagnostics.qml \ ui/components/BackendSetup.qml ui/components/OmamailLogo.qml \ ui/account/MailAccount.qml ui/account/BackendSync.qml ui/account/SendQueue.qml ui/account/Intents.qml ui/account/BatchAction.qml ui/account/Rsvp.qml ui/account/LabelActions.qml ui/account/Unsubscribe.qml ui/account/NewMailNotification.qml \ diff --git a/tests/spellcheck/composer-preview.qml b/tests/spellcheck/composer-preview.qml new file mode 100644 index 0000000..c0cba58 --- /dev/null +++ b/tests/spellcheck/composer-preview.qml @@ -0,0 +1,173 @@ +import QtQuick +import "../../ui/components" as Omamail + +// S01 preview: the real ComposeView with the optional spelling adapter, shown +// in a window so the underline behaviour and suggestion UX can be tuned by hand +// without a mail account and without touching the installed plugin. +// +// Run it on the desktop (the mock shell imports stand in for the Omarchy shell): +// /usr/lib/qt6/bin/qml -I ui/tests/qml/imports tests/spellcheck/composer-preview.qml +Rectangle { + id: root + width: 1040 + height: 780 + color: "#101014" + + property var suggestions: [] + property string inspectedWord: "" + property bool inspectedMisspelled: false + property string adapterStatus: "loading" + + function findItem(item, name) { + if (!item) return null + if (item.objectName === name) return item + var values = item.children || [] + for (var i = 0; i < values.length; i++) { + var found = findItem(values[i], name) + if (found) return found + } + return null + } + + function refresh() { + var adapter = compose.spellingAdapter + var body = findItem(compose, "compose-body-editor") + adapterStatus = compose.spellingStatus + if (!adapter || !body) { suggestions = []; inspectedWord = ""; inspectedMisspelled = false; return } + var info = adapter.inspect(body.cursorPosition) + suggestions = info.suggestions + inspectedWord = info.word + inspectedMisspelled = info.misspelled + } + + function correct(replacement) { + var adapter = compose.spellingAdapter + var body = findItem(compose, "compose-body-editor") + if (!adapter || !body) return + adapter.applyCorrection(body.cursorPosition, replacement) + refresh() + } + + function ignoreWord() { + var adapter = compose.spellingAdapter + if (adapter && inspectedWord !== "") adapter.ignoreForSession(inspectedWord) + refresh() + } + + QtObject { + id: mailService + property bool sendPending: false + property bool sending: false + property int sendSecondsRemaining: 10 + property var lastSent: null + property var recipientContacts: [] + property var sendAsAliases: [] + property var sendIdentities: [ + ({ email: "me@example.com", accountId: "me@example.com", label: "me" }) + ] + property string accountEmail: "me@example.com" + property string activeAccountId: "me@example.com" + function preferredSendAs(_r) { return null } + function switchTo(_id) { return true } + function refreshRecipientContacts() {} + function send(_f) { return true } + function copyText(_t) { return true } + function clipboardAttachment(_dir, callback) { callback({ ok: false, error: "no-image" }); return true } + } + + Connections { + id: bodyConnections + function onCursorPositionChanged() { root.refresh() } + } + + Omamail.ComposeView { + id: compose + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.bottom: panel.top + service: mailService + textColor: "#e8e8ee" + backgroundColor: "#101014" + accentColor: "#ff8a3d" + dimColor: "#a9a9ae" + dimmerColor: "#737377" + popupBackgroundColor: "#1a1a1e" + popupBorderColor: "#3c3c41" + panelFontFamily: "sans" + } + + Rectangle { + id: panel + anchors.left: parent.left + anchors.right: parent.right + anchors.bottom: parent.bottom + height: 140 + color: "#1a1a1e" + + Column { + anchors.fill: parent + anchors.margins: 12 + spacing: 8 + + Text { + color: "#a9a9ae" + font.pixelSize: 13 + text: "spelling: " + root.adapterStatus + + " word: " + (root.inspectedWord === "" ? "(caret not in a word)" : root.inspectedWord) + + (root.inspectedMisspelled ? " [misspelled]" : "") + } + + Row { + spacing: 6 + Repeater { + model: root.suggestions + Rectangle { + width: suggestionLabel.implicitWidth + 16 + height: 28 + radius: 4 + color: "#2a2a30" + Text { id: suggestionLabel; anchors.centerIn: parent; color: "#e8e8ee"; text: modelData } + MouseArea { anchors.fill: parent; onClicked: root.correct(modelData) } + } + } + } + + Row { + spacing: 12 + + Rectangle { + width: toggleLabel.implicitWidth + 16 + height: 28 + radius: 4 + color: "#2a2a30" + Text { id: toggleLabel; anchors.centerIn: parent; color: "#e8e8ee" + text: compose.spellingEnabled ? "spelling: on" : "spelling: off" } + MouseArea { anchors.fill: parent; onClicked: { compose.spellingEnabled = !compose.spellingEnabled; root.refresh() } } + } + + Rectangle { + width: ignoreLabel.implicitWidth + 16 + height: 28 + radius: 4 + color: "#2a2a30" + Text { id: ignoreLabel; anchors.centerIn: parent; color: "#e8e8ee"; text: "ignore for session" } + MouseArea { anchors.fill: parent; onClicked: root.ignoreWord() } + } + } + + Text { + color: "#737377" + font.pixelSize: 12 + text: "Type in the body; red underlines mark misspellings (Qt's fixed red — S00 D1). " + + "Caret in a word shows suggestions; Ctrl+Z undoes a correction." + } + } + } + + Component.onCompleted: { + compose.begin("new", null, "", []) + bodyConnections.target = findItem(compose, "compose-body-editor") + refresh() + } +} diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index c82697b..05b5b80 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -38,6 +38,21 @@ DropArea { property bool opened: false property bool userModified: false property bool settingBodyText: false + // S01 temporary inputs; S04 replaces them with persisted user settings. + property bool spellingEnabled: true + property string spellingLanguage: "en_US" + property var spellingPersonalWords: [] + // Body checking is on only when the optional Sonnet adapter loaded and + // reports a dictionary for the requested language. + readonly property bool spellingAvailable: spellcheckLoader.status === Loader.Ready + && spellcheckLoader.item !== null && spellcheckLoader.item.available + readonly property string spellingStatus: spellcheckLoader.status === Loader.Error + ? "no-module" + : (spellcheckLoader.item ? spellcheckLoader.item.status + : (spellingEnabled ? "loading" : "disabled")) + // The live adapter, or null before it loads / when disabled. Tests and the + // preview drive spelling through this rather than reaching into the loader. + readonly property var spellingAdapter: spellcheckLoader.item // Drafts parked for their send's undo window, oldest first, each beside // the name of the send it belongs to. The timer owns them while the // visible composer stays free for the next message. @@ -1842,6 +1857,23 @@ DropArea { } } + // The spelling adapter is loaded optionally and destroyed when disabled, so + // a machine without org.kde.sonnet still opens the composer and a closed + // composer releases the highlighter. It binds to the body document and is + // never given a null document (Sonnet's setQuickDocument dereferences it). + Loader { + id: spellcheckLoader + active: root.spellingEnabled + source: "../compose/SpellcheckAdapter.qml" + onLoaded: { + if (!item) return + item.document = bodyEdit.textDocument + item.enabled = root.spellingEnabled + item.language = root.spellingLanguage + item.personalWords = root.spellingPersonalWords + } + } + Rectangle { objectName: "compose-body-restore-flash" anchors.fill: bodyFlick diff --git a/ui/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml new file mode 100644 index 0000000..00a2084 --- /dev/null +++ b/ui/compose/SpellcheckAdapter.qml @@ -0,0 +1,97 @@ +import QtQuick +import org.kde.sonnet as Sonnet + +// Optional spelling adapter (S01). This is the only production file that +// imports org.kde.sonnet, so it is always created through a Loader: a machine +// without the module gets a load error and an editor that still works, rather +// than a composer that refuses to open. +// +// The interface is frozen by planning/decisions/S00.md. Do not rename the +// properties or functions without changing that record. +// +// Two Sonnet behaviours the callers must respect (S00 §2): +// * corrections must call suggestions() for the same position immediately +// before replaceWord(), or Sonnet inserts instead of replacing; +// * the underline colour is Qt's fixed red; misspelledColor has no effect. +Item { + id: adapter + + // The editor's QQuickTextDocument. Never assigned null once set: Sonnet's + // setQuickDocument dereferences the parent without a null check. Release the + // highlighter by destroying the adapter (unload its Loader), not by clearing + // this. + property var document: null + // `enabled` is reused from Item rather than redeclared: the adapter is + // non-visual, so this keeps the name frozen by S00 without shadowing + // QQuickItem.enabled (which qmllint rejects). The owning Loader is inactive + // when spelling is off, so this is a runtime toggle within a loaded adapter. + property string language: "en_US" + // App-owned words to treat as correct (S00 §4). Persistence belongs to the + // settings layer (S04); this property only applies them. + property var personalWords: [] + + readonly property bool available: highlighter.spellCheckerFound + // "ready", "disabled", or "no-dictionary". A missing module is reported by + // the owning Loader as Loader.Error, not here. + readonly property string status: !enabled ? "disabled" + : (available ? "ready" : "no-dictionary") + + Component.onCompleted: applySettings() + onEnabledChanged: applySettings() + onLanguageChanged: applySettings() + onPersonalWordsChanged: applyPersonalWords() + + // Returns { word, misspelled, suggestions }. Call this for the position of a + // click or the caret; it also primes applyCorrection for the same position. + function inspect(position) { + if (!available || document === null) return { word: "", misspelled: false, suggestions: [] } + var at = Math.max(0, Math.floor(position)) + var list = highlighter.suggestions(at, 5) + return { + word: String(highlighter.wordUnderMouse), + misspelled: highlighter.wordIsMisspelled === true, + suggestions: list || [] + } + } + + // Applies a suggestion. The priming call is required: replaceWord anchors the + // replacement to the word the last suggestions() call remembered. + function applyCorrection(position, replacement) { + if (!available || document === null) return false + var at = Math.max(0, Math.floor(position)) + highlighter.suggestions(at, 0) + highlighter.replaceWord(String(replacement), at) + return true + } + + // Session-only ignore (S00 §4): never written to the user's dictionary. + function ignoreForSession(word) { + if (!available || !word) return + highlighter.ignoreWord(String(word)) + } + + function applySettings() { + if (!available) return + if (enabled) { + highlighter.setCurrentLanguage(language) + applyPersonalWords() + } + highlighter.active = enabled + } + + function applyPersonalWords() { + if (!available) return + for (var i = 0; i < personalWords.length; i++) { + var word = String(personalWords[i]) + if (word !== "") highlighter.ignoreWord(word) + } + } + + onDocumentChanged: if (document !== null) highlighter.document = document + + Sonnet.SpellcheckHighlighter { + id: highlighter + active: false + automatic: false // deterministic language; avoids the too-many-errors heuristic + } +} diff --git a/ui/tests/qml/tst_spellcheck_adapter.qml b/ui/tests/qml/tst_spellcheck_adapter.qml new file mode 100644 index 0000000..f72dd90 --- /dev/null +++ b/ui/tests/qml/tst_spellcheck_adapter.qml @@ -0,0 +1,111 @@ +import QtQuick +import QtTest + +// S01: the optional spelling adapter's contract (planning/decisions/S00.md §3). +// The adapter is loaded through a Loader so this file has no mandatory +// org.kde.sonnet import and skips where Sonnet or en_US is unavailable. +Item { + id: root + width: 800 + height: 200 + + readonly property string sample: "ok \uD83D\uDCE8 wrod and mispelled; don't TEH. A correct sentence follows here." + + TextEdit { + id: edit + anchors.fill: parent + textFormat: TextEdit.PlainText + font.pixelSize: 18 + wrapMode: TextEdit.Wrap + text: root.sample + } + + Loader { + id: loader + source: "../../compose/SpellcheckAdapter.qml" + onLoaded: { + item.document = edit.textDocument + item.enabled = true + item.language = "en_US" + } + } + + TestCase { + name: "SpellcheckAdapter" + when: windowShown + + function init() { edit.text = root.sample } + + function adapter() { + if (loader.status === Loader.Error || !loader.item) { + skip("org.kde.sonnet QML module unavailable (loader status " + loader.status + ")") + return null + } + var a = loader.item + if (!a.available) { + skip("en_US dictionary unavailable (status " + a.status + ")") + return null + } + return a + } + + function test_ready_and_status() { + var a = adapter() + if (!a) return + compare(a.available, true) + compare(a.status, "ready") + } + + function test_inspect_word_misspelling_and_suggestions() { + var a = adapter() + if (!a) return + var at = edit.text.indexOf("wrod") + compare(at, 6) + var info = a.inspect(at) + compare(info.word, "wrod") + compare(info.misspelled, true) + verify(info.suggestions.length > 0) + compare(String(info.suggestions[0]), "word") + // A correct word is not reported as misspelled. + var ok = a.inspect(edit.text.indexOf("sentence")) + compare(ok.misspelled, false) + } + + function test_correction_is_undo_safe_and_does_not_touch_other_words() { + var a = adapter() + if (!a) return + var before = edit.text + verify(a.applyCorrection(6, "word")) + verify(edit.text !== before) + compare(edit.text.indexOf("word and"), 6) + edit.undo() + compare(edit.text, before) + } + + function test_disable_does_not_mutate_text() { + var a = adapter() + if (!a) return + a.enabled = false + compare(a.status, "disabled") + a.enabled = true + compare(a.status, "ready") + compare(edit.text, root.sample) + } + + function test_personal_words_are_treated_as_correct() { + var a = adapter() + if (!a) return + // A word unique to this test: ignore is process-global and irreversible, + // so ignoring a word another test uses would make that test depend on + // order. + edit.text = "zqxjw zqxjw" + compare(a.inspect(0).misspelled, true) + a.personalWords = ["zqxjw"] + compare(a.inspect(0).misspelled, false) + // Applying personal words never disables the checker for other words. + compare(a.available, true) + edit.text = root.sample + compare(a.inspect(edit.text.indexOf("wrod")).misspelled, true) + } + } +} diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml new file mode 100644 index 0000000..3137618 --- /dev/null +++ b/ui/tests/qml/tst_spellcheck_composer.qml @@ -0,0 +1,107 @@ +import QtQuick +import QtTest +import "../../components" as Omamail + +// S01: the real composer attaches the optional spelling adapter to its body +// document, does not change the draft while checking, and unloads cleanly when +// disabled. Underlines are proven by the adapter contract test and the S00 +// probe; here the point is the wiring, not the highlighter. +Item { + width: 900 + height: 600 + + QtObject { + id: mailService + property bool sendPending: false + property bool sending: false + property int sendSecondsRemaining: 10 + property var lastSent: null + property var recipientContacts: [] + property var sendAsAliases: [] + property var sendIdentities: [ + ({ email: "me@example.com", accountId: "me@example.com", label: "me" }) + ] + property string accountEmail: "me@example.com" + property string activeAccountId: "me@example.com" + function preferredSendAs(_r) { return null } + function switchTo(_id) { return true } + function refreshRecipientContacts() {} + function send(_f) { return true } + function copyText(_t) { return true } + function clipboardAttachment(_dir, callback) { callback({ ok: false, error: "no-image" }); return true } + } + + Omamail.ComposeView { + id: compose + anchors.fill: parent + service: mailService + textColor: Qt.rgba(1, 1, 1, 1) + backgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1) + accentColor: Qt.rgba(1, 0.5, 0, 1) + dimColor: Qt.rgba(0.67, 0.67, 0.67, 1) + dimmerColor: Qt.rgba(0.47, 0.47, 0.47, 1) + popupBackgroundColor: Qt.rgba(0.13, 0.13, 0.13, 1) + popupBorderColor: Qt.rgba(0.3, 0.3, 0.3, 1) + panelFontFamily: "sans" + } + + TestCase { + name: "ComposeSpelling" + when: windowShown + + function named(item, objectName) { + if (!item) return null + if (item.objectName === objectName) return item + var values = item.children || [] + for (var i = 0; i < values.length; i++) { + var found = named(values[i], objectName) + if (found) return found + } + return null + } + + function init() { compose.begin("new", null, "", []) } + + function test_body_adapter_attaches_and_checking_does_not_mutate() { + var body = named(compose, "compose-body-editor") + verify(body, "the composer owns a body editor") + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (!compose.spellingAvailable) { + skip("spelling unavailable (" + compose.spellingStatus + ")") + return + } + body.text = "This sentance has a mispelled wrod." + var before = body.text + var info = compose.spellingAdapter.inspect(body.text.indexOf("mispelled")) + compare(info.misspelled, true) + compare(info.word, "mispelled") + // Merely inspecting must not change the draft. + compare(body.text, before) + } + + function test_a_correction_changes_the_body_and_undo_restores_it() { + var body = named(compose, "compose-body-editor") + verify(body) + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (!compose.spellingAvailable) { skip("spelling unavailable"); return } + body.text = "a mispelled wrod here" + var before = body.text + var at = body.text.indexOf("mispelled") + var info = compose.spellingAdapter.inspect(at) + compose.spellingAdapter.applyCorrection(at, info.suggestions[0]) + verify(body.text !== before) + body.undo() + compare(body.text, before) + } + + function test_disabling_unloads_the_adapter_and_re_enabling_restores_it() { + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + compose.spellingEnabled = false + tryVerify(function() { return compose.spellingAdapter === null }, 3000) + compare(compose.spellingStatus, "disabled") + compose.spellingEnabled = true + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + compare(compose.spellingAvailable, true) + } + } +} From f790ee62dd7542a7e9889571887b33c4118c4495 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 12:41:22 -0500 Subject: [PATCH 04/18] S01: draw the spelling underline ourselves; check only finished words Sonnet's QML highlighter colours the misspelled word red as well as underlining it (unlike the QWidget one), and misspelledColor is inert. So the adapter's highlighter now stays inactive and is used purely as a checker; the composer draws the line itself from completed-word ranges. - spellcheck adapter: adds misspelledRanges(text); a word is marked only once a delimiter follows it, so a word still being typed is never underlined; replaces item icons with the theme error colour - ComposeView: errorColor property, debounced completion check, underline overlay on the body item using positionToRectangle - App.qml passes the theme's urgent role as errorColor - preview: thinner suggestion strip coloured from the composer's theme roles - tests: adapter 9, composer 6, all green --- tests/spellcheck/composer-preview.qml | 106 +++++++++++------------ ui/App.qml | 1 + ui/components/ComposeView.qml | 49 +++++++++++ ui/compose/SpellcheckAdapter.qml | 56 ++++++++++-- ui/tests/qml/tst_spellcheck_adapter.qml | 25 ++++++ ui/tests/qml/tst_spellcheck_composer.qml | 15 ++++ 6 files changed, 190 insertions(+), 62 deletions(-) diff --git a/tests/spellcheck/composer-preview.qml b/tests/spellcheck/composer-preview.qml index c0cba58..b34b469 100644 --- a/tests/spellcheck/composer-preview.qml +++ b/tests/spellcheck/composer-preview.qml @@ -1,9 +1,10 @@ import QtQuick +import qs.Commons import "../../ui/components" as Omamail -// S01 preview: the real ComposeView with the optional spelling adapter, shown -// in a window so the underline behaviour and suggestion UX can be tuned by hand -// without a mail account and without touching the installed plugin. +// S01 preview: the real ComposeView with the optional spelling adapter, plus a +// slim suggestion strip for tuning. Every colour and the font come from the +// composer's own theme properties, so this is what the app would inherit. // // Run it on the desktop (the mock shell imports stand in for the Omarchy shell): // /usr/lib/qt6/bin/qml -I ui/tests/qml/imports tests/spellcheck/composer-preview.qml @@ -11,7 +12,7 @@ Rectangle { id: root width: 1040 height: 780 - color: "#101014" + color: compose.backgroundColor property var suggestions: [] property string inspectedWord: "" @@ -85,7 +86,7 @@ Rectangle { anchors.left: parent.left anchors.right: parent.right anchors.top: parent.top - anchors.bottom: panel.top + anchors.bottom: strip.top service: mailService textColor: "#e8e8ee" backgroundColor: "#101014" @@ -95,72 +96,71 @@ Rectangle { popupBackgroundColor: "#1a1a1e" popupBorderColor: "#3c3c41" panelFontFamily: "sans" + errorColor: "#ff5555" } + // A slim strip, coloured from the composer's theme roles, standing in for the + // S02 suggestion UI while the behaviour is tuned. Rectangle { - id: panel + id: strip anchors.left: parent.left anchors.right: parent.right anchors.bottom: parent.bottom - height: 140 - color: "#1a1a1e" + height: Style.space(30) + color: compose.popupBackgroundColor + + Rectangle { + anchors.top: parent.top + width: parent.width + height: 1 + color: compose.popupBorderColor + } - Column { + Row { anchors.fill: parent - anchors.margins: 12 - spacing: 8 + anchors.leftMargin: Style.space(10) + anchors.rightMargin: Style.space(10) + spacing: Style.space(10) Text { - color: "#a9a9ae" - font.pixelSize: 13 - text: "spelling: " + root.adapterStatus + - " word: " + (root.inspectedWord === "" ? "(caret not in a word)" : root.inspectedWord) + - (root.inspectedMisspelled ? " [misspelled]" : "") + anchors.verticalCenter: parent.verticalCenter + color: compose.dimColor + font.family: compose.panelFontFamily + font.pixelSize: Style.font.caption + text: inspectedWord === "" + ? (adapterStatus === "ready" ? "" : "spelling: " + adapterStatus) + : (inspectedMisspelled ? inspectedWord : "") } - Row { - spacing: 6 - Repeater { - model: root.suggestions - Rectangle { - width: suggestionLabel.implicitWidth + 16 - height: 28 - radius: 4 - color: "#2a2a30" - Text { id: suggestionLabel; anchors.centerIn: parent; color: "#e8e8ee"; text: modelData } - MouseArea { anchors.fill: parent; onClicked: root.correct(modelData) } - } + Repeater { + model: root.suggestions + Text { + anchors.verticalCenter: parent.verticalCenter + color: compose.accentColor + font.family: compose.panelFontFamily + font.pixelSize: Style.font.caption + text: modelData + MouseArea { anchors.fill: parent; onClicked: root.correct(modelData) } } } - Row { - spacing: 12 - - Rectangle { - width: toggleLabel.implicitWidth + 16 - height: 28 - radius: 4 - color: "#2a2a30" - Text { id: toggleLabel; anchors.centerIn: parent; color: "#e8e8ee" - text: compose.spellingEnabled ? "spelling: on" : "spelling: off" } - MouseArea { anchors.fill: parent; onClicked: { compose.spellingEnabled = !compose.spellingEnabled; root.refresh() } } - } - - Rectangle { - width: ignoreLabel.implicitWidth + 16 - height: 28 - radius: 4 - color: "#2a2a30" - Text { id: ignoreLabel; anchors.centerIn: parent; color: "#e8e8ee"; text: "ignore for session" } - MouseArea { anchors.fill: parent; onClicked: root.ignoreWord() } - } + Text { + anchors.verticalCenter: parent.verticalCenter + visible: root.inspectedMisspelled && root.inspectedWord !== "" + color: compose.dimColor + font.family: compose.panelFontFamily + font.pixelSize: Style.font.caption + text: "ignore" + MouseArea { anchors.fill: parent; onClicked: root.ignoreWord() } } Text { - color: "#737377" - font.pixelSize: 12 - text: "Type in the body; red underlines mark misspellings (Qt's fixed red — S00 D1). " + - "Caret in a word shows suggestions; Ctrl+Z undoes a correction." + anchors.verticalCenter: parent.verticalCenter + color: compose.dimColor + font.family: compose.panelFontFamily + font.pixelSize: Style.font.caption + text: compose.spellingEnabled ? "spelling on" : "spelling off" + MouseArea { anchors.fill: parent; onClicked: { compose.spellingEnabled = !compose.spellingEnabled; root.refresh() } } } } } diff --git a/ui/App.qml b/ui/App.qml index 84d69a8..cf64c62 100644 --- a/ui/App.qml +++ b/ui/App.qml @@ -2156,6 +2156,7 @@ Item { popupBackgroundColor: root.popupBackground popupBorderColor: root.popupBorder panelFontFamily: root.fontFamily + errorColor: root.urgent contentDirection: root.service ? root.service.contentDirection : "" // The stack follows the view: opening pushes, closing pops — and // the pop is here rather than on `closed`, because a draft parked diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index 05b5b80..df815e9 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -53,6 +53,30 @@ DropArea { // The live adapter, or null before it loads / when disabled. Tests and the // preview drive spelling through this rather than reaching into the loader. readonly property var spellingAdapter: spellcheckLoader.item + // Finished misspelled words as {start, end} UTF-16 offsets into the body text. + property var spellingRanges: [] + // The theme's error role, drawn under misspelled words. The composer draws + // the underline itself because Sonnet's QML highlighter also colours the word + // red; see planning/decisions/S00.md and the S01 handoff. + property color errorColor: textColor + + // A word is marked only once it is finished (something follows it), so this + // only has to keep up with the document; the completeness rule is what defers + // the underline while someone is still typing a word. + function refreshSpellingRanges() { + var adapter = spellingAdapter + spellingRanges = (adapter && spellingAvailable && spellingEnabled) + ? adapter.misspelledRanges(bodyEdit.text) : [] + } + onSpellingAvailableChanged: refreshSpellingRanges() + onSpellingEnabledChanged: refreshSpellingRanges() + + Timer { + id: spellingDebounce + interval: 120 + repeat: false + onTriggered: root.refreshSpellingRanges() + } // Drafts parked for their send's undo window, oldest first, each beside // the name of the send it belongs to. The timer owns them while the // visible composer stays free for the next message. @@ -1851,9 +1875,33 @@ DropArea { root.bodyWasEdited = true root.noteUserModified() } + spellingDebounce.restart() } Keys.priority: Keys.BeforeItem Keys.onPressed: root.pasteKey(event) + + // The spelling underline is drawn here, not by Sonnet, so the word is not + // also coloured red and the colour comes from the theme. It sits on the + // body item so it scrolls and wraps with the text. + Item { + id: spellingUnderlines + anchors.fill: parent + Repeater { + model: root.spellingRanges + delegate: Rectangle { + required property var modelData + readonly property rect fromRect: bodyEdit.positionToRectangle(modelData.start) + readonly property rect toRect: bodyEdit.positionToRectangle(Math.max(modelData.start, modelData.end - 1)) + x: fromRect.x + y: fromRect.y + fromRect.height - height + width: Math.max(2, fromRect.y === toRect.y + ? toRect.x + toRect.width - fromRect.x + : fromRect.width) + height: 1 + color: root.errorColor + } + } + } } } @@ -1871,6 +1919,7 @@ DropArea { item.enabled = root.spellingEnabled item.language = root.spellingLanguage item.personalWords = root.spellingPersonalWords + root.refreshSpellingRanges() } } diff --git a/ui/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml index 00a2084..906148e 100644 --- a/ui/compose/SpellcheckAdapter.qml +++ b/ui/compose/SpellcheckAdapter.qml @@ -6,13 +6,12 @@ import org.kde.sonnet as Sonnet // without the module gets a load error and an editor that still works, rather // than a composer that refuses to open. // -// The interface is frozen by planning/decisions/S00.md. Do not rename the -// properties or functions without changing that record. -// -// Two Sonnet behaviours the callers must respect (S00 §2): -// * corrections must call suggestions() for the same position immediately -// before replaceWord(), or Sonnet inserts instead of replacing; -// * the underline colour is Qt's fixed red; misspelledColor has no effect. +// The interface is frozen by planning/decisions/S00.md, with one later change: +// the underline is drawn by the caller, not by Sonnet. Sonnet's QML highlighter +// paints the misspelled word red as well as underlining it (its errorFormat +// sets a red foreground; misspelledColor is inert), unlike the QWidget one, +// which only underlines. So the highlighter here stays inactive and is used +// only as a checker: it never writes any format to the document. Item { id: adapter @@ -70,13 +69,50 @@ Item { highlighter.ignoreWord(String(word)) } + // Every misspelled word that is finished, as UTF-16 {start, end} offsets into + // `text`. A word is finished only when something follows it, so the word the + // user is still typing is never marked: the underline appears once a + // delimiter (space, punctuation, newline) has been typed after it. + function misspelledRanges(text) { + var ranges = [] + if (!available || !enabled || !text) return ranges + var length = text.length + var index = 0 + while (index < length) { + if (!isWordChar(text.charAt(index))) { index += 1; continue } + var start = index + while (index < length && isWordChar(text.charAt(index))) index += 1 + var end = index + // Nothing follows: this is the word still being typed. Earlier finished + // words have already been collected, so stop. + if (end >= length) break + var wordStart = start + var wordEnd = end + while (wordStart < wordEnd && isApostrophe(text.charAt(wordStart))) wordStart += 1 + while (wordEnd > wordStart && isApostrophe(text.charAt(wordEnd - 1))) wordEnd -= 1 + if (wordEnd > wordStart) { + var word = text.substring(wordStart, wordEnd) + if (highlighter.isWordMisspelled(word)) ranges.push({ start: wordStart, end: wordEnd }) + } + } + return ranges + } + + function isWordChar(character) { + // Letters and digits across the common scripts, plus the apostrophes that + // sit inside a word. A surrogate half (an emoji) matches nothing and is + // skipped, so it is never treated as a word. + return /[0-9A-Za-z\u00C0-\u024F\u0300-\u036F\u0370-\u03FF\u0400-\u04FF'\u2019]/.test(character) + } + + function isApostrophe(character) { return character === "'" || character === "\u2019" } + function applySettings() { if (!available) return if (enabled) { highlighter.setCurrentLanguage(language) applyPersonalWords() } - highlighter.active = enabled } function applyPersonalWords() { @@ -91,7 +127,9 @@ Item { Sonnet.SpellcheckHighlighter { id: highlighter + // Never active: Sonnet must not paint the document (it would colour the + // word red as well as underlining it). Query methods work while inactive. active: false - automatic: false // deterministic language; avoids the too-many-errors heuristic + automatic: false } } diff --git a/ui/tests/qml/tst_spellcheck_adapter.qml b/ui/tests/qml/tst_spellcheck_adapter.qml index f72dd90..7a082c1 100644 --- a/ui/tests/qml/tst_spellcheck_adapter.qml +++ b/ui/tests/qml/tst_spellcheck_adapter.qml @@ -92,6 +92,31 @@ Item { compare(edit.text, root.sample) } + function test_misspelled_ranges_are_only_finished_words() { + var a = adapter() + if (!a) return + // Nothing follows the word: still being typed, so not marked yet. + compare(a.misspelledRanges("wrod").length, 0) + // A delimiter finished it. + compare(a.misspelledRanges("wrod ").length, 1) + // The trailing word is skipped; the finished one before it is not. + var one = a.misspelledRanges("a wrod and mispelled") + compare(one.length, 1) + compare(one[0].start, 2) + compare(one[0].end, 6) + compare(a.misspelledRanges("a wrod and mispelled ").length, 2) + } + + function test_misspelled_ranges_use_utf16_offsets() { + var a = adapter() + if (!a) return + // "the " is four units, the emoji is two more, so wrod starts at 7. + var ranges = a.misspelledRanges("the \uD83D\uDCE8 wrod ") + compare(ranges.length, 1) + compare(ranges[0].start, 7) + compare(ranges[0].end, 11) + } + function test_personal_words_are_treated_as_correct() { var a = adapter() if (!a) return diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml index 3137618..e62c4e3 100644 --- a/ui/tests/qml/tst_spellcheck_composer.qml +++ b/ui/tests/qml/tst_spellcheck_composer.qml @@ -94,6 +94,21 @@ Item { compare(body.text, before) } + function test_underline_ranges_require_a_finished_word() { + var body = named(compose, "compose-body-editor") + verify(body) + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (!compose.spellingAvailable) { skip("spelling unavailable"); return } + body.text = "a wrod" + wait(250) // past the debounce + compare(compose.spellingRanges.length, 0) + body.text = "a wrod " + wait(250) + compare(compose.spellingRanges.length, 1) + compare(compose.spellingRanges[0].start, 2) + compare(compose.spellingRanges[0].end, 6) + } + function test_disabling_unloads_the_adapter_and_re_enabling_restores_it() { tryVerify(function() { return compose.spellingAdapter !== null }, 3000) compose.spellingEnabled = false From ee1b7768051deea0d35d73402e8f36b946e1f826 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 12:41:41 -0500 Subject: [PATCH 05/18] S01: record the underline redesign and supersede S00 D1 --- planning/decisions/S01.md | 69 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 planning/decisions/S01.md diff --git a/planning/decisions/S01.md b/planning/decisions/S01.md new file mode 100644 index 0000000..03c11cc --- /dev/null +++ b/planning/decisions/S01.md @@ -0,0 +1,69 @@ +# S01 decision — body underlines, drawn by the composer + +Status: **IN PROGRESS** — implementation landed for hands-on tuning; the formal +handoff follows once the look and behaviour settle. Task: S01. Base: `8692d4d` +(the S00 branch tip; S00 is not yet merged). Branch: `task/S01-body-spelling`. + +This record updates the S00 adapter contract and supersedes S00 decision **D1**. +It is the working agreement for S01 until superseded by the handoff. + +## 1. Why D1 changed + +S00 §2.2 found that Sonnet's `misspelledColor` has no effect on the rendered +underline. S01 found the larger problem: Sonnet's **QML** highlighter also sets +`errorFormat.setForeground(spellColor)`, so a misspelled word is drawn in red +*text* as well as a red underline. The **QWidget** highlighter +(`src/ui/highlighter.cpp`) sets only the underline style and colour — the red +foreground is specific to the QML one, and 6.29.0 is the newest Arch package. + +Owner decision (2026-09-29): **underline only**, so the composer draws the +underline itself and Sonnet's highlighter never paints. + +## 2. Decisions confirmed by the owner (2026-09-29) + +| # | Decision | +| --- | --- | +| D1′ | The composer draws the underline; Sonnet's highlighter stays `active: false` and is used only as a checker. Supersedes S00 D1 (accept Qt's red). | +| D1c | The underline colour is the theme's error/urgent role (`Color.urgent`), passed to the composer as `errorColor`. | +| D2′ | A word is marked only once it is **finished** — when a delimiter follows it. A word still being typed is never underlined. | +| D3′ | Suggestions live in a slim inline strip under the body, coloured from the composer's theme roles and font. | + +D2 (app-owned personal words via `ignoreWord`) and D3 (Sonnet `replaceWord` with +`suggestions()` priming) from S00 stand unchanged. + +## 3. Contract changes to the S00 adapter + +- The highlighter is created with `active: false` and is never activated. The + query methods (`isWordMisspelled`, `suggestions`, `replaceWord`) work while + inactive; `inspect`, `applyCorrection`, `ignoreForSession`, and + `personalWords` are unchanged. +- New: `misspelledRanges(text)` returns finished misspelled words as UTF-16 + `{start, end}` offsets. Tokens are runs of letters/digits/apostrophes across + the common scripts; a surrogate half (an emoji) is not a word. A token at the + very end of the text is treated as still being typed and is skipped. +- `enabled` continues to be `Item.enabled` (no redeclaration), so a disabled + adapter reports `status: "disabled"` and returns no ranges. + +`ComposeView` gains `errorColor`, `spellingRanges`, `spellingAdapter`, +`spellingAvailable`, `spellingStatus`, and `spellingEnabled` / `spellingLanguage` +/ `spellingPersonalWords` as temporary inputs (S04 supplies persisted settings). +It recomputes ranges on a 120 ms debounce; the debounce is only for cost — the +completeness rule is what defers the underline. + +## 4. Evidence + +- Underline-only: the composer was rendered offscreen with `errorColor` set to + pure red and the body text `"this sentance has a mispelled wrod here "`. Red + pixels occur on a single baseline row (y=187, 118 px for the three words) with + no red pixels in the glyph body — the word text keeps the theme colour. +- Tests: adapter contract 9/9, composer integration 6/6; `test_source.sh`, + `test_qml_names.py`, `qml-check`, `git diff --check` pass. +- Hand-tuning: `tests/spellcheck/composer-preview.qml` (real composer, mock + shell imports). + +## 5. Open for tuning + +- Underline thickness is one pixel; placement is the character-box baseline. +- The inline strip is a preview affordance; its production form belongs to S02. +- Wrapped long words are drawn on their first line only. +- Checking is not yet deferred during IME composition. From 94ae441f84027f95f5187b6672779f72417516af Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 12:56:48 -0500 Subject: [PATCH 06/18] S01: suggestions in the right-click menu and at the caret (Ctrl+.) - TextMenu gains a spelling section above Cut/Copy/Paste: up to five suggestions, Ignore for this session, and Add to dictionary, all sharing the existing theme colours and j/k/o keyboard navigation - ComposeView captures the clicked word via TextEdit.positionAt and the caret word via Ctrl+., and routes corrections to the adapter; the fixed bottom strip is retired - keeps the captured UTF-16 position so a correction targets the clicked word even if the caret moved - tests: menu/caret integration 10 in the composer test, text menu 14; full QML suite 1023 passed / 8 pre-existing Qt 6.11 failures; the TextMenu cursor test now names its row instead of assuming index 0 --- planning/decisions/S01.md | 11 +- tests/spellcheck/composer-preview.qml | 132 ++--------------------- ui/components/ComposeView.qml | 64 ++++++++++- ui/components/TextMenu.qml | 78 +++++++++++++- ui/tests/qml/tst_spellcheck_composer.qml | 70 ++++++++++++ ui/tests/qml/tst_text_menu.qml | 4 +- 6 files changed, 229 insertions(+), 130 deletions(-) diff --git a/planning/decisions/S01.md b/planning/decisions/S01.md index 03c11cc..23b4a38 100644 --- a/planning/decisions/S01.md +++ b/planning/decisions/S01.md @@ -26,7 +26,7 @@ underline itself and Sonnet's highlighter never paints. | D1′ | The composer draws the underline; Sonnet's highlighter stays `active: false` and is used only as a checker. Supersedes S00 D1 (accept Qt's red). | | D1c | The underline colour is the theme's error/urgent role (`Color.urgent`), passed to the composer as `errorColor`. | | D2′ | A word is marked only once it is **finished** — when a delimiter follows it. A word still being typed is never underlined. | -| D3′ | Suggestions live in a slim inline strip under the body, coloured from the composer's theme roles and font. | +| D3′ | Suggestions live at the **top of the existing right-click `TextMenu`** (theme colours, keyboard j/k/o navigation, one menu for every field), plus a `Ctrl+.` popover anchored at the caret word. The fixed bottom strip is retired — it sat far from the word in a full-screen window and crowded the Send row. | D2 (app-owned personal words via `ignoreWord`) and D3 (Sonnet `replaceWord` with `suggestions()` priming) from S00 stand unchanged. @@ -64,6 +64,13 @@ completeness rule is what defers the underline. ## 5. Open for tuning - Underline thickness is one pixel; placement is the character-box baseline. -- The inline strip is a preview affordance; its production form belongs to S02. +- The spelling section sits above Cut/Copy/Paste. It inherits the menu's theme + colours and j/k/o navigation for free; the row order and the separators are + the main things to tune. +- `Ctrl+.` opens the same menu at the caret word. The key is free elsewhere in + the app and falls through when the caret word is not misspelled. - Wrapped long words are drawn on their first line only. - Checking is not yet deferred during IME composition. +- "Add to dictionary" appends to the app-owned list for this session; S04 makes + it persist. Ignore and add are process-global (S00 §4), so they affect every + composer. diff --git a/tests/spellcheck/composer-preview.qml b/tests/spellcheck/composer-preview.qml index b34b469..b1c16bf 100644 --- a/tests/spellcheck/composer-preview.qml +++ b/tests/spellcheck/composer-preview.qml @@ -1,10 +1,11 @@ import QtQuick -import qs.Commons import "../../ui/components" as Omamail -// S01 preview: the real ComposeView with the optional spelling adapter, plus a -// slim suggestion strip for tuning. Every colour and the font come from the -// composer's own theme properties, so this is what the app would inherit. +// S01 preview: the real ComposeView with the optional spelling adapter, for +// hands-on tuning of the underline and the suggestion menu. +// +// right-click a misspelled word -> suggestions, Ignore, Add to dictionary +// Ctrl+. -> the same, anchored at the caret word // // Run it on the desktop (the mock shell imports stand in for the Omarchy shell): // /usr/lib/qt6/bin/qml -I ui/tests/qml/imports tests/spellcheck/composer-preview.qml @@ -14,47 +15,6 @@ Rectangle { height: 780 color: compose.backgroundColor - property var suggestions: [] - property string inspectedWord: "" - property bool inspectedMisspelled: false - property string adapterStatus: "loading" - - function findItem(item, name) { - if (!item) return null - if (item.objectName === name) return item - var values = item.children || [] - for (var i = 0; i < values.length; i++) { - var found = findItem(values[i], name) - if (found) return found - } - return null - } - - function refresh() { - var adapter = compose.spellingAdapter - var body = findItem(compose, "compose-body-editor") - adapterStatus = compose.spellingStatus - if (!adapter || !body) { suggestions = []; inspectedWord = ""; inspectedMisspelled = false; return } - var info = adapter.inspect(body.cursorPosition) - suggestions = info.suggestions - inspectedWord = info.word - inspectedMisspelled = info.misspelled - } - - function correct(replacement) { - var adapter = compose.spellingAdapter - var body = findItem(compose, "compose-body-editor") - if (!adapter || !body) return - adapter.applyCorrection(body.cursorPosition, replacement) - refresh() - } - - function ignoreWord() { - var adapter = compose.spellingAdapter - if (adapter && inspectedWord !== "") adapter.ignoreForSession(inspectedWord) - refresh() - } - QtObject { id: mailService property bool sendPending: false @@ -76,17 +36,9 @@ Rectangle { function clipboardAttachment(_dir, callback) { callback({ ok: false, error: "no-image" }); return true } } - Connections { - id: bodyConnections - function onCursorPositionChanged() { root.refresh() } - } - Omamail.ComposeView { id: compose - anchors.left: parent.left - anchors.right: parent.right - anchors.top: parent.top - anchors.bottom: strip.top + anchors.fill: parent service: mailService textColor: "#e8e8ee" backgroundColor: "#101014" @@ -99,75 +51,5 @@ Rectangle { errorColor: "#ff5555" } - // A slim strip, coloured from the composer's theme roles, standing in for the - // S02 suggestion UI while the behaviour is tuned. - Rectangle { - id: strip - anchors.left: parent.left - anchors.right: parent.right - anchors.bottom: parent.bottom - height: Style.space(30) - color: compose.popupBackgroundColor - - Rectangle { - anchors.top: parent.top - width: parent.width - height: 1 - color: compose.popupBorderColor - } - - Row { - anchors.fill: parent - anchors.leftMargin: Style.space(10) - anchors.rightMargin: Style.space(10) - spacing: Style.space(10) - - Text { - anchors.verticalCenter: parent.verticalCenter - color: compose.dimColor - font.family: compose.panelFontFamily - font.pixelSize: Style.font.caption - text: inspectedWord === "" - ? (adapterStatus === "ready" ? "" : "spelling: " + adapterStatus) - : (inspectedMisspelled ? inspectedWord : "") - } - - Repeater { - model: root.suggestions - Text { - anchors.verticalCenter: parent.verticalCenter - color: compose.accentColor - font.family: compose.panelFontFamily - font.pixelSize: Style.font.caption - text: modelData - MouseArea { anchors.fill: parent; onClicked: root.correct(modelData) } - } - } - - Text { - anchors.verticalCenter: parent.verticalCenter - visible: root.inspectedMisspelled && root.inspectedWord !== "" - color: compose.dimColor - font.family: compose.panelFontFamily - font.pixelSize: Style.font.caption - text: "ignore" - MouseArea { anchors.fill: parent; onClicked: root.ignoreWord() } - } - - Text { - anchors.verticalCenter: parent.verticalCenter - color: compose.dimColor - font.family: compose.panelFontFamily - font.pixelSize: Style.font.caption - text: compose.spellingEnabled ? "spelling on" : "spelling off" - MouseArea { anchors.fill: parent; onClicked: { compose.spellingEnabled = !compose.spellingEnabled; root.refresh() } } - } - } - } - - Component.onCompleted: { - compose.begin("new", null, "", []) - bodyConnections.target = findItem(compose, "compose-body-editor") - refresh() - } + Component.onCompleted: compose.begin("new", null, "", []) } diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index df815e9..993cca4 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -77,6 +77,52 @@ DropArea { repeat: false onTriggered: root.refreshSpellingRanges() } + + // Right-click: the word under the pointer, kept for the menu's spelling + // section. Only the body is checked; another field clears the section. + function prepareSpellingMenu(editor, x, y) { + var adapter = spellingAdapter + if (!adapter || !spellingAvailable || editor !== bodyEdit) { + textMenu.spellingPosition = -1 + textMenu.spellingWord = "" + textMenu.spellingMisspelled = false + textMenu.spellingSuggestions = [] + return + } + var position = editor.positionAt(x, y) + var info = adapter.inspect(position) + textMenu.spellingPosition = position + textMenu.spellingWord = info.word + textMenu.spellingMisspelled = info.misspelled + textMenu.spellingSuggestions = info.suggestions + } + + // Keyboard: suggestions for the word at the caret, anchored to it. Returns + // false when there is nothing to offer so the key falls through. + function openSpellingAtCaret() { + var adapter = spellingAdapter + if (!adapter || !spellingAvailable) return false + var position = bodyEdit.cursorPosition + var info = adapter.inspect(position) + if (!info.misspelled || info.suggestions.length === 0) return false + textMenu.spellingPosition = position + textMenu.spellingWord = info.word + textMenu.spellingMisspelled = true + textMenu.spellingSuggestions = info.suggestions + var box = bodyEdit.positionToRectangle(position) + var scene = bodyEdit.mapToGlobal(box.x, box.y + box.height) + textMenu.openAt(bodyEdit, scene.x, scene.y, "") + return true + } + + // App-owned personal words (S00 §4): persisted by S04, applied here. + function addPersonalWord(word) { + if (!word) return + var words = spellingPersonalWords.slice() + if (words.indexOf(word) < 0) words.push(word) + spellingPersonalWords = words + } + onSpellingPersonalWordsChanged: if (spellcheckLoader.item) spellcheckLoader.item.personalWords = spellingPersonalWords // Drafts parked for their send's undo window, oldest first, each beside // the name of the send it belongs to. The timer owns them while the // visible composer stays free for the next message. @@ -1878,7 +1924,13 @@ DropArea { spellingDebounce.restart() } Keys.priority: Keys.BeforeItem - Keys.onPressed: root.pasteKey(event) + Keys.onPressed: function(event) { + if ((event.modifiers & Qt.ControlModifier) && event.key === Qt.Key_Period) { + if (root.openSpellingAtCaret()) event.accepted = true + return + } + root.pasteKey(event) + } // The spelling underline is drawn here, not by Sonnet, so the word is not // also coloured red and the colour comes from the theme. It sits on the @@ -2098,6 +2150,7 @@ DropArea { acceptedButtons: Qt.RightButton onPressed: function(mouse) { var scene = parent.mapToGlobal(mouse.x, mouse.y) + root.prepareSpellingMenu(parent, mouse.x, mouse.y) textMenu.openAt(parent, scene.x, scene.y, "") } } @@ -2117,5 +2170,14 @@ DropArea { if (target) target.forceActiveFocus() root.paste() } + onSpellingCorrect: function(replacement) { + if (root.spellingAdapter) root.spellingAdapter.applyCorrection(textMenu.spellingPosition, replacement) + root.refreshSpellingRanges() + } + onSpellingIgnore: function(word) { + if (root.spellingAdapter) root.spellingAdapter.ignoreForSession(word) + root.refreshSpellingRanges() + } + onSpellingAddToDictionary: root.addPersonalWord(word) } } diff --git a/ui/components/TextMenu.qml b/ui/components/TextMenu.qml index 750857e..9a8f228 100644 --- a/ui/components/TextMenu.qml +++ b/ui/components/TextMenu.qml @@ -27,9 +27,22 @@ Item { // The link under the pointer when it opened, or "" for none. property string link: "" property int cursorIndex: -1 + // Spelling, set by the owner before opening. An empty suggestion list with + // spellingMisspelled false hides the whole section. spellingPosition is the + // UTF-16 offset the suggestions were taken from, kept so a correction still + // targets the clicked word if the caret has moved by the time one is picked. + property int spellingPosition: -1 + property string spellingWord: "" + property bool spellingMisspelled: false + property var spellingSuggestions: [] + readonly property bool spellingVisible: spellingSuggestions.length > 0 || spellingMisspelled + readonly property bool spellingActionsVisible: spellingMisspelled && spellingWord !== "" readonly property bool opened: menu.opened readonly property bool hasSelection: !!target && String(target.selectedText || "") !== "" - readonly property var menuRows: [cutRow, copyRow, pasteRow, selectAllRow, openLinkRow, copyLinkRow] + readonly property var menuRows: [ + suggestion0, suggestion1, suggestion2, suggestion3, suggestion4, + ignoreRow, addRow, cutRow, copyRow, pasteRow, selectAllRow, openLinkRow, copyLinkRow + ] readonly property alias cutRow: cutRow readonly property alias copyRow: copyRow @@ -37,12 +50,17 @@ Item { readonly property alias selectAllRow: selectAllRow readonly property alias openLinkRow: openLinkRow readonly property alias copyLinkRow: copyLinkRow + readonly property alias ignoreWordRow: ignoreRow + readonly property alias addToDictionaryRow: addRow signal copyRequested(string text) // Paste is the owner's: a compose form tries the clipboard for an image // before it pastes text, and only it knows how. signal pasteRequested(var target) signal openLinkRequested(string url) + signal spellingCorrect(string replacement) + signal spellingIgnore(string word) + signal spellingAddToDictionary(string word) anchors.fill: parent z: 50 @@ -79,6 +97,12 @@ Item { function runCursor() { if (cursorIndex >= 0) menuRows[cursorIndex].activated() } function close() { menu.close() } + function chooseSuggestion(index) { + var replacement = String(root.spellingSuggestions[index] || "") + menu.close() + if (replacement !== "") root.spellingCorrect(replacement) + } + function copySelection() { var text = hasSelection ? String(target.selectedText) : "" menu.close() @@ -132,6 +156,58 @@ Item { } } + MenuRow { + id: suggestion0 + visible: root.spellingSuggestions.length > 0 + text: String(root.spellingSuggestions[0] || "") + onActivated: root.chooseSuggestion(0) + } + MenuRow { + id: suggestion1 + visible: root.spellingSuggestions.length > 1 + text: String(root.spellingSuggestions[1] || "") + onActivated: root.chooseSuggestion(1) + } + MenuRow { + id: suggestion2 + visible: root.spellingSuggestions.length > 2 + text: String(root.spellingSuggestions[2] || "") + onActivated: root.chooseSuggestion(2) + } + MenuRow { + id: suggestion3 + visible: root.spellingSuggestions.length > 3 + text: String(root.spellingSuggestions[3] || "") + onActivated: root.chooseSuggestion(3) + } + MenuRow { + id: suggestion4 + visible: root.spellingSuggestions.length > 4 + text: String(root.spellingSuggestions[4] || "") + onActivated: root.chooseSuggestion(4) + } + MenuSeparatorLine { + visible: root.spellingVisible + width: menu.width - menu.leftPadding - menu.rightPadding + lineColor: root.textColor + } + MenuRow { + id: ignoreRow + visible: root.spellingActionsVisible + text: "Ignore for this session" + onActivated: { var word = root.spellingWord; menu.close(); root.spellingIgnore(word) } + } + MenuRow { + id: addRow + visible: root.spellingActionsVisible + text: "Add to dictionary" + onActivated: { var word = root.spellingWord; menu.close(); root.spellingAddToDictionary(word) } + } + MenuSeparatorLine { + visible: root.spellingVisible + width: menu.width - menu.leftPadding - menu.rightPadding + lineColor: root.textColor + } MenuRow { id: cutRow visible: root.editable diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml index e62c4e3..02085f1 100644 --- a/ui/tests/qml/tst_spellcheck_composer.qml +++ b/ui/tests/qml/tst_spellcheck_composer.qml @@ -109,6 +109,76 @@ Item { compare(compose.spellingRanges[0].end, 6) } + function test_right_click_offers_suggestions_for_the_clicked_word() { + var body = named(compose, "compose-body-editor") + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (!compose.spellingAvailable) { skip("spelling unavailable"); return } + body.text = "a mispelled wrod " + wait(250) + var box = body.positionToRectangle(body.text.indexOf("mispelled")) + mouseClick(body, box.x + 2, box.y + box.height / 2, Qt.RightButton) + wait(20) + var menu = named(compose, "compose-text-menu") + verify(menu.opened, "the text menu opened") + compare(menu.spellingMisspelled, true) + compare(menu.spellingWord, "mispelled") + verify(menu.spellingSuggestions.length > 0) + // Choosing the first suggestion replaces the clicked word. + menu.chooseSuggestion(0) + wait(20) + verify(body.text.indexOf("mispelled") === -1) + } + + function test_ignore_for_session_stops_marking_the_word() { + var body = named(compose, "compose-body-editor") + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (!compose.spellingAvailable) { skip("spelling unavailable"); return } + body.text = "the floobert here " + wait(250) + compare(compose.spellingRanges.length, 1) + var box = body.positionToRectangle(body.text.indexOf("floobert")) + mouseClick(body, box.x + 2, box.y + box.height / 2, Qt.RightButton) + wait(20) + var menu = named(compose, "compose-text-menu") + compare(menu.spellingWord, "floobert") + menu.ignoreWordRow.activated() + wait(250) + compare(compose.spellingRanges.length, 0) + } + + function test_add_to_dictionary_stops_marking_the_word() { + var body = named(compose, "compose-body-editor") + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (!compose.spellingAvailable) { skip("spelling unavailable"); return } + body.text = "the blorptar here " + wait(250) + compare(compose.spellingRanges.length, 1) + var box = body.positionToRectangle(body.text.indexOf("blorptar")) + mouseClick(body, box.x + 2, box.y + box.height / 2, Qt.RightButton) + wait(20) + var menu = named(compose, "compose-text-menu") + compare(menu.spellingWord, "blorptar") + menu.addToDictionaryRow.activated() + wait(250) + compare(compose.spellingRanges.length, 0) + } + + function test_ctrl_period_opens_suggestions_at_the_caret_word() { + var body = named(compose, "compose-body-editor") + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (!compose.spellingAvailable) { skip("spelling unavailable"); return } + body.text = "the mispelled here " + wait(250) + body.cursorPosition = body.text.indexOf("mispelled") + 2 + body.forceActiveFocus() + keyClick(Qt.Key_Period, Qt.ControlModifier) + wait(20) + var menu = named(compose, "compose-text-menu") + verify(menu.opened, "the caret shortcut opened the menu") + compare(menu.spellingWord, "mispelled") + verify(menu.spellingSuggestions.length > 0) + } + function test_disabling_unloads_the_adapter_and_re_enabling_restores_it() { tryVerify(function() { return compose.spellingAdapter !== null }, 3000) compose.spellingEnabled = false diff --git a/ui/tests/qml/tst_text_menu.qml b/ui/tests/qml/tst_text_menu.qml index 94fe658..682a240 100644 --- a/ui/tests/qml/tst_text_menu.qml +++ b/ui/tests/qml/tst_text_menu.qml @@ -145,7 +145,9 @@ Item { function test_the_cursor_starts_on_the_first_usable_row() { editor.select(0, 5) show(true, "https://example.com/a") - compare(menu.cursorIndex, 0) + // The menu may carry rows above Cut (spelling), so name the row rather + // than its index. + compare(menu.cursorIndex, menu.menuRows.indexOf(menu.cutRow)) editor.deselect() show(true) // Nothing selected: Cut and Copy are out, Paste is the first row. From 1f9f4988de7c57e8428ec6f4b771f81d9bac6bd5 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 13:02:10 -0500 Subject: [PATCH 07/18] S01: reach the end of the word with the underline positionToRectangle returns the caret at a position (width 1), not the character's box, so anchoring the width on end-1 stopped the line at the start of the last letter. Use the caret one past the word instead. Measured: 'sentance' drew 47 px before, 53 px after (full advance 52.7 px). --- ui/components/ComposeView.qml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index 993cca4..4395da6 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -1942,13 +1942,16 @@ DropArea { model: root.spellingRanges delegate: Rectangle { required property var modelData + // positionToRectangle gives the caret at a position (width 1), so + // the right edge of the word is the caret one past its last + // character, not the last character's own rectangle. readonly property rect fromRect: bodyEdit.positionToRectangle(modelData.start) - readonly property rect toRect: bodyEdit.positionToRectangle(Math.max(modelData.start, modelData.end - 1)) + readonly property rect toRect: bodyEdit.positionToRectangle(modelData.end) x: fromRect.x y: fromRect.y + fromRect.height - height width: Math.max(2, fromRect.y === toRect.y - ? toRect.x + toRect.width - fromRect.x - : fromRect.width) + ? toRect.x - fromRect.x + : Math.max(fromRect.width, bodyEdit.width - fromRect.x)) height: 1 color: root.errorColor } From f485bf4597bc0551724bc5c5075835fa50c9231a Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 13:53:09 -0500 Subject: [PATCH 08/18] S02: guard corrections against a stale draft and mark them as edits --- planning/decisions/S02.md | 67 ++++++++ ui/components/ComposeView.qml | 17 +- ui/tests/qml/tst_spellcheck_menu.qml | 234 +++++++++++++++++++++++++++ 3 files changed, 316 insertions(+), 2 deletions(-) create mode 100644 planning/decisions/S02.md create mode 100644 ui/tests/qml/tst_spellcheck_menu.qml diff --git a/planning/decisions/S02.md b/planning/decisions/S02.md new file mode 100644 index 0000000..2576185 --- /dev/null +++ b/planning/decisions/S02.md @@ -0,0 +1,67 @@ +# S02 decision — the spelling menu actions, made safe + +Status: **READY FOR REVIEW**. Task: S02. Base: `1f9f498` (the S01 branch tip, +`task/S01-body-spelling`). Branch: `task/S02-spelling-menu`. + +S01 landed the suggestion rows, Ignore, Add to dictionary, and the right-click / +`Ctrl+.` wiring as a prototype. S02 completes that prototype into the finished +menu behaviour — the only production change is a guard on the correction path +and the draft-dirty marking, plus a dedicated menu test file. + +## 1. What S02 adds on top of S01 + +| Concern | S01 state | S02 change | +| --- | --- | --- | +| Correction target | `applyCorrection(savedPosition, replacement)` fired blindly | Re-verify the word at the saved position before editing; abort if it no longer matches | +| Draft dirty state | Menu owns focus, so the body's `onTextChanged` skipped `bodyWasEdited`/`noteUserModified` | A correction marks the draft dirty itself | +| `onSpellingAddToDictionary` | Deprecated parameter injection (`word` undeclared; qmllint/test warning) | Formal `function(word)` handler | +| Menu tests | 8 composer tests, none exercising the menu guards | `tst_spellcheck_menu.qml`, 11 focused tests | + +The adapter contract is unchanged: `inspect`, `applyCorrection`, +`ignoreForSession` and `personalWords` keep their S00/S01 frozen shapes. The +guard is caller-side (in `ComposeView`), not in the adapter. + +## 2. Decisions + +| # | Decision | +| --- | --- | +| D1 | A correction re-checks the word at `textMenu.spellingPosition` with `inspect` and aborts unless `word` still equals `spellingWord` **and** it is still misspelled. The word-identity check is what makes the guard catch the case where the position now holds a *different* misspelled word; misspelled-ness alone is not enough. | +| D2 | A correction sets `bodyWasEdited = true` and calls `noteUserModified()`, because the menu owns focus while open and the body's own `onTextChanged` correctly declines to mark an edit it did not see. | +| D3 | "Add to dictionary" stays **app-owned** (S00 §4: `ignoreWord`, never `addWordToDictionary`), so it cannot fail in a way the menu must surface. The S02 criterion "personal dictionary failure is visible" is satisfied vacuously by construction; the only persistence — and therefore the only place a real write could fail — is S04. | + +## 3. Evidence + +`qmltestrunner` (Qt 6.11.2, offscreen, software backend, real Sonnet 6.29.0 + +`en_US` — no skips): + +- `tst_spellcheck_adapter.qml` — 9/9. +- `tst_spellcheck_composer.qml` — 10/10 (the deprecation warning on the + add-to-dictionary handler is gone). +- `tst_spellcheck_menu.qml` — 11/11 (new): click-vs-caret target; two identical + words; emoji (non-BMP) prefix; selection does not redirect; punctuation and + newline word boundaries; stale document aborts; no-suggestions still offers + Ignore/Add; keyboard accepts the first suggestion; open/close never edits or + dirties; a menu correction is one undo away; a correction marks the draft + dirty. +- `tst_text_menu.qml` — 14/14 (ordinary menu with no spelling provider is + unchanged). +- `python3 tests/test_qml_names.py` — ok; `git diff --check` — clean; `qmllint` + adds no warnings on the changed block (the 219 pre-existing import warnings + from the standalone `-I /usr/share/omarchy/shell` run are baseline noise). + +## 4. Deferred to S04 + +- Persisting personal words and the enabled/language settings across restarts. +- The `spellingPersonalWords` input remains the temporary `S01` plumbing; S04 + feeds it from real settings. + +## 5. Review risks and limitations + +- The stale-document guard is proven against a body replaced while the menu is + open; the "destroyed composer" half of the S02 wording is covered by QML + ownership (the menu is a child of the composer and cannot outlive it). No + retained reference is held beyond the child `TextMenu`. +- "Added word survives process restart" is not S02 scope — S00 §4 made + ignore-and-add process-global, and persistence is S04. +- No live account, mailbox, or credential was involved; all tests use the + synthetic `mailService` fixture and reserved example domains. diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index 4395da6..2a55034 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -2174,13 +2174,26 @@ DropArea { root.paste() } onSpellingCorrect: function(replacement) { - if (root.spellingAdapter) root.spellingAdapter.applyCorrection(textMenu.spellingPosition, replacement) + var adapter = root.spellingAdapter + if (!adapter) return + // The menu outlives its click: a draft can change underneath it (a reply + // quote arriving, an agent answer landing) while it is open. Re-check the + // word at the saved position before editing, so a stale position never + // rewrites whatever text now sits there. + var now = adapter.inspect(textMenu.spellingPosition) + if (now.word !== textMenu.spellingWord || !now.misspelled) return + adapter.applyCorrection(textMenu.spellingPosition, replacement) + // The menu owns focus while it is open, so the body's onTextChanged does + // not mark the edit. A correction is a user edit: dirty the draft and + // refresh the underlines itself. + root.bodyWasEdited = true + root.noteUserModified() root.refreshSpellingRanges() } onSpellingIgnore: function(word) { if (root.spellingAdapter) root.spellingAdapter.ignoreForSession(word) root.refreshSpellingRanges() } - onSpellingAddToDictionary: root.addPersonalWord(word) + onSpellingAddToDictionary: function(word) { root.addPersonalWord(word) } } } diff --git a/ui/tests/qml/tst_spellcheck_menu.qml b/ui/tests/qml/tst_spellcheck_menu.qml new file mode 100644 index 0000000..20c2654 --- /dev/null +++ b/ui/tests/qml/tst_spellcheck_menu.qml @@ -0,0 +1,234 @@ +import QtQuick +import QtTest +import "../../components" as Omamail + +// S02: the right-click / Ctrl+. spelling menu on the composer body — the word +// it targets, the correction/ignore/dictionary actions it offers, and the +// guards that keep a stale or destroyed draft from being rewritten. The +// underlines and the adapter contract are covered by tst_spellcheck_adapter +// and tst_spellcheck_composer; here the point is the menu wiring. +Item { + width: 900 + height: 600 + + QtObject { + id: mailService + property bool sendPending: false + property bool sending: false + property int sendSecondsRemaining: 10 + property var lastSent: null + property var recipientContacts: [] + property var sendAsAliases: [] + property var sendIdentities: [ + ({ email: "me@example.com", accountId: "me@example.com", label: "me" }) + ] + property string accountEmail: "me@example.com" + property string activeAccountId: "me@example.com" + function preferredSendAs(_r) { return null } + function switchTo(_id) { return true } + function refreshRecipientContacts() {} + function send(_f) { return true } + function copyText(_t) { return true } + function clipboardAttachment(_dir, callback) { callback({ ok: false, error: "no-image" }); return true } + } + + Omamail.ComposeView { + id: compose + anchors.fill: parent + service: mailService + textColor: Qt.rgba(1, 1, 1, 1) + backgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1) + accentColor: Qt.rgba(1, 0.5, 0, 1) + dimColor: Qt.rgba(0.67, 0.67, 0.67, 1) + dimmerColor: Qt.rgba(0.47, 0.47, 0.47, 1) + popupBackgroundColor: Qt.rgba(0.13, 0.13, 0.13, 1) + popupBorderColor: Qt.rgba(0.3, 0.3, 0.3, 1) + panelFontFamily: "sans" + } + + TestCase { + name: "ComposeSpellingMenu" + when: windowShown + + function named(item, objectName) { + if (!item) return null + if (item.objectName === objectName) return item + var values = item.children || [] + for (var i = 0; i < values.length; i++) { + var found = named(values[i], objectName) + if (found) return found + } + return null + } + + function body() { return named(compose, "compose-body-editor") } + function menu() { return named(compose, "compose-text-menu") } + + function init() { + compose.begin("new", null, "", []) + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (!compose.spellingAvailable) skip("spelling unavailable (" + compose.spellingStatus + ")") + } + + // Right-click the middle of a word and wait for the menu to open. The word + // may already be present earlier in the text, so fromIndex selects which. + function clickWord(editor, word, fromIndex) { + var idx = editor.text.indexOf(word, fromIndex || 0) + verify(idx >= 0, "the word is present: " + word) + var startRect = editor.positionToRectangle(idx) + var endRect = editor.positionToRectangle(idx + word.length) + var cx = (startRect.x + endRect.x) / 2 + var cy = startRect.y + startRect.height / 2 + mouseClick(editor, cx, cy, Qt.RightButton) + wait(20) + return idx + } + + function test_click_targets_the_word_not_the_caret() { + var editor = body() + editor.text = "a wrod here" + editor.cursorPosition = editor.text.length // the caret sits in "here" + clickWord(editor, "wrod") + var m = menu() + verify(m.opened, "the menu opened") + compare(m.spellingWord, "wrod") + compare(m.spellingMisspelled, true) + var suggestion = m.spellingSuggestions[0] + m.chooseSuggestion(0) + wait(20) + compare(editor.text, "a " + suggestion + " here") + } + + function test_two_identical_words_correct_only_the_clicked_one() { + var editor = body() + editor.text = "a wrod and wrod here" + clickWord(editor, "wrod", editor.text.indexOf("wrod") + 1) // the second one + var m = menu() + compare(m.spellingWord, "wrod") + var suggestion = m.spellingSuggestions[0] + m.chooseSuggestion(0) + wait(20) + compare(editor.text.indexOf("wrod"), 2) // the first is untouched + compare(editor.text, "a wrod and " + suggestion + " here") + } + + function test_emoji_prefix_still_targets_the_word() { + var editor = body() + editor.text = "the \uD83D\uDCE8 wrod here" + clickWord(editor, "wrod") + var m = menu() + compare(m.spellingWord, "wrod") + var suggestion = m.spellingSuggestions[0] + m.chooseSuggestion(0) + wait(20) + compare(editor.text, "the \uD83D\uDCE8 " + suggestion + " here") + } + + function test_a_selection_does_not_redirect_spelling() { + var editor = body() + editor.text = "a wrod here" + editor.select(editor.text.indexOf("here"), editor.text.length) + clickWord(editor, "wrod") + var m = menu() + // The spelling section targets the clicked word, never the selection. + compare(m.spellingWord, "wrod") + // But the selection is still present, so Cut and Copy stay available. + verify(m.hasSelection, "the selection is still reported") + m.chooseSuggestion(0) + wait(20) + verify(editor.text.indexOf("wrod") === -1) + } + + function test_punctuation_and_newline_are_not_part_of_the_word() { + var editor = body() + editor.text = "a wrod, and mispelled.\nnext" + clickWord(editor, "wrod") + compare(menu().spellingWord, "wrod") + menu().close() + clickWord(editor, "mispelled") + compare(menu().spellingWord, "mispelled") + } + + function test_stale_document_aborts_the_correction() { + var editor = body() + editor.text = "a wrod here" + clickWord(editor, "wrod") + var m = menu() + compare(m.spellingWord, "wrod") + // The body is replaced while the menu is still open — the saved position + // now points at a *different* misspelled word, so applying must not fire. + editor.text = "a mispelled here" + var before = editor.text + m.chooseSuggestion(0) + wait(20) + compare(editor.text, before) + } + + function test_no_suggestions_offers_ignore_and_add_but_no_rows() { + var editor = body() + editor.text = "a zxqjklv here " + wait(250) + compare(compose.spellingRanges.length, 1) + clickWord(editor, "zxqjklv") + var m = menu() + compare(m.spellingMisspelled, true) + compare(m.spellingSuggestions.length, 0) + verify(m.ignoreWordRow.visible, "Ignore is offered without suggestions") + verify(m.addToDictionaryRow.visible, "Add to dictionary is offered without suggestions") + m.ignoreWordRow.activated() + wait(250) + compare(compose.spellingRanges.length, 0) + } + + function test_keyboard_accepts_the_first_suggestion() { + var editor = body() + editor.text = "a wrod here" + clickWord(editor, "wrod") + var m = menu() + // The cursor starts on the first usable row, which is the first + // suggestion; Enter/O runs it without touching the mouse. + compare(m.cursorIndex, 0) + var suggestion = m.spellingSuggestions[0] + m.runCursor() + wait(20) + compare(editor.text, "a " + suggestion + " here") + } + + function test_opening_and_closing_never_edits_or_dirties() { + var editor = body() + editor.text = "a wrod here" + var before = editor.text + clickWord(editor, "wrod") + var m = menu() + verify(m.opened, "the menu opened") + m.close() + compare(editor.text, before) + compare(compose.userModified, false) + compare(compose.bodyWasEdited, false) + } + + function test_a_menu_correction_is_one_undo_away() { + var editor = body() + editor.text = "a wrod here" + clickWord(editor, "wrod") + var m = menu() + var before = editor.text + m.chooseSuggestion(0) + wait(20) + verify(editor.text !== before) + editor.undo() + compare(editor.text, before) + } + + function test_a_correction_marks_the_draft_dirty() { + var editor = body() + editor.text = "a wrod here" + clickWord(editor, "wrod") + var m = menu() + m.chooseSuggestion(0) + wait(20) + compare(compose.bodyWasEdited, true) + compare(compose.userModified, true) + } + } +} From caa24a5302e1bdb1ca8a8bd59f4679b8f59aeb81 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 15:00:03 -0500 Subject: [PATCH 09/18] S04: add spelling settings, personal dictionary persistence, and graceful absence --- manifest.json | 18 ++++- planning/decisions/S04.md | 84 +++++++++++++++++++++ ui/App.qml | 3 + ui/Service.qml | 92 ++++++++++++++++++++++- ui/components/ComposeView.qml | 21 +++--- ui/components/SettingsPage.qml | 93 ++++++++++++++++++++++++ ui/tests/qml/tst_service_settings.qml | 50 +++++++++++++ ui/tests/qml/tst_spellcheck_composer.qml | 7 ++ ui/tests/qml/tst_spellcheck_menu.qml | 7 ++ 9 files changed, 363 insertions(+), 12 deletions(-) create mode 100644 planning/decisions/S04.md diff --git a/manifest.json b/manifest.json index d257b0b..cf0098b 100644 --- a/manifest.json +++ b/manifest.json @@ -48,7 +48,9 @@ "unifiedCalendarView": false, "openOnClick": "Window", "showBarIcon": true, - "suggestEvents": false + "suggestEvents": false, + "spellingEnabled": true, + "spellingLanguage": "en_US" }, "schema": [ { @@ -162,6 +164,20 @@ ], "defaultValue": "Window", "description": "The full window, or a small card with the most recent unread mail." + }, + { + "key": "spellingEnabled", + "type": "boolean", + "label": "Spell-check while composing", + "defaultValue": true, + "description": "Underline misspelled words in the message body with corrections, Ignore, and Add to dictionary. Uses the local Hunspell engine; nothing is sent anywhere." + }, + { + "key": "spellingLanguage", + "type": "string", + "label": "Spelling dictionary language", + "defaultValue": "en_US", + "description": "The Hunspell dictionary code used for spell-checking, for example en_US. Requires the matching hunspell dictionary package to be installed." } ] } diff --git a/planning/decisions/S04.md b/planning/decisions/S04.md new file mode 100644 index 0000000..6c63c0a --- /dev/null +++ b/planning/decisions/S04.md @@ -0,0 +1,84 @@ +# S04 decision — spelling settings, persistence, and graceful absence + +Status: **READY FOR REVIEW**. Task: S04. Base: `f485bf4` (the S02 branch tip, +`task/S02-spelling-menu`; S03 was deferred this pass). Branch: +`task/S04-spelling-settings`. + +S04 turns the S01 temporary inputs into persisted settings, stores the +app-owned personal dictionary, and explains absence instead of failing. + +## 1. What S04 adds + +| Concern | Before (S02) | After (S04) | +| --- | --- | --- | +| Enabled / language | ComposeView defaults (`true`, `"en_US"`), lost on restart | Manifest-schema settings, persisted by the shell | +| Personal words | ComposeView-local list, session-only | Service-owned `spelling.json`, survives restart | +| Availability | Computed inside ComposeView only | Service-level Sonnet probe, shown in Settings | +| Settings UI | none | "Spelling" section in SettingsPage | + +## 2. Decisions + +| # | Decision | +| --- | --- | +| D1 | `spellingEnabled` (boolean, default on) and `spellingLanguage` (string, `"en_US"`) live in the manifest schema and persist through the shell like `suggestEvents`. | +| D2 | Personal words are app-owned and stored in a private `spelling.json` beside `window.json`, never in a global Sonnet/Hunspell dictionary. Add is idempotent; remove exists for future UI. | +| D3 | Availability is a Service-level probe (a Loader over the same `SpellcheckAdapter`), kept separate from the requested `spellingEnabled`. The Settings page explains a missing module or dictionary; it never silently substitutes a language. | +| D4 | The enabled toggle stays usable when the dictionary is missing: the request is persisted even before the dictionary is installed; the underline simply does not appear until it is. | + +## 3. Dependency guidance + +Spell-checking is optional and local: + +- **Sonnet QML module** (`org.kde.sonnet`, the KDE spell-checking framework) is + imported only by `ui/compose/SpellcheckAdapter.qml`, which is always loaded + through a Loader. Without it the composer still opens; `spellingStatus` reads + `no-module`. +- **Hunspell dictionary** for the requested language — `hunspell-en_us` for the + `en_US` default (Arch: `pacman -S hunspell-en_us`; Ubuntu: `hunspell-en-us`). + Without it `spellingStatus` reads `no-dictionary` and the Settings page names + the package to install. +- Neither is a hard dependency: a machine with neither still composes, edits, + and sends. Checking is local — no network or model calls. + +## 4. Evidence + +`qmltestrunner` (Qt 6.11.2, offscreen, Sonnet 6.29.0 + `en_US` present): + +- `tst_spellcheck_adapter.qml` 9/9; `tst_spellcheck_composer.qml` 10/10; + `tst_spellcheck_menu.qml` 13/13; `tst_text_menu.qml` 14/14. +- `tst_service_settings.qml` 15/15, including four new spelling cases: defaults + + persistence, personal-word add/remove/dedupe, parse/dedupe/junk rejection, + and the availability probe settling to a known status. +- `tst_settings_name.qml` 8/8; `tst_settings_sidebar.qml` 9/9; + `tst_calendar_settings.qml` 6/6 — the new Settings section leaves the + existing page intact. +- `python3 tests/test_qml_names.py` ok; `git diff --check` clean; `manifest.json` + parses; `qmllint` adds only the same `Loader.item` typing warnings the S01 + adapter already carries. + +## 5. S-criteria mapping + +| Criterion | Where | +| --- | --- | +| S1 underline | S01 | +| S2 body only (subject deferred) | S01 + STATE.md | +| S3 menu actions | S02 | +| S4 undo + dirty state | S02 | +| S5 `en_US`, local, enabled setting, graceful absence | S04 (this task) | +| S6 personal words survive restart, ignore session-only | S04 (persistence) + S02 (ignore) | + +## 6. Review risks and limitations + +- The `spelling.json` write goes through `writeConfig` (the same config-store + host helper as `window.json`); the file round-trip is not exercised in the + bare QML test harness (no host process), only the in-memory store and the + parse/normalise path are. The write path is shared with `window.json`, which + is covered elsewhere. A failed write is best-effort: the word stays in memory + for the session and is retried on the next change, but is not surfaced as an + error (there is no compose-time error channel for a dictionary write, and the + consequence is only a word re-flagged after restart). +- The availability probe loads Sonnet in the service process (one extra, + lightweight highlighter), independent of any compose window. +- "Default on when available" means the setting defaults to on and the underline + appears only when the probe reports `ready`; the two facts are kept distinct + rather than conflated into one flag. diff --git a/ui/App.qml b/ui/App.qml index cf64c62..f0024ed 100644 --- a/ui/App.qml +++ b/ui/App.qml @@ -2158,6 +2158,9 @@ Item { panelFontFamily: root.fontFamily errorColor: root.urgent contentDirection: root.service ? root.service.contentDirection : "" + spellingEnabled: root.service ? root.service.spellingEnabled : true + spellingLanguage: root.service ? root.service.spellingLanguage : "en_US" + spellingPersonalWords: root.service ? root.service.spellingPersonalWords : [] // The stack follows the view: opening pushes, closing pops — and // the pop is here rather than on `closed`, because a draft parked // for sending closes without saying so. diff --git a/ui/Service.qml b/ui/Service.qml index 7da0c91..e004560 100644 --- a/ui/Service.qml +++ b/ui/Service.qml @@ -140,7 +140,9 @@ Item { unifiedCalendarView: false, showBarIcon: true, unifiedMailboxes: false, - suggestEvents: false + suggestEvents: false, + spellingEnabled: true, + spellingLanguage: "en_US" }) function normalizedSettings(values) { var next = ({}) @@ -424,7 +426,7 @@ Item { } function writeConfig(name, text, callback) { - var allowed = ["credentials.json", "window.json", "calendars.json"] + var allowed = ["credentials.json", "window.json", "calendars.json", "spelling.json"] if (allowed.indexOf(String(name || "")) < 0) { if (typeof callback === "function") callback(false, "Invalid configuration file") return false @@ -627,6 +629,74 @@ Item { persistSetting("unifiedMailboxes", value === true) } + // ------------------------------------------------------------- spelling + // + // Spelling is local and optional: the composer loads the Sonnet adapter + // through a Loader, so a machine without the module or dictionary still + // composes. The enabled flag is the user's request; availability is a + // separate runtime fact reported by the probe, so "off because the user + // turned it off" and "off because en_US is missing" read differently. + readonly property bool spellingEnabled: !settings || settings.spellingEnabled !== false + function setSpellingEnabled(value) { persistSetting("spellingEnabled", value !== false) } + readonly property string spellingLanguage: settings + ? String(settings.spellingLanguage || "en_US") : "en_US" + function setSpellingLanguage(value) { persistSetting("spellingLanguage", String(value || "en_US")) } + + // Whether Sonnet and the requested dictionary are actually loadable. The + // probe is separate from the per-composer adapter so the settings page can + // explain a missing module or dictionary before any compose window opens. + readonly property bool spellingAvailable: spellingProbe.status === Loader.Ready + && spellingProbe.item !== null && spellingProbe.item.available + readonly property string spellingStatus: spellingProbe.status === Loader.Error + ? "no-module" : (spellingProbe.item ? spellingProbe.item.status : "loading") + + // App-owned personal words (S00 §4, S6): persisted beside the other window + // state, applied by the composer, never written to a global dictionary. + property var spellingPersonalWords: [] + property bool spellingPersonalWordsLoaded: false + property bool spellingPersonalWordsWriting: false + + function applySpellingPersonalWords(raw) { + var parsed = null + try { parsed = JSON.parse(String(raw || "")) } catch (e) { parsed = null } + var words = (parsed && Array.isArray(parsed.words)) ? parsed.words : [] + var next = [] + for (var i = 0; i < words.length; i++) { + var word = words[i] + if (typeof word !== "string") continue + if (word !== "" && next.indexOf(word) < 0) next.push(word) + } + spellingPersonalWords = next + spellingPersonalWordsLoaded = true + } + + function saveSpellingPersonalWords() { + if (!spellingPersonalWordsLoaded || spellingPersonalWordsWriting) return + spellingPersonalWordsWriting = true + writeConfig("spelling.json", JSON.stringify({ words: spellingPersonalWords }), function(ok) { + root.spellingPersonalWordsWriting = false + }) + } + + function addPersonalWord(word) { + var value = String(word || "") + if (value === "" || spellingPersonalWords.indexOf(value) >= 0) return + var next = spellingPersonalWords.slice() + next.push(value) + spellingPersonalWords = next + saveSpellingPersonalWords() + } + + function removePersonalWord(word) { + var value = String(word || "") + var at = spellingPersonalWords.indexOf(value) + if (at < 0) return + var next = spellingPersonalWords.slice() + next.splice(at, 1) + spellingPersonalWords = next + saveSpellingPersonalWords() + } + // ---------------------------------------------------------- the accounts property var accountList: Accounts.emptyList() @@ -2622,6 +2692,24 @@ Item { onLoadFailed: root.applyWindowPrefs("") } + // Spelling's personal dictionary is app-owned (S00 §4): persisted beside the + // window state, never written to a global dictionary. + FileView { + id: spellingWordsFile + path: root.configPath("spelling.json") + printErrors: false + onLoaded: root.applySpellingPersonalWords(text()) + onLoadFailed: root.applySpellingPersonalWords("") + } + + // Availability probe: loads Sonnet once so the settings page can explain a + // missing module or dictionary without a compose window open. + Loader { + id: spellingProbe + active: true + source: "compose/SpellcheckAdapter.qml" + } + Timer { id: windowPrefsSettling interval: 500 diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index 2a55034..0da6d97 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -38,7 +38,9 @@ DropArea { property bool opened: false property bool userModified: false property bool settingBodyText: false - // S01 temporary inputs; S04 replaces them with persisted user settings. + // Spelling settings (S04): read from the service, applied to the adapter. + // The service owns the values and persistence; the composer only applies + // them. Missing support is reported via spellingStatus. property bool spellingEnabled: true property string spellingLanguage: "en_US" property var spellingPersonalWords: [] @@ -115,14 +117,12 @@ DropArea { return true } - // App-owned personal words (S00 §4): persisted by S04, applied here. - function addPersonalWord(word) { - if (!word) return - var words = spellingPersonalWords.slice() - if (words.indexOf(word) < 0) words.push(word) - spellingPersonalWords = words + // App-owned personal words (S00 §4): owned and persisted by the service + // (S04); applied to the adapter and rechecked whenever the list changes. + onSpellingPersonalWordsChanged: { + if (spellcheckLoader.item) spellcheckLoader.item.personalWords = spellingPersonalWords + refreshSpellingRanges() } - onSpellingPersonalWordsChanged: if (spellcheckLoader.item) spellcheckLoader.item.personalWords = spellingPersonalWords // Drafts parked for their send's undo window, oldest first, each beside // the name of the send it belongs to. The timer owns them while the // visible composer stays free for the next message. @@ -2194,6 +2194,9 @@ DropArea { if (root.spellingAdapter) root.spellingAdapter.ignoreForSession(word) root.refreshSpellingRanges() } - onSpellingAddToDictionary: function(word) { root.addPersonalWord(word) } + onSpellingAddToDictionary: function(word) { + if (root.service && typeof root.service.addPersonalWord === "function") + root.service.addPersonalWord(word) + } } } diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml index fbd4d66..e27f330 100644 --- a/ui/components/SettingsPage.qml +++ b/ui/components/SettingsPage.qml @@ -686,6 +686,99 @@ Column { } } + // ------------------------------------------------------------- spelling + + Text { + id: spellingHeading + text: "SPELLING" + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + font.letterSpacing: 1 + } + + Rectangle { + objectName: "settings-spelling" + width: parent.width + implicitHeight: Math.max(spellingText.implicitHeight, spellingSwitch.implicitHeight) + + Style.space(16) + radius: Style.cornerRadius + color: Style.normalFillFor(root.textColor, root.accentColor) + + Column { + id: spellingText + anchors.left: parent.left + anchors.leftMargin: Style.space(12) + anchors.right: spellingState.left + anchors.rightMargin: Style.space(10) + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(2) + + Text { + width: parent.width + text: "Spell-check while composing" + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.bodySmall + textFormat: Text.PlainText + } + + Text { + width: parent.width + text: "Underline misspelled words in the message body with corrections, " + + "Ignore, and Add to dictionary. Uses the local Hunspell engine; " + + "nothing is sent anywhere." + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + textFormat: Text.PlainText + } + + // Availability is a runtime fact, separate from the enabled request: + // a machine without Sonnet or the en_US dictionary still composes. + Text { + objectName: "spellingNeedsSetup" + width: parent.width + visible: !!root.service && !root.service.spellingAvailable + text: root.service && root.service.spellingStatus === "no-module" + ? "Spell-checking is unavailable: the Sonnet QML module is not installed." + : "The " + (root.service ? root.service.spellingLanguage : "en_US") + + " dictionary is not installed. Install the matching Hunspell " + + "dictionary package (for example hunspell-en_us) and reopen settings." + color: root.accentColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + textFormat: Text.PlainText + } + } + + Text { + id: spellingState + objectName: "spellingState" + anchors.right: spellingSwitch.left + anchors.rightMargin: Style.space(8) + anchors.verticalCenter: parent.verticalCenter + text: spellingSwitch.checked ? "On" : "Off" + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + + ToggleSwitch { + id: spellingSwitch + objectName: "spellingSwitch" + anchors.right: parent.right + anchors.rightMargin: Style.space(10) + anchors.verticalCenter: parent.verticalCenter + checked: !root.service || root.service.spellingEnabled !== false + foreground: root.textColor + accent: root.accentColor + onToggled: if (root.service) root.service.setSpellingEnabled(!root.service.spellingEnabled) + } + } + // -------------------------------------------------------- notifications Text { diff --git a/ui/tests/qml/tst_service_settings.qml b/ui/tests/qml/tst_service_settings.qml index 21597fc..da16c84 100644 --- a/ui/tests/qml/tst_service_settings.qml +++ b/ui/tests/qml/tst_service_settings.qml @@ -142,5 +142,55 @@ Item { compare(shellStore.updatedEntry.previewOnCursor, true) compare(shellStore.updatedEntry.markReadDelaySec, 30) } + + // ------------------------------------------------------------ spelling + + function test_spelling_defaults_on_and_persists_changes() { + mailService.applySettings({}) + compare(mailService.spellingEnabled, true) + compare(mailService.spellingLanguage, "en_US") + + mailService.setSpellingEnabled(false) + compare(mailService.spellingEnabled, false) + compare(shellStore.updatedEntry.spellingEnabled, false) + + // A stored value of another shape is not a decision to turn it off. + mailService.applySettings({ spellingEnabled: "no" }) + compare(mailService.spellingEnabled, true) + + mailService.setSpellingLanguage("en_GB") + compare(mailService.spellingLanguage, "en_GB") + compare(shellStore.updatedEntry.spellingLanguage, "en_GB") + } + + function test_spelling_personal_words_add_remove_and_dedupe() { + mailService.applySpellingPersonalWords("") + compare(mailService.spellingPersonalWords.length, 0) + mailService.addPersonalWord("blorptar") + mailService.addPersonalWord("blorptar") + mailService.addPersonalWord("floobert") + compare(mailService.spellingPersonalWords.length, 2) + compare(mailService.spellingPersonalWords[0], "blorptar") + mailService.removePersonalWord("blorptar") + compare(mailService.spellingPersonalWords.length, 1) + compare(mailService.spellingPersonalWords[0], "floobert") + } + + function test_spelling_personal_words_parse_dedupe_and_ignore_junk() { + mailService.applySpellingPersonalWords('{"words":["a","b","a","","c",42,null]}') + compare(mailService.spellingPersonalWords.length, 3) + compare(mailService.spellingPersonalWords[0], "a") + compare(mailService.spellingPersonalWords[1], "b") + compare(mailService.spellingPersonalWords[2], "c") + } + + // The probe loads Sonnet through the same adapter the composer uses; it + // settles into one concrete status on any machine rather than hanging. + function test_spelling_availability_settles_to_a_known_status() { + tryVerify(function() { + var status = mailService.spellingStatus + return status === "ready" || status === "no-dictionary" || status === "no-module" + }, 3000) + } } } diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml index 02085f1..d31db74 100644 --- a/ui/tests/qml/tst_spellcheck_composer.qml +++ b/ui/tests/qml/tst_spellcheck_composer.qml @@ -23,18 +23,25 @@ Item { ] property string accountEmail: "me@example.com" property string activeAccountId: "me@example.com" + property var spellingPersonalWords: [] function preferredSendAs(_r) { return null } function switchTo(_id) { return true } function refreshRecipientContacts() {} function send(_f) { return true } function copyText(_t) { return true } function clipboardAttachment(_dir, callback) { callback({ ok: false, error: "no-image" }); return true } + function addPersonalWord(word) { + if (word && spellingPersonalWords.indexOf(word) < 0) { + var words = spellingPersonalWords.slice(); words.push(word); spellingPersonalWords = words + } + } } Omamail.ComposeView { id: compose anchors.fill: parent service: mailService + spellingPersonalWords: mailService.spellingPersonalWords textColor: Qt.rgba(1, 1, 1, 1) backgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1) accentColor: Qt.rgba(1, 0.5, 0, 1) diff --git a/ui/tests/qml/tst_spellcheck_menu.qml b/ui/tests/qml/tst_spellcheck_menu.qml index 20c2654..7a6ed71 100644 --- a/ui/tests/qml/tst_spellcheck_menu.qml +++ b/ui/tests/qml/tst_spellcheck_menu.qml @@ -24,18 +24,25 @@ Item { ] property string accountEmail: "me@example.com" property string activeAccountId: "me@example.com" + property var spellingPersonalWords: [] function preferredSendAs(_r) { return null } function switchTo(_id) { return true } function refreshRecipientContacts() {} function send(_f) { return true } function copyText(_t) { return true } function clipboardAttachment(_dir, callback) { callback({ ok: false, error: "no-image" }); return true } + function addPersonalWord(word) { + if (word && spellingPersonalWords.indexOf(word) < 0) { + var words = spellingPersonalWords.slice(); words.push(word); spellingPersonalWords = words + } + } } Omamail.ComposeView { id: compose anchors.fill: parent service: mailService + spellingPersonalWords: mailService.spellingPersonalWords textColor: Qt.rgba(1, 1, 1, 1) backgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1) accentColor: Qt.rgba(1, 0.5, 0, 1) From 500b553ee006d84fc5a10fbd3ed1d3d2e2c4ca09 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 15:44:50 -0500 Subject: [PATCH 10/18] S04: Fix spelling persistence, language tracking, and stale corrections Fix the spelling review findings: - The personal dictionary now reaches both host write boundaries (config-store.sh and StandaloneShell.qml), and a refused write is surfaced in Settings instead of silently staying memory-only. - Personal-word writes queue the latest snapshot and merge a late initial read, so an add during an in-flight write or before the file loads is not lost. - The native settings allowlist accepts spellingEnabled and spellingLanguage, with a SettingsStore round-trip test. - The composer and service probe follow spellingLanguage continuously and report no-dictionary for the requested language rather than falling back to English; availability compares the accepted dictionary with the request because Sonnet keeps the prior language on a missing one. - A spelling correction is refused when the body revision moved under the menu, so a repeated misspelling cannot redirect the edit to the wrong occurrence. - Underline geometry re-measures on width, wrap and font changes. - The spelling bindings move from App.qml into ComposeView, keeping App.qml under the 128 KB source ceiling. --- app/qml/StandaloneShell.qml | 2 +- app/src/file_store.cpp | 3 +- app/tests/native/tst_settings.cpp | 14 +++ app/tests/qml/tst_standalone_composition.qml | 7 ++ scripts/config-store.sh | 4 +- tests/test_config_store.sh | 13 +++ ui/App.qml | 3 - ui/Service.qml | 59 +++++++++- ui/components/ComposeView.qml | 56 +++++++-- ui/components/SettingsPage.qml | 16 +++ ui/components/TextMenu.qml | 4 + ui/compose/SpellcheckAdapter.qml | 27 ++++- ui/tests/qml/tst_service_settings.qml | 114 +++++++++++++++++++ ui/tests/qml/tst_spellcheck_composer.qml | 49 +++++++- ui/tests/qml/tst_spellcheck_menu.qml | 21 ++++ 15 files changed, 363 insertions(+), 29 deletions(-) diff --git a/app/qml/StandaloneShell.qml b/app/qml/StandaloneShell.qml index 3d4f1cb..f102631 100644 --- a/app/qml/StandaloneShell.qml +++ b/app/qml/StandaloneShell.qml @@ -84,7 +84,7 @@ QtObject { } function writeConfig(name, text, callback) { - var allowed = ["credentials.json", "window.json", "window-size.json", "calendars.json"] + var allowed = ["credentials.json", "window.json", "window-size.json", "calendars.json", "spelling.json"] if (allowed.indexOf(String(name || "")) < 0 || !fileStore || typeof fileStore.write !== "function") { if (typeof callback === "function") callback(false, "Invalid configuration file") diff --git a/app/src/file_store.cpp b/app/src/file_store.cpp index 2e970ce..884ac8a 100644 --- a/app/src/file_store.cpp +++ b/app/src/file_store.cpp @@ -27,7 +27,8 @@ const QSet &allowedSettings() QStringLiteral("oauthPort"), QStringLiteral("undoSendSeconds"), QStringLiteral("unifiedCalendarView"), QStringLiteral("openOnClick"), QStringLiteral("showBarIcon"), QStringLiteral("suggestEvents"), - QStringLiteral("unifiedMailboxes")}; + QStringLiteral("unifiedMailboxes"), QStringLiteral("spellingEnabled"), + QStringLiteral("spellingLanguage")}; return keys; } diff --git a/app/tests/native/tst_settings.cpp b/app/tests/native/tst_settings.cpp index 350e097..d88e8c0 100644 --- a/app/tests/native/tst_settings.cpp +++ b/app/tests/native/tst_settings.cpp @@ -19,6 +19,7 @@ class SettingsTest : public QObject { private slots: void initTestCase(); void atomicSettingsRoundTrip(); + void acceptsSpellingSettings(); void invalidJsonIsPreserved(); void rejectsCredentialAndUnknownFields(); void fileStoreReadsWritesAndWatches(); @@ -62,6 +63,19 @@ void SettingsTest::atomicSettingsRoundTrip() #endif } +void SettingsTest::acceptsSpellingSettings() +{ + QTemporaryDir directory; + const QString path = directory.filePath(QStringLiteral("settings.json")); + SettingsStore store(path); + QString error; + const QVariantMap settings{{QStringLiteral("spellingEnabled"), false}, + {QStringLiteral("spellingLanguage"), QStringLiteral("en_US")}}; + QVERIFY2(store.replace(settings, &error), qPrintable(error)); + QCOMPARE(store.load(&error), settings); + QVERIFY(error.isEmpty()); +} + void SettingsTest::invalidJsonIsPreserved() { QTemporaryDir directory; diff --git a/app/tests/qml/tst_standalone_composition.qml b/app/tests/qml/tst_standalone_composition.qml index bfb3fda..e755946 100644 --- a/app/tests/qml/tst_standalone_composition.qml +++ b/app/tests/qml/tst_standalone_composition.qml @@ -666,6 +666,13 @@ TestCase { verify(composition.shell.writeConfig("calendars.json", "{}", function(ok) { called = ok })) verify(called) compare(host.files["/fixture/config/omamail/calendars.json"], "{}") + // The personal spelling dictionary goes through the same host boundary; a + // name the shell refuses silently loses an added word at restart. + called = false + verify(composition.shell.writeConfig("spelling.json", "{\"words\":[\"blorptar\"]}", + function(ok) { called = ok })) + verify(called) + compare(host.files["/fixture/config/omamail/spelling.json"], "{\"words\":[\"blorptar\"]}") verify(!composition.shell.writeConfig("../outside", "secret", function() {})) verify(!Object.prototype.hasOwnProperty.call(host.files, "/fixture/config/omamail/../outside")) } diff --git a/scripts/config-store.sh b/scripts/config-store.sh index 4ae64f9..8235566 100755 --- a/scripts/config-store.sh +++ b/scripts/config-store.sh @@ -14,9 +14,9 @@ set -eu name=${1:-} case "$name" in - credentials.json|accounts.json|window.json|calendars.json|compose.json) ;; + credentials.json|accounts.json|window.json|calendars.json|compose.json|spelling.json) ;; *) - printf '%s\n' 'usage: config-store.sh credentials.json|accounts.json|window.json|calendars.json|compose.json' >&2 + printf '%s\n' 'usage: config-store.sh credentials.json|accounts.json|window.json|calendars.json|compose.json|spelling.json' >&2 exit 2 ;; esac diff --git a/tests/test_config_store.sh b/tests/test_config_store.sh index d80cbe1..708fb37 100755 --- a/tests/test_config_store.sh +++ b/tests/test_config_store.sh @@ -56,6 +56,19 @@ done printf '%s\n' '{"zoom":1}' | "$store" window.json >/dev/null grep -q '"zoom":1' "$XDG_CONFIG_HOME/omamail/window.json" +# The app-owned personal spelling dictionary is one of those files. The service +# writes it through the same helper, so a name the writer refused would mean an +# added word never reached disk while the UI said it had. +printf '%s\n' '{"words":["blorptar"]}' | "$store" spelling.json >/dev/null +grep -q '"blorptar"' "$XDG_CONFIG_HOME/omamail/spelling.json" +if stat -c '%a' "$XDG_CONFIG_HOME/omamail/spelling.json" >/dev/null 2>&1; then + spelling_mode=$(stat -c '%a' "$XDG_CONFIG_HOME/omamail/spelling.json") +else + spelling_mode=$(stat -f '%Lp' "$XDG_CONFIG_HOME/omamail/spelling.json") +fi +[ "$spelling_mode" = 600 ] \ + || { echo 'config-store.sh: the personal dictionary must stay owner-only' >&2; exit 1; } + # An unknown name, an empty payload, and the permissions the files are kept at. if printf '%s\n' 'x' | "$store" secrets.json >/dev/null 2>&1; then echo 'config-store.sh: an unknown file name must be refused' >&2 diff --git a/ui/App.qml b/ui/App.qml index f0024ed..cf64c62 100644 --- a/ui/App.qml +++ b/ui/App.qml @@ -2158,9 +2158,6 @@ Item { panelFontFamily: root.fontFamily errorColor: root.urgent contentDirection: root.service ? root.service.contentDirection : "" - spellingEnabled: root.service ? root.service.spellingEnabled : true - spellingLanguage: root.service ? root.service.spellingLanguage : "en_US" - spellingPersonalWords: root.service ? root.service.spellingPersonalWords : [] // The stack follows the view: opening pushes, closing pops — and // the pop is here rather than on `closed`, because a draft parked // for sending closes without saying so. diff --git a/ui/Service.qml b/ui/Service.qml index e004560..130d0dc 100644 --- a/ui/Service.qml +++ b/ui/Service.qml @@ -652,11 +652,17 @@ Item { // App-owned personal words (S00 §4, S6): persisted beside the other window // state, applied by the composer, never written to a global dictionary. + // + // The write is a queue rather than a one-shot. A second word added while the + // first write is still in flight must reach disk too, and an add that lands + // before the initial file read finishes must survive the read. property var spellingPersonalWords: [] property bool spellingPersonalWordsLoaded: false property bool spellingPersonalWordsWriting: false + property bool spellingPersonalWordsPending: false + property string spellingPersonalWordsError: "" - function applySpellingPersonalWords(raw) { + function normalizeSpellingPersonalWords(raw) { var parsed = null try { parsed = JSON.parse(String(raw || "")) } catch (e) { parsed = null } var words = (parsed && Array.isArray(parsed.words)) ? parsed.words : [] @@ -666,15 +672,45 @@ Item { if (typeof word !== "string") continue if (word !== "" && next.indexOf(word) < 0) next.push(word) } + return next + } + + // Replace the list. The FileView load path uses `mergeSpellingPersonalWords` + // below; this is the explicit/reset form and what the tests drive. + function applySpellingPersonalWords(raw) { + spellingPersonalWords = normalizeSpellingPersonalWords(raw) + spellingPersonalWordsLoaded = true + if (spellingPersonalWordsPending) saveSpellingPersonalWords() + } + + // A load that arrives after the user has already added a word must union, + // not replace: the in-memory additions are this session's intent and the + // disk copy is yesterday's. + function mergeSpellingPersonalWords(raw) { + var onDisk = normalizeSpellingPersonalWords(raw) + var next = spellingPersonalWords.slice() + for (var i = 0; i < onDisk.length; i++) { + if (next.indexOf(onDisk[i]) < 0) next.push(onDisk[i]) + } spellingPersonalWords = next spellingPersonalWordsLoaded = true + if (spellingPersonalWordsPending) saveSpellingPersonalWords() } function saveSpellingPersonalWords() { - if (!spellingPersonalWordsLoaded || spellingPersonalWordsWriting) return + // Before the load completes, remember that there is something to write so + // the load can flush it rather than dropping it. + if (!spellingPersonalWordsLoaded) { spellingPersonalWordsPending = true; return } + if (spellingPersonalWordsWriting) { spellingPersonalWordsPending = true; return } spellingPersonalWordsWriting = true - writeConfig("spelling.json", JSON.stringify({ words: spellingPersonalWords }), function(ok) { + spellingPersonalWordsPending = false + writeConfig("spelling.json", JSON.stringify({ words: spellingPersonalWords }), function(ok, error) { root.spellingPersonalWordsWriting = false + // The write boundaries can refuse the file (a host allowlist that has + // not been told about it, a full disk): keep the failure where the + // Settings page can say so instead of pretending the word saved. + root.spellingPersonalWordsError = ok ? "" : String(error || "Could not save personal words") + if (root.spellingPersonalWordsPending) root.saveSpellingPersonalWords() }) } @@ -2698,18 +2734,29 @@ Item { id: spellingWordsFile path: root.configPath("spelling.json") printErrors: false - onLoaded: root.applySpellingPersonalWords(text()) - onLoadFailed: root.applySpellingPersonalWords("") + // Merge rather than replace: a word added before the read returned is this + // session's and must not be undone by yesterday's file. + onLoaded: root.mergeSpellingPersonalWords(text()) + onLoadFailed: root.mergeSpellingPersonalWords("") } // Availability probe: loads Sonnet once so the settings page can explain a - // missing module or dictionary without a compose window open. + // missing module or dictionary without a compose window open. Its language + // follows the setting so the status is about the *requested* dictionary, not + // a default-English fallback. Loader { id: spellingProbe active: true source: "compose/SpellcheckAdapter.qml" } + Binding { + target: spellingProbe.item + property: "language" + value: root.spellingLanguage + when: spellingProbe.item !== null + } + Timer { id: windowPrefsSettling interval: 500 diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index 0da6d97..eaa0a06 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -41,9 +41,17 @@ DropArea { // Spelling settings (S04): read from the service, applied to the adapter. // The service owns the values and persistence; the composer only applies // them. Missing support is reported via spellingStatus. - property bool spellingEnabled: true - property string spellingLanguage: "en_US" - property var spellingPersonalWords: [] + // The spelling settings live on the service; the composer follows them when + // one is wired, and falls back to the defaults for the tests and previews + // that instantiate it bare. A caller may still assign over the binding. + property bool spellingEnabled: service && service.spellingEnabled !== undefined + ? service.spellingEnabled : true + property string spellingLanguage: service && service.spellingLanguage !== undefined + ? String(service.spellingLanguage) : "en_US" + property var spellingPersonalWords: service ? service.spellingPersonalWords : [] + // Bumped on every body change so a menu opened before an edit can tell that + // the text under its saved position moved (finding 5). + property int bodyRevision: 0 // Body checking is on only when the optional Sonnet adapter loaded and // reports a dictionary for the requested language. readonly property bool spellingAvailable: spellcheckLoader.status === Loader.Ready @@ -57,6 +65,12 @@ DropArea { readonly property var spellingAdapter: spellcheckLoader.item // Finished misspelled words as {start, end} UTF-16 offsets into the body text. property var spellingRanges: [] + // Reads the layout inputs that positionToRectangle() consumes in C++, where + // the binding engine cannot see them. The underline bindings read this so a + // resize, wrap or font change re-measures their geometry (finding 9). + readonly property string spellingLayoutKey: + bodyEdit.width + ":" + bodyEdit.wrapMode + ":" + bodyEdit.font.pixelSize + + ":" + bodyEdit.font.family // The theme's error role, drawn under misspelled words. The composer draws // the underline itself because Sonnet's QML highlighter also colours the word // red; see planning/decisions/S00.md and the S01 handoff. @@ -94,6 +108,7 @@ DropArea { var position = editor.positionAt(x, y) var info = adapter.inspect(position) textMenu.spellingPosition = position + textMenu.spellingRevision = root.bodyRevision textMenu.spellingWord = info.word textMenu.spellingMisspelled = info.misspelled textMenu.spellingSuggestions = info.suggestions @@ -108,6 +123,7 @@ DropArea { var info = adapter.inspect(position) if (!info.misspelled || info.suggestions.length === 0) return false textMenu.spellingPosition = position + textMenu.spellingRevision = root.bodyRevision textMenu.spellingWord = info.word textMenu.spellingMisspelled = true textMenu.spellingSuggestions = info.suggestions @@ -1921,6 +1937,7 @@ DropArea { root.bodyWasEdited = true root.noteUserModified() } + root.bodyRevision += 1 spellingDebounce.restart() } Keys.priority: Keys.BeforeItem @@ -1942,11 +1959,22 @@ DropArea { model: root.spellingRanges delegate: Rectangle { required property var modelData + objectName: "spelling-underline" // positionToRectangle gives the caret at a position (width 1), so // the right edge of the word is the caret one past its last // character, not the last character's own rectangle. - readonly property rect fromRect: bodyEdit.positionToRectangle(modelData.start) - readonly property rect toRect: bodyEdit.positionToRectangle(modelData.end) + // + // The layout key is named inside these bindings on purpose: the + // function reads width, wrap and font in C++, so without it a + // reflow would leave the underline where the word used to be. + readonly property rect fromRect: { + root.spellingLayoutKey + return bodyEdit.positionToRectangle(modelData.start) + } + readonly property rect toRect: { + root.spellingLayoutKey + return bodyEdit.positionToRectangle(modelData.end) + } x: fromRect.x y: fromRect.y + fromRect.height - height width: Math.max(2, fromRect.y === toRect.y @@ -1972,12 +2000,20 @@ DropArea { if (!item) return item.document = bodyEdit.textDocument item.enabled = root.spellingEnabled - item.language = root.spellingLanguage item.personalWords = root.spellingPersonalWords root.refreshSpellingRanges() } } + // The language is a binding, not a one-time assignment at load: a later + // Settings change must reach an already-open adapter (finding 6). + Binding { + target: spellcheckLoader.item + property: "language" + value: root.spellingLanguage + when: spellcheckLoader.item !== null + } + Rectangle { objectName: "compose-body-restore-flash" anchors.fill: bodyFlick @@ -2177,9 +2213,11 @@ DropArea { var adapter = root.spellingAdapter if (!adapter) return // The menu outlives its click: a draft can change underneath it (a reply - // quote arriving, an agent answer landing) while it is open. Re-check the - // word at the saved position before editing, so a stale position never - // rewrites whatever text now sits there. + // quote arriving, an agent answer landing) while it is open. A revision + // that moved means the saved position no longer addresses the word the + // menu offered, which the word string alone cannot tell when the same + // misspelling appears more than once. Re-check both before editing. + if (textMenu.spellingRevision !== root.bodyRevision) return var now = adapter.inspect(textMenu.spellingPosition) if (now.word !== textMenu.spellingWord || !now.misspelled) return adapter.applyCorrection(textMenu.spellingPosition, replacement) diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml index e27f330..19cba12 100644 --- a/ui/components/SettingsPage.qml +++ b/ui/components/SettingsPage.qml @@ -752,6 +752,22 @@ Column { wrapMode: Text.WordWrap textFormat: Text.PlainText } + + // The personal word list is the one spelling write that can be refused + // by the host. The word stays in memory for the session, but a failed + // save has to say so rather than quietly vanish at restart. + Text { + objectName: "spellingPersonalWordsError" + width: parent.width + visible: !!root.service && String(root.service.spellingPersonalWordsError || "") !== "" + text: "Personal words could not be saved: " + + (root.service ? root.service.spellingPersonalWordsError : "") + color: root.accentColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + textFormat: Text.PlainText + } } Text { diff --git a/ui/components/TextMenu.qml b/ui/components/TextMenu.qml index 9a8f228..37cd828 100644 --- a/ui/components/TextMenu.qml +++ b/ui/components/TextMenu.qml @@ -32,6 +32,10 @@ Item { // UTF-16 offset the suggestions were taken from, kept so a correction still // targets the clicked word if the caret has moved by the time one is picked. property int spellingPosition: -1 + // The document revision the suggestions were taken from. The owner refuses + // a correction when its live revision has moved on, so editing elsewhere + // cannot redirect the correction to the same word at a shifted position. + property int spellingRevision: -1 property string spellingWord: "" property bool spellingMisspelled: false property var spellingSuggestions: [] diff --git a/ui/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml index 906148e..c62b7f7 100644 --- a/ui/compose/SpellcheckAdapter.qml +++ b/ui/compose/SpellcheckAdapter.qml @@ -29,7 +29,18 @@ Item { // settings layer (S04); this property only applies them. property var personalWords: [] - readonly property bool available: highlighter.spellCheckerFound + // Availability is about the *requested* language, and it is computed after + // `setCurrentLanguage` rather than bound to `spellCheckerFound`. + // + // When the requested dictionary is missing, Sonnet keeps the prior language + // and leaves `spellCheckerFound` true, so asking for `zz_ZZ` while `en_US` is + // installed would still read as ready. The accepted language is + // `currentLanguage`; comparing it with the request is what says "no + // dictionary for this one". The backing property is assigned in + // `applySettings` because `currentLanguage` does not notify, so a binding + // would hold a stale answer after the revert. + property bool requestedLanguageAvailable: false + readonly property bool available: requestedLanguageAvailable // "ready", "disabled", or "no-dictionary". A missing module is reported by // the owning Loader as Loader.Error, not here. readonly property string status: !enabled ? "disabled" @@ -108,11 +119,15 @@ Item { function isApostrophe(character) { return character === "'" || character === "\u2019" } function applySettings() { - if (!available) return - if (enabled) { - highlighter.setCurrentLanguage(language) - applyPersonalWords() - } + // The request is attempted even when the previous one reverted: a later + // successful call is the only way back from a missing dictionary, and + // guarding on the prior result would leave the switch unrecoverable. + highlighter.setCurrentLanguage(language) + // Sonnet reports the language it accepted. A request it could not serve + // leaves the prior one in place, which is the no-dictionary answer. + requestedLanguageAvailable = highlighter.spellCheckerFound + && highlighter.currentLanguage === language + if (enabled) applyPersonalWords() } function applyPersonalWords() { diff --git a/ui/tests/qml/tst_service_settings.qml b/ui/tests/qml/tst_service_settings.qml index da16c84..9ed1732 100644 --- a/ui/tests/qml/tst_service_settings.qml +++ b/ui/tests/qml/tst_service_settings.qml @@ -19,9 +19,32 @@ Item { } } + // The personal dictionary write is asynchronous and may fail. This stands in + // for the host writer so a test can hold the reply and complete it later. + QtObject { + id: configPlatform + property var writes: [] + property var callbacks: [] + function writeConfig(name, text, callback) { + writes = writes.concat([{ name: String(name), text: String(text) }]) + callbacks = callbacks.concat([callback]) + return true + } + function confirm(index, ok, error) { + var cb = callbacks[index] + if (typeof cb !== "function") return false + var next = callbacks.slice() + next[index] = null + callbacks = next + cb(ok, error) + return true + } + } + Omamail.Service { id: mailService shell: shellStore + platform: configPlatform manifest: ({ id: "omamail", __sourceDir: "/tmp/omamail-test" }) } @@ -34,6 +57,14 @@ Item { TestCase { name: "ServiceSettings" + function init() { + configPlatform.writes = [] + configPlatform.callbacks = [] + mailService.spellingPersonalWordsWriting = false + mailService.spellingPersonalWordsPending = false + mailService.spellingPersonalWordsError = "" + } + function test_scoped_manifest_resolves_bundled_helpers_without_private_metadata() { verify(scopedMailService.pluginDir !== "") verify(scopedMailService.pluginDir.indexOf("%") < 0, @@ -184,6 +215,71 @@ Item { compare(mailService.spellingPersonalWords[2], "c") } + // Two words added while the first write is still in flight: the second is + // queued and written after the first completes, so disk ends with both. + function test_spelling_personal_words_queue_changes_during_a_write() { + mailService.applySpellingPersonalWords("") + configPlatform.writes = [] + configPlatform.callbacks = [] + mailService.addPersonalWord("alpha") + compare(configPlatform.writes.length, 1) + compare(JSON.parse(configPlatform.writes[0].text).words.length, 1) + mailService.addPersonalWord("beta") + compare(configPlatform.writes.length, 1, "the second add waits for the in-flight write") + compare(configPlatform.confirm(0, true, ""), true) + compare(configPlatform.writes.length, 2, "the queued snapshot is written once the first completes") + compare(JSON.parse(configPlatform.writes[1].text).words.length, 2) + compare(configPlatform.confirm(1, true, ""), true) + compare(mailService.spellingPersonalWordsError, "") + } + + // A refused write is recorded rather than swallowed, and the next change + // asks the host again. + function test_spelling_personal_words_retry_after_a_failed_write() { + mailService.applySpellingPersonalWords("") + configPlatform.writes = [] + configPlatform.callbacks = [] + mailService.addPersonalWord("alpha") + compare(configPlatform.confirm(0, false, "disk full"), true) + compare(mailService.spellingPersonalWordsError, "disk full") + mailService.addPersonalWord("beta") + compare(configPlatform.writes.length, 2, "a later change retries the failed write") + compare(configPlatform.confirm(1, true, ""), true) + compare(mailService.spellingPersonalWordsError, "") + } + + // Write then read: what a completed write put in the file is what a later + // read restores, which is the restart guarantee the old path never had. + function test_spelling_personal_words_round_trip_through_a_restart() { + mailService.applySpellingPersonalWords("") + configPlatform.writes = [] + configPlatform.callbacks = [] + mailService.addPersonalWord("blorptar") + compare(configPlatform.confirm(0, true, ""), true) + var saved = configPlatform.writes[0].text + // A restart reads the file back with no words in memory. + mailService.applySpellingPersonalWords(saved) + compare(mailService.spellingPersonalWords.length, 1) + compare(mailService.spellingPersonalWords[0], "blorptar") + } + + // A word added before the initial read returns is the session's, not the + // file's: the later load unions the two instead of replacing memory. + function test_spelling_personal_words_merge_a_late_load() { + mailService.applySpellingPersonalWords("") + configPlatform.writes = [] + configPlatform.callbacks = [] + mailService.spellingPersonalWordsLoaded = false + mailService.addPersonalWord("alpha") + compare(configPlatform.writes.length, 0, "nothing is written before the load completes") + mailService.mergeSpellingPersonalWords('{"words":["beta","alpha"]}') + compare(mailService.spellingPersonalWords.length, 2) + verify(mailService.spellingPersonalWords.indexOf("alpha") >= 0) + verify(mailService.spellingPersonalWords.indexOf("beta") >= 0) + compare(configPlatform.writes.length, 1, "the deferred add is flushed after the load") + compare(configPlatform.confirm(0, true, ""), true) + } + // The probe loads Sonnet through the same adapter the composer uses; it // settles into one concrete status on any machine rather than hanging. function test_spelling_availability_settles_to_a_known_status() { @@ -192,5 +288,23 @@ Item { return status === "ready" || status === "no-dictionary" || status === "no-module" }, 3000) } + + // Availability is about the requested dictionary, not a default-English + // fallback: a missing language reads no-dictionary and setting it back + // recovers. + function test_spelling_availability_follows_the_requested_language() { + tryVerify(function() { + var status = mailService.spellingStatus + return status === "ready" || status === "no-dictionary" || status === "no-module" + }, 3000) + if (mailService.spellingStatus === "no-module") { skip("Sonnet is not installed"); return } + mailService.setSpellingLanguage("en_US") + tryVerify(function() { return mailService.spellingStatus === "ready" }, 3000) + mailService.setSpellingLanguage("zz_ZZ") + tryVerify(function() { return mailService.spellingStatus === "no-dictionary" }, 3000) + compare(mailService.spellingAvailable, false) + mailService.setSpellingLanguage("en_US") + tryVerify(function() { return mailService.spellingStatus === "ready" }, 3000) + } } } diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml index d31db74..10aba40 100644 --- a/ui/tests/qml/tst_spellcheck_composer.qml +++ b/ui/tests/qml/tst_spellcheck_composer.qml @@ -67,7 +67,13 @@ Item { return null } - function init() { compose.begin("new", null, "", []) } + function init() { + compose.begin("new", null, "", []) + // Reset the layout and the requested language: an earlier case may have + // narrowed the composer or pointed at a dictionary that is not here. + compose.parent.width = 900 + compose.spellingLanguage = "en_US" + } function test_body_adapter_attaches_and_checking_does_not_mutate() { var body = named(compose, "compose-body-editor") @@ -186,6 +192,47 @@ Item { verify(menu.spellingSuggestions.length > 0) } + // The adapter's language follows the setting after load, and availability + // is about the requested dictionary: a missing one reads no-dictionary and + // switching back recovers, with no silent fallback to English. + function test_language_follows_the_setting_and_reports_a_missing_dictionary() { + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (compose.spellingStatus === "no-module") { skip("Sonnet is not installed"); return } + compose.spellingLanguage = "en_US" + tryVerify(function() { return compose.spellingStatus === "ready" }, 3000) + compose.spellingLanguage = "zz_ZZ" + tryVerify(function() { return compose.spellingStatus === "no-dictionary" }, 3000) + compare(compose.spellingAvailable, false) + compose.spellingLanguage = "en_US" + tryVerify(function() { return compose.spellingStatus === "ready" }, 3000) + compare(compose.spellingAvailable, true) + } + + // The underline is positioned from positionToRectangle(), which reads the + // editor's width, wrap and font in C++. The binding has to name those + // inputs, or a wrapped word keeps an underline where the word used to be. + function test_underline_follows_the_editor_when_it_resizes() { + var body = named(compose, "compose-body-editor") + verify(body) + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (!compose.spellingAvailable) { skip("spelling unavailable (" + compose.spellingStatus + ")"); return } + body.text = "hello hello hello hello hello hello hello hello hello hello hello hello wrod here " + wait(250) + compare(compose.spellingRanges.length, 1) + var start = compose.spellingRanges[0].start + var underline = named(compose, "spelling-underline") + verify(underline, "a misspelled word draws an underline") + var wide = body.positionToRectangle(start) + fuzzyCompare(underline.x, wide.x, 1.0) + compose.parent.width = 300 + wait(100) + var narrow = body.positionToRectangle(start) + verify(narrow.x !== wide.x || narrow.y !== wide.y, + "the narrower editor re-wraps the word") + fuzzyCompare(underline.x, narrow.x, 1.0) + fuzzyCompare(underline.y, narrow.y + narrow.height - underline.height, 1.0) + } + function test_disabling_unloads_the_adapter_and_re_enabling_restores_it() { tryVerify(function() { return compose.spellingAdapter !== null }, 3000) compose.spellingEnabled = false diff --git a/ui/tests/qml/tst_spellcheck_menu.qml b/ui/tests/qml/tst_spellcheck_menu.qml index 7a6ed71..42bcdad 100644 --- a/ui/tests/qml/tst_spellcheck_menu.qml +++ b/ui/tests/qml/tst_spellcheck_menu.qml @@ -171,6 +171,27 @@ Item { compare(editor.text, before) } + // A revision guard, not a word-string guard. Two occurrences of the same + // misspelling make the string at the old position still spell `wrod`, so + // comparing only the word would let an edit at the front of the draft + // redirect the correction to the first occurrence. + function test_stale_same_word_aborts_the_correction() { + var editor = body() + editor.text = "a wrod and wrod here" + clickWord(editor, "wrod", editor.text.indexOf("wrod") + 1) // the second one + var m = menu() + compare(m.spellingWord, "wrod") + // Insert text ahead of both words while the menu is open: positions shift + // but the word string at the saved position is unchanged. + editor.insert(0, "12345678 ") + var before = editor.text + m.chooseSuggestion(0) + wait(20) + compare(editor.text, before, + "a changed document must refuse the correction even when the word repeats") + compare(editor.text.indexOf("wrod"), before.indexOf("wrod")) + } + function test_no_suggestions_offers_ignore_and_add_but_no_rows() { var editor = body() editor.text = "a zxqjklv here " From 8a595a4ad6669c0d2dc911a085c25e5f61219644 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 16:40:23 -0500 Subject: [PATCH 11/18] S04: recheck underlines after a valid-to-valid dictionary switch --- ui/components/ComposeView.qml | 4 +++ ui/tests/qml/tst_spellcheck_composer.qml | 33 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index eaa0a06..aa32457 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -86,6 +86,10 @@ DropArea { } onSpellingAvailableChanged: refreshSpellingRanges() onSpellingEnabledChanged: refreshSpellingRanges() + // A valid-to-valid language switch leaves `spellingAvailable` true, so the + // ranges would keep the old dictionary's underlines. Re-check after the + // adapter has applied the new language (the debounce lets that land first). + onSpellingLanguageChanged: spellingDebounce.restart() Timer { id: spellingDebounce diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml index 10aba40..81becdc 100644 --- a/ui/tests/qml/tst_spellcheck_composer.qml +++ b/ui/tests/qml/tst_spellcheck_composer.qml @@ -242,5 +242,38 @@ Item { tryVerify(function() { return compose.spellingAdapter !== null }, 3000) compare(compose.spellingAvailable, true) } + + // Switching between two *available* dictionaries must re-run the underline + // ranges: availability stays true, so only a language-change refresh keeps + // the old dictionary's underlines from lingering. + function test_a_valid_to_valid_language_switch_rechecks_ranges() { + var body = named(compose, "compose-body-editor") + tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + if (compose.spellingStatus === "no-module") { skip("Sonnet is not installed"); return } + + compose.spellingLanguage = "en_GB" + tryVerify(function() { + return compose.spellingStatus === "ready" || compose.spellingStatus === "no-dictionary" + }, 3000) + if (compose.spellingStatus !== "ready") { + compose.spellingLanguage = "en_US" + skip("en_GB dictionary unavailable"); return + } + + // British spellings are misspelled in en_US and correct in en_GB. + var sample = "colour favourite cancelled organise centre metre neighbour travelling" + compose.spellingLanguage = "en_US" + body.text = sample + " " + wait(250) + var usRanges = compose.spellingRanges.length + verify(usRanges > 0, "en_US marks the British spellings") + + compose.spellingLanguage = "en_GB" + wait(250) + var live = JSON.stringify(compose.spellingRanges) + var actual = JSON.stringify(compose.spellingAdapter.misspelledRanges(body.text)) + compare(live, actual, "ranges recheck after a valid-to-valid switch") + verify(compose.spellingRanges.length < usRanges, "en_GB accepts the British spellings") + } } } From c32dcfab9c244f6771509ec3a12fe9b2cb07525c Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 21:37:19 -0500 Subject: [PATCH 12/18] fix: Keep spelling actions from dirtying unchanged drafts --- ui/components/ComposeView.qml | 12 ++++++- ui/compose/SpellcheckAdapter.qml | 13 +++++-- ui/compose/SpellingSession.js | 17 ++++++++++ ui/tests/qml/tst_spellcheck_composer.qml | 43 ++++++++++++++++++++++++ ui/tests/qml/tst_spellcheck_menu.qml | 33 ++++++++++++++++++ 5 files changed, 115 insertions(+), 3 deletions(-) create mode 100644 ui/compose/SpellingSession.js diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index aa32457..68a538d 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -125,7 +125,7 @@ DropArea { if (!adapter || !spellingAvailable) return false var position = bodyEdit.cursorPosition var info = adapter.inspect(position) - if (!info.misspelled || info.suggestions.length === 0) return false + if (!info.misspelled) return false textMenu.spellingPosition = position textMenu.spellingRevision = root.bodyRevision textMenu.spellingWord = info.word @@ -1935,7 +1935,12 @@ DropArea { selectedTextColor: root.textColor font.family: root.panelFontFamily font.pixelSize: Style.font.bodySmall + property string lastPlainText: "" onTextChanged: { + // Sonnet can emit textChanged while rehighlighting an unchanged + // document. Only a plain-text change edits the draft or its revision. + if (text === lastPlainText) return + lastPlainText = text root.noteDraftChanged() if (!root.settingBodyText && activeFocus) { root.bodyWasEdited = true @@ -2018,6 +2023,11 @@ DropArea { when: spellcheckLoader.item !== null } + Connections { + target: spellcheckLoader.item + function onCheckerChanged() { spellingDebounce.restart() } + } + Rectangle { objectName: "compose-body-restore-flash" anchors.fill: bodyFlick diff --git a/ui/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml index c62b7f7..9874358 100644 --- a/ui/compose/SpellcheckAdapter.qml +++ b/ui/compose/SpellcheckAdapter.qml @@ -1,5 +1,6 @@ import QtQuick import org.kde.sonnet as Sonnet +import "SpellingSession.js" as Session // Optional spelling adapter (S01). This is the only production file that // imports org.kde.sonnet, so it is always created through a Loader: a machine @@ -11,7 +12,8 @@ import org.kde.sonnet as Sonnet // paints the misspelled word red as well as underlining it (its errorFormat // sets a red foreground; misspelledColor is inert), unlike the QWidget one, // which only underlines. So the highlighter here stays inactive and is used -// only as a checker: it never writes any format to the document. +// only as a checker. Ignore can still cause a rehighlight notification, which +// the editor must distinguish from an actual plain-text edit. Item { id: adapter @@ -46,7 +48,12 @@ Item { readonly property string status: !enabled ? "disabled" : (available ? "ready" : "no-dictionary") - Component.onCompleted: applySettings() + signal checkerChanged() + Component.onCompleted: { + Session.subscribe(adapter) + applySettings() + } + Component.onDestruction: Session.unsubscribe(adapter) onEnabledChanged: applySettings() onLanguageChanged: applySettings() onPersonalWordsChanged: applyPersonalWords() @@ -78,6 +85,7 @@ Item { function ignoreForSession(word) { if (!available || !word) return highlighter.ignoreWord(String(word)) + Session.changed() } // Every misspelled word that is finished, as UTF-16 {start, end} offsets into @@ -136,6 +144,7 @@ Item { var word = String(personalWords[i]) if (word !== "") highlighter.ignoreWord(word) } + Session.changed() } onDocumentChanged: if (document !== null) highlighter.document = document diff --git a/ui/compose/SpellingSession.js b/ui/compose/SpellingSession.js new file mode 100644 index 0000000..65982a2 --- /dev/null +++ b/ui/compose/SpellingSession.js @@ -0,0 +1,17 @@ +.pragma library + +// Sonnet's ignore list is shared by the process. Notify every live adapter +// when it changes so each composer updates its cached underline ranges. +var adapters = [] + +function subscribe(adapter) { adapters.push(adapter) } + +function unsubscribe(adapter) { + var index = adapters.indexOf(adapter) + if (index >= 0) adapters.splice(index, 1) +} + +function changed() { + var current = adapters.slice() + for (var i = 0; i < current.length; i++) current[i].checkerChanged() +} diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml index 81becdc..614761e 100644 --- a/ui/tests/qml/tst_spellcheck_composer.qml +++ b/ui/tests/qml/tst_spellcheck_composer.qml @@ -92,6 +92,49 @@ Item { compare(body.text, before) } + function test_session_ignore_refreshes_a_separate_composer_document() { + var body = named(compose, "compose-body-editor") + tryVerify(function() { return compose.spellingAvailable }, 3000) + body.text = "the zqxjremotereviewhere here " + tryCompare(compose, "spellingRanges", [{ start: 4, end: 24 }]) + var component = Qt.createComponent("../../compose/SpellcheckAdapter.qml") + compare(component.status, Component.Ready) + var secondDoc = Qt.createQmlObject('import QtQuick; TextEdit { text: "zqxjremotereviewhere " }', compose) + var second = component.createObject(compose, { document: secondDoc.textDocument }) + try { + verify(second.available) + second.ignoreForSession("zqxjremotereviewhere") + tryVerify(function() { return compose.spellingRanges.length === 0 }) + compare(compose.spellingAdapter.inspect(6).misspelled, false) + } finally { + second.destroy() + secondDoc.destroy() + } + } + + function test_personal_words_preserve_focused_draft_selection_and_undo() { + var body = named(compose, "compose-body-editor") + tryVerify(function() { return compose.spellingAvailable }, 3000) + body.text = "the zqxjpersonalreviewhere here " + body.forceActiveFocus() + body.select(4, 9) + compose.userModified = false + compose.bodyWasEdited = false + var before = body.text + var selected = body.selectedText + var revision = compose.bodyRevision + var undoAvailable = body.canUndo + mailService.addPersonalWord("zqxjpersonalreviewhere") + wait(250) + compare(body.text, before) + compare(body.selectedText, selected) + compare(body.canUndo, undoAvailable) + compare(compose.userModified, false) + compare(compose.bodyWasEdited, false) + compare(compose.bodyRevision, revision) + compare(compose.spellingRanges.length, 0) + } + function test_a_correction_changes_the_body_and_undo_restores_it() { var body = named(compose, "compose-body-editor") verify(body) diff --git a/ui/tests/qml/tst_spellcheck_menu.qml b/ui/tests/qml/tst_spellcheck_menu.qml index 42bcdad..2e71501 100644 --- a/ui/tests/qml/tst_spellcheck_menu.qml +++ b/ui/tests/qml/tst_spellcheck_menu.qml @@ -72,6 +72,7 @@ Item { function menu() { return named(compose, "compose-text-menu") } function init() { + compose.parent.forceActiveFocus() compose.begin("new", null, "", []) tryVerify(function() { return compose.spellingAdapter !== null }, 3000) if (!compose.spellingAvailable) skip("spelling unavailable (" + compose.spellingStatus + ")") @@ -222,6 +223,38 @@ Item { compare(editor.text, "a " + suggestion + " here") } + function test_keyboard_opens_ignore_and_add_without_suggestions() { + var editor = body() + editor.text = "the zxqjklv here " + editor.cursorPosition = 8 + compare(compose.spellingAdapter.inspect(8).suggestions.length, 0) + editor.forceActiveFocus() + keyClick(Qt.Key_Period, Qt.ControlModifier) + tryCompare(menu(), "opened", true) + compare(menu().spellingMisspelled, true) + verify(menu().ignoreWordRow.visible) + verify(menu().addToDictionaryRow.visible) + menu().close() + } + + function test_menu_ignore_preserves_clean_draft_and_revision() { + var editor = body() + editor.text = "the zqxjmenureviewhere here " + editor.forceActiveFocus() + compose.userModified = false + compose.bodyWasEdited = false + var before = editor.text + var revision = compose.bodyRevision + clickWord(editor, "zqxjmenureviewhere") + menu().ignoreWordRow.activated() + wait(250) + compare(editor.text, before) + compare(compose.userModified, false) + compare(compose.bodyWasEdited, false) + compare(compose.bodyRevision, revision) + compare(compose.spellingRanges.length, 0) + } + function test_opening_and_closing_never_edits_or_dirties() { var editor = body() editor.text = "a wrod here" From 39d4dd58ed15f63f07f96402d58bf88c543e02a5 Mon Sep 17 00:00:00 2001 From: Chris Gray Date: Tue, 29 Sep 2026 21:41:11 -0500 Subject: [PATCH 13/18] docs: Record spelling review fixes and validation limits --- planning/evidence/SPELLING-REVIEW.md | 71 ++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 planning/evidence/SPELLING-REVIEW.md diff --git a/planning/evidence/SPELLING-REVIEW.md b/planning/evidence/SPELLING-REVIEW.md new file mode 100644 index 0000000..4506f9c --- /dev/null +++ b/planning/evidence/SPELLING-REVIEW.md @@ -0,0 +1,71 @@ +# Spelling review follow-up + +Reviewed source: `c32dcfab9c244f6771509ec3a12fe9b2cb07525c`. +Base: `d88833e44ae64d8b72ebb7ab3a1f014b16fd89f5`. +Environment: Linux, Rust 1.98.1, Qt 6.11.2, Sonnet 6.29.0, +hunspell-en_us 2026.02.25-1. Fixtures use synthetic text and temporary HOME/XDG +roots. Scope is the composer body; subject checking remains deferred. + +## Findings resolved + +- Sonnet Ignore can emit textChanged during rehighlighting even with its visual + highlighter inactive. The composer previously treated the unchanged text as + a user edit. It now compares plain text before updating dirty state, recovery, + or the correction-menu revision. Ignore and shared personal-word updates keep + unchanged focused drafts clean, with selection and undo history preserved. +- Sonnet's process-wide ignore list changed another composer's checking answer + without updating its cached underlines. Live adapters now broadcast checker + changes and unregister on destruction. Other composers recheck their ranges. +- Ctrl+. previously refused misspellings with no replacements. It now opens + the menu so keyboard users can reach Ignore and Add to dictionary. + +The fresh independent reviewer reproduced the three issues with real Sonnet, +then verified the fixes and their source hashes. Nine independent checks pass, +including adapter destruction, Loader off/on, real text edits, Undo, and Redo. +Four tracked regressions cover menu Ignore, a separate document's session +Ignore, shared personal-word changes, and the no-suggestions keyboard path. + +## Validation + +| Command or scenario | Result | +| --- | --- | +| `make validate` | Exit 2: Rust/JS/shell passed; QML 1053 passed, 8 failed, no skips | +| Rust targets inside validate | All pass; library 555 passed, 11 ignored | +| Actual Sonnet adapter/composer/menu suites | 9 / 15 / 16 passed, no failures or skips | +| Independent fix verification | 9 passed, no failures or skips | +| Real missing-Sonnet runner with isolated qt.conf | Production composer edit/Undo 3 passed; standalone composition fixture 30 passed | +| `make test-js test-shell test-app-qml qml-check` | Exit 0; existing QML warnings retained | +| `QT_QPA_PLATFORM=offscreen ctest --test-dir app/build --output-on-failure --no-tests=error -R '^tst_settings$'` | Exit 0; native settings test passed | +| `cmake --build app/build -j2` | Exit 0; rebuilt standalone app with the new session library embedded | +| `QT_QPA_PLATFORM=offscreen ctest --test-dir app/build --output-on-failure --no-tests=error -R '^tst_(settings|resources)$'` | Exit 0; settings and embedded-resource tests passed | +| `omarchy plugin validate .` and `git diff --check` | Exit 0 | +| `python3 tests/test_backend_api.py --binary target/debug/omamail` | Exit 0; unchanged API 6, 30 methods, 178 advertised | +| `python3 tests/test_backend_process.py` | Exit 0; real native bridge scenarios pass | + +The missing-module standalone fixture does not include the compiled +NativeProcess host; it proves graceful optional loading, not full host +integration. Logs, restricted-runner fixtures, and independent review remain +in ignored `artifacts/final-review/`. Screenshots show synthetic production-UI +previews, not persisted settings across a real host restart. + +## Baseline adjudication and judgment + +The exact base, built from its own source under the same environment, reproduces +the same eight `KeyboardReaderNavigation` failures. Those are accepted as +inherited regression limitations; full validation is not reported green. +The known first-line-only underline for a word wrapping across visual lines +remains the documented S01 limitation. + +Security: **PASS for the reviewed spelling/configuration changes**. The fresh +review checked local-only spelling, app-owned private configuration, optional +loading, and absence of global dictionary/preferences writes in isolated tests. +It found no additional defect in the fixes. This is scoped to the changed +boundary, not a certification of the upstream application. + +Release acceptance: **REVISE**. Fresh real Service/FileView restart evidence for +personal-word persistence and session-ignore lifetime, installed-dictionary +rediscovery, and IME behavior still need acceptance evidence. The current +“reopen settings” installation guidance is an unverified recovery claim because +the service probe stays loaded. Combined-feature integration and private-runtime +provenance/rollback remain I00/R00/J00 work. No merge, release, or daily-runtime +replacement approval is recorded here. From ba7e537f4dd54b051683b26a4cd8f4da7a6e8011 Mon Sep 17 00:00:00 2001 From: Chris Gray <216301595+latentoperator@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:05:48 -0500 Subject: [PATCH 14/18] Drop internal task references from source comments --- tests/spellcheck/composer-preview.qml | 2 +- tests/spellcheck/playground.qml | 8 ++++---- ui/Service.qml | 4 ++-- ui/components/ComposeView.qml | 8 ++++---- ui/compose/SpellcheckAdapter.qml | 12 ++++++------ ui/tests/qml/SpellcheckProbe.qml | 4 ++-- ui/tests/qml/tst_spellcheck_adapter.qml | 2 +- ui/tests/qml/tst_spellcheck_composer.qml | 4 ++-- ui/tests/qml/tst_spellcheck_menu.qml | 2 +- ui/tests/qml/tst_spellcheck_probe.qml | 4 ++-- 10 files changed, 25 insertions(+), 25 deletions(-) diff --git a/tests/spellcheck/composer-preview.qml b/tests/spellcheck/composer-preview.qml index b1c16bf..38136f6 100644 --- a/tests/spellcheck/composer-preview.qml +++ b/tests/spellcheck/composer-preview.qml @@ -1,7 +1,7 @@ import QtQuick import "../../ui/components" as Omamail -// S01 preview: the real ComposeView with the optional spelling adapter, for +// Preview: the real ComposeView with the optional spelling adapter, for // hands-on tuning of the underline and the suggestion menu. // // right-click a misspelled word -> suggestions, Ignore, Add to dictionary diff --git a/tests/spellcheck/playground.qml b/tests/spellcheck/playground.qml index 5765ea0..7df6201 100644 --- a/tests/spellcheck/playground.qml +++ b/tests/spellcheck/playground.qml @@ -3,15 +3,15 @@ import QtQuick.Controls import QtQuick.Layouts import org.kde.sonnet as Sonnet -// S00 interactive playground — a throwaway tool for trying the spelling -// adapter contract by hand before S01 wires it into the composer. +// Interactive playground — a throwaway tool for trying the spelling adapter +// contract by hand, outside the composer. // // Run it on the desktop (not offscreen): // /usr/lib/qt6/bin/qml tests/spellcheck/playground.qml // // Type in the body: misspelled words get Qt's red underline. Put the caret in // a word to see Sonnet's suggestions; click one to correct it. The correction -// uses the frozen rule from planning/decisions/S00.md §2.1 — prime with +// uses the adapter's correction rule — prime with // suggestions(position, 0) immediately before replaceWord(word, position) — // because without the prime Sonnet inserts instead of replacing. ApplicationWindow { @@ -19,7 +19,7 @@ ApplicationWindow { width: 860 height: 560 visible: true - title: "Omamail spelling playground — S00" + title: "Omamail spelling playground" property var suggestions: [] property string inspectedWord: "" diff --git a/ui/Service.qml b/ui/Service.qml index 130d0dc..0a45e8f 100644 --- a/ui/Service.qml +++ b/ui/Service.qml @@ -650,7 +650,7 @@ Item { readonly property string spellingStatus: spellingProbe.status === Loader.Error ? "no-module" : (spellingProbe.item ? spellingProbe.item.status : "loading") - // App-owned personal words (S00 §4, S6): persisted beside the other window + // App-owned personal words: persisted beside the other window // state, applied by the composer, never written to a global dictionary. // // The write is a queue rather than a one-shot. A second word added while the @@ -2728,7 +2728,7 @@ Item { onLoadFailed: root.applyWindowPrefs("") } - // Spelling's personal dictionary is app-owned (S00 §4): persisted beside the + // Spelling's personal dictionary is app-owned: persisted beside the // window state, never written to a global dictionary. FileView { id: spellingWordsFile diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml index 68a538d..5afead3 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -38,7 +38,7 @@ DropArea { property bool opened: false property bool userModified: false property bool settingBodyText: false - // Spelling settings (S04): read from the service, applied to the adapter. + // Spelling settings: read from the service, applied to the adapter. // The service owns the values and persistence; the composer only applies // them. Missing support is reported via spellingStatus. // The spelling settings live on the service; the composer follows them when @@ -73,7 +73,7 @@ DropArea { + ":" + bodyEdit.font.family // The theme's error role, drawn under misspelled words. The composer draws // the underline itself because Sonnet's QML highlighter also colours the word - // red; see planning/decisions/S00.md and the S01 handoff. + // red; see ui/compose/SpellcheckAdapter.qml. property color errorColor: textColor // A word is marked only once it is finished (something follows it), so this @@ -137,8 +137,8 @@ DropArea { return true } - // App-owned personal words (S00 §4): owned and persisted by the service - // (S04); applied to the adapter and rechecked whenever the list changes. + // App-owned personal words: owned and persisted by the service; + // applied to the adapter and rechecked whenever the list changes. onSpellingPersonalWordsChanged: { if (spellcheckLoader.item) spellcheckLoader.item.personalWords = spellingPersonalWords refreshSpellingRanges() diff --git a/ui/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml index 9874358..60950c9 100644 --- a/ui/compose/SpellcheckAdapter.qml +++ b/ui/compose/SpellcheckAdapter.qml @@ -2,12 +2,12 @@ import QtQuick import org.kde.sonnet as Sonnet import "SpellingSession.js" as Session -// Optional spelling adapter (S01). This is the only production file that +// Optional spelling adapter. This is the only production file that // imports org.kde.sonnet, so it is always created through a Loader: a machine // without the module gets a load error and an editor that still works, rather // than a composer that refuses to open. // -// The interface is frozen by planning/decisions/S00.md, with one later change: +// The interface is fixed, with one later change: // the underline is drawn by the caller, not by Sonnet. Sonnet's QML highlighter // paints the misspelled word red as well as underlining it (its errorFormat // sets a red foreground; misspelledColor is inert), unlike the QWidget one, @@ -23,12 +23,12 @@ Item { // this. property var document: null // `enabled` is reused from Item rather than redeclared: the adapter is - // non-visual, so this keeps the name frozen by S00 without shadowing + // non-visual, so this keeps the fixed interface name without shadowing // QQuickItem.enabled (which qmllint rejects). The owning Loader is inactive // when spelling is off, so this is a runtime toggle within a loaded adapter. property string language: "en_US" - // App-owned words to treat as correct (S00 §4). Persistence belongs to the - // settings layer (S04); this property only applies them. + // App-owned words to treat as correct. Persistence belongs to the + // settings layer in Service.qml; this property only applies them. property var personalWords: [] // Availability is about the *requested* language, and it is computed after @@ -81,7 +81,7 @@ Item { return true } - // Session-only ignore (S00 §4): never written to the user's dictionary. + // Session-only ignore: never written to the user's dictionary. function ignoreForSession(word) { if (!available || !word) return highlighter.ignoreWord(String(word)) diff --git a/ui/tests/qml/SpellcheckProbe.qml b/ui/tests/qml/SpellcheckProbe.qml index 75ea349..2622f05 100644 --- a/ui/tests/qml/SpellcheckProbe.qml +++ b/ui/tests/qml/SpellcheckProbe.qml @@ -1,12 +1,12 @@ import QtQuick import org.kde.sonnet as Sonnet -// S00 probe component: the only file under tests/ that imports org.kde.sonnet. +// Probe component: the only file under tests/ that imports org.kde.sonnet. // It is loaded through a Loader so a machine without the module reports a // loader error to the probe instead of failing the whole test file to import. // // The adapter the real feature will use is provisional; this exists to prove -// the runtime behaviour the adapter must rely on. See planning/decisions/S00.md. +// the runtime behaviour the adapter must rely on. Item { id: probe diff --git a/ui/tests/qml/tst_spellcheck_adapter.qml b/ui/tests/qml/tst_spellcheck_adapter.qml index 7a082c1..52dfa56 100644 --- a/ui/tests/qml/tst_spellcheck_adapter.qml +++ b/ui/tests/qml/tst_spellcheck_adapter.qml @@ -1,7 +1,7 @@ import QtQuick import QtTest -// S01: the optional spelling adapter's contract (planning/decisions/S00.md §3). +// The optional spelling adapter's contract. // The adapter is loaded through a Loader so this file has no mandatory // org.kde.sonnet import and skips where Sonnet or en_US is unavailable. Item { diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml index 614761e..125b06f 100644 --- a/ui/tests/qml/tst_spellcheck_composer.qml +++ b/ui/tests/qml/tst_spellcheck_composer.qml @@ -2,9 +2,9 @@ import QtQuick import QtTest import "../../components" as Omamail -// S01: the real composer attaches the optional spelling adapter to its body +// The real composer attaches the optional spelling adapter to its body // document, does not change the draft while checking, and unloads cleanly when -// disabled. Underlines are proven by the adapter contract test and the S00 +// disabled. Underlines are proven by the adapter contract test and the Sonnet // probe; here the point is the wiring, not the highlighter. Item { width: 900 diff --git a/ui/tests/qml/tst_spellcheck_menu.qml b/ui/tests/qml/tst_spellcheck_menu.qml index 2e71501..3d4a8b7 100644 --- a/ui/tests/qml/tst_spellcheck_menu.qml +++ b/ui/tests/qml/tst_spellcheck_menu.qml @@ -2,7 +2,7 @@ import QtQuick import QtTest import "../../components" as Omamail -// S02: the right-click / Ctrl+. spelling menu on the composer body — the word +// The right-click / Ctrl+. spelling menu on the composer body — the word // it targets, the correction/ignore/dictionary actions it offers, and the // guards that keep a stale or destroyed draft from being rewritten. The // underlines and the adapter contract are covered by tst_spellcheck_adapter diff --git a/ui/tests/qml/tst_spellcheck_probe.qml b/ui/tests/qml/tst_spellcheck_probe.qml index 5b60a90..8f5fa1f 100644 --- a/ui/tests/qml/tst_spellcheck_probe.qml +++ b/ui/tests/qml/tst_spellcheck_probe.qml @@ -1,10 +1,10 @@ import QtQuick import QtTest -// S00 probe: proves the real Sonnet QML highlighter behaviour the spelling +// Probe: proves the real Sonnet QML highlighter behaviour the spelling // adapter depends on. It loads Sonnet through a Loader so this file has no // mandatory org.kde.sonnet import, and skips (rather than fails) where Sonnet -// or the en_US dictionary is absent. See planning/decisions/S00.md. +// or the en_US dictionary is absent. Item { id: root width: 800 From 8455b70a3dda87ccbaf4283b2da789cf744844ed Mon Sep 17 00:00:00 2001 From: Chris Gray <216301595+latentoperator@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:41:38 -0500 Subject: [PATCH 15/18] Tell the user to restart after installing a spelling dictionary Sonnet lists installed dictionaries once per process. A dictionary installed while Omamail runs is not found by reopening Settings or by a new spelling adapter; verified on Qt 6.11.2 and Sonnet 6.29.0 by installing a dictionary under XDG_DATA_HOME mid-run. A fresh process finds it. --- ui/components/SettingsPage.qml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml index 19cba12..2880683 100644 --- a/ui/components/SettingsPage.qml +++ b/ui/components/SettingsPage.qml @@ -737,6 +737,8 @@ Column { // Availability is a runtime fact, separate from the enabled request: // a machine without Sonnet or the en_US dictionary still composes. + // Sonnet lists installed dictionaries once per process, so a dictionary + // installed while Omamail runs is only found after a restart. Text { objectName: "spellingNeedsSetup" width: parent.width @@ -745,7 +747,7 @@ Column { ? "Spell-checking is unavailable: the Sonnet QML module is not installed." : "The " + (root.service ? root.service.spellingLanguage : "en_US") + " dictionary is not installed. Install the matching Hunspell " - + "dictionary package (for example hunspell-en_us) and reopen settings." + + "dictionary package (for example hunspell-en_us), then restart Omamail." color: root.accentColor font.family: root.panelFontFamily font.pixelSize: Style.font.caption From 97a57c266e189c98799757ec2a62e2f577fc2814 Mon Sep 17 00:00:00 2001 From: Chris Gray <216301595+latentoperator@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:49:47 -0500 Subject: [PATCH 16/18] Move the personal spelling words into their own component Service.qml has a 128 KiB ceiling in tests/test_source.sh. Spelling alone fits under it, but together with message export it does not. The personal-word store (load, merge, queued write, and its FileView) moves unchanged to compose/PersonalWords.qml; Service keeps the same public properties and functions. --- Makefile | 2 +- ui/Service.qml | 103 +++----------------------- ui/compose/PersonalWords.qml | 102 +++++++++++++++++++++++++ ui/tests/qml/tst_service_settings.qml | 24 +++--- 4 files changed, 124 insertions(+), 107 deletions(-) create mode 100644 ui/compose/PersonalWords.qml diff --git a/Makefile b/Makefile index 7a6d43c..810e8ad 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ QMLLINT := /usr/lib/qt6/bin/qmllint .DEFAULT_GOAL := test QML_FILES := ui/Service.qml ui/BarWidget.qml ui/App.qml ui/compose/RecoveryController.qml \ - ui/compose/SpellcheckAdapter.qml \ + ui/compose/SpellcheckAdapter.qml ui/compose/PersonalWords.qml \ ui/backend/Backend.qml ui/backend/Runtime.qml ui/diagnostics/Diagnostics.qml \ ui/components/BackendSetup.qml ui/components/OmamailLogo.qml \ ui/account/MailAccount.qml ui/account/BackendSync.qml ui/account/SendQueue.qml ui/account/Intents.qml ui/account/BatchAction.qml ui/account/Rsvp.qml ui/account/LabelActions.qml ui/account/Unsubscribe.qml ui/account/NewMailNotification.qml \ diff --git a/ui/Service.qml b/ui/Service.qml index 0a45e8f..02d022d 100644 --- a/ui/Service.qml +++ b/ui/Service.qml @@ -7,6 +7,7 @@ import "calendar" import "agent" import "backend" import "diagnostics" +import "compose" as Compose import "agent/Agent.js" as Agent import "account/Accounts.js" as Accounts @@ -650,88 +651,14 @@ Item { readonly property string spellingStatus: spellingProbe.status === Loader.Error ? "no-module" : (spellingProbe.item ? spellingProbe.item.status : "loading") - // App-owned personal words: persisted beside the other window - // state, applied by the composer, never written to a global dictionary. - // - // The write is a queue rather than a one-shot. A second word added while the - // first write is still in flight must reach disk too, and an add that lands - // before the initial file read finishes must survive the read. - property var spellingPersonalWords: [] - property bool spellingPersonalWordsLoaded: false - property bool spellingPersonalWordsWriting: false - property bool spellingPersonalWordsPending: false - property string spellingPersonalWordsError: "" - - function normalizeSpellingPersonalWords(raw) { - var parsed = null - try { parsed = JSON.parse(String(raw || "")) } catch (e) { parsed = null } - var words = (parsed && Array.isArray(parsed.words)) ? parsed.words : [] - var next = [] - for (var i = 0; i < words.length; i++) { - var word = words[i] - if (typeof word !== "string") continue - if (word !== "" && next.indexOf(word) < 0) next.push(word) - } - return next - } - - // Replace the list. The FileView load path uses `mergeSpellingPersonalWords` - // below; this is the explicit/reset form and what the tests drive. - function applySpellingPersonalWords(raw) { - spellingPersonalWords = normalizeSpellingPersonalWords(raw) - spellingPersonalWordsLoaded = true - if (spellingPersonalWordsPending) saveSpellingPersonalWords() - } - - // A load that arrives after the user has already added a word must union, - // not replace: the in-memory additions are this session's intent and the - // disk copy is yesterday's. - function mergeSpellingPersonalWords(raw) { - var onDisk = normalizeSpellingPersonalWords(raw) - var next = spellingPersonalWords.slice() - for (var i = 0; i < onDisk.length; i++) { - if (next.indexOf(onDisk[i]) < 0) next.push(onDisk[i]) - } - spellingPersonalWords = next - spellingPersonalWordsLoaded = true - if (spellingPersonalWordsPending) saveSpellingPersonalWords() - } - - function saveSpellingPersonalWords() { - // Before the load completes, remember that there is something to write so - // the load can flush it rather than dropping it. - if (!spellingPersonalWordsLoaded) { spellingPersonalWordsPending = true; return } - if (spellingPersonalWordsWriting) { spellingPersonalWordsPending = true; return } - spellingPersonalWordsWriting = true - spellingPersonalWordsPending = false - writeConfig("spelling.json", JSON.stringify({ words: spellingPersonalWords }), function(ok, error) { - root.spellingPersonalWordsWriting = false - // The write boundaries can refuse the file (a host allowlist that has - // not been told about it, a full disk): keep the failure where the - // Settings page can say so instead of pretending the word saved. - root.spellingPersonalWordsError = ok ? "" : String(error || "Could not save personal words") - if (root.spellingPersonalWordsPending) root.saveSpellingPersonalWords() - }) - } - - function addPersonalWord(word) { - var value = String(word || "") - if (value === "" || spellingPersonalWords.indexOf(value) >= 0) return - var next = spellingPersonalWords.slice() - next.push(value) - spellingPersonalWords = next - saveSpellingPersonalWords() - } - - function removePersonalWord(word) { - var value = String(word || "") - var at = spellingPersonalWords.indexOf(value) - if (at < 0) return - var next = spellingPersonalWords.slice() - next.splice(at, 1) - spellingPersonalWords = next - saveSpellingPersonalWords() - } + // App-owned personal words: compose/PersonalWords.qml stores them in + // spelling.json; the composer applies them. + Compose.PersonalWords { id: personalWords; service: root } + readonly property var spellingWordStore: personalWords + readonly property var spellingPersonalWords: personalWords.words + readonly property string spellingPersonalWordsError: personalWords.error + function addPersonalWord(word) { personalWords.add(word) } + function removePersonalWord(word) { personalWords.remove(word) } // ---------------------------------------------------------- the accounts @@ -2728,18 +2655,6 @@ Item { onLoadFailed: root.applyWindowPrefs("") } - // Spelling's personal dictionary is app-owned: persisted beside the - // window state, never written to a global dictionary. - FileView { - id: spellingWordsFile - path: root.configPath("spelling.json") - printErrors: false - // Merge rather than replace: a word added before the read returned is this - // session's and must not be undone by yesterday's file. - onLoaded: root.mergeSpellingPersonalWords(text()) - onLoadFailed: root.mergeSpellingPersonalWords("") - } - // Availability probe: loads Sonnet once so the settings page can explain a // missing module or dictionary without a compose window open. Its language // follows the setting so the status is about the *requested* dictionary, not diff --git a/ui/compose/PersonalWords.qml b/ui/compose/PersonalWords.qml new file mode 100644 index 0000000..a83a51e --- /dev/null +++ b/ui/compose/PersonalWords.qml @@ -0,0 +1,102 @@ +import QtQuick +import Quickshell.Io + +// App-owned personal spelling words, persisted as spelling.json beside the +// window state and applied by the composer. Never written to a global +// dictionary. +// +// The write is a queue rather than a one-shot. A second word added while the +// first write is still in flight must reach disk too, and an add that lands +// before the initial file read finishes must survive the read. +Item { + id: store + visible: false + + // The service owns both file boundaries: configPath() and writeConfig(). + required property var service + + property var words: [] + property bool loaded: false + property bool writing: false + property bool pending: false + property string error: "" + + function normalize(raw) { + var parsed = null + try { parsed = JSON.parse(String(raw || "")) } catch (e) { parsed = null } + var list = (parsed && Array.isArray(parsed.words)) ? parsed.words : [] + var next = [] + for (var i = 0; i < list.length; i++) { + var word = list[i] + if (typeof word !== "string") continue + if (word !== "" && next.indexOf(word) < 0) next.push(word) + } + return next + } + + // Replace the list. The file load uses `merge` below; this is the explicit + // reset form and what the tests drive. + function apply(raw) { + words = normalize(raw) + loaded = true + if (pending) save() + } + + // A load that arrives after the user has already added a word must union, + // not replace: the in-memory additions are this session's intent and the + // disk copy is yesterday's. + function merge(raw) { + var onDisk = normalize(raw) + var next = words.slice() + for (var i = 0; i < onDisk.length; i++) { + if (next.indexOf(onDisk[i]) < 0) next.push(onDisk[i]) + } + words = next + loaded = true + if (pending) save() + } + + function save() { + // Before the load completes, remember that there is something to write so + // the load can flush it rather than dropping it. + if (!loaded || writing) { pending = true; return } + writing = true + pending = false + service.writeConfig("spelling.json", JSON.stringify({ words: words }), function(ok, failure) { + store.writing = false + // The write boundaries can refuse the file (a host allowlist that has + // not been told about it, a full disk): keep the failure where the + // Settings page can say so instead of pretending the word saved. + store.error = ok ? "" : String(failure || "Could not save personal words") + if (store.pending) store.save() + }) + } + + function add(word) { + var value = String(word || "") + if (value === "" || words.indexOf(value) >= 0) return + var next = words.slice() + next.push(value) + words = next + save() + } + + function remove(word) { + var value = String(word || "") + var at = words.indexOf(value) + if (at < 0) return + var next = words.slice() + next.splice(at, 1) + words = next + save() + } + + FileView { + path: store.service.configPath("spelling.json") + printErrors: false + // Merge rather than replace: a word added before the read returned is this + // session's and must not be undone by yesterday's file. + onLoaded: store.merge(text()) + onLoadFailed: store.merge("") + } +} diff --git a/ui/tests/qml/tst_service_settings.qml b/ui/tests/qml/tst_service_settings.qml index 9ed1732..99b3cb4 100644 --- a/ui/tests/qml/tst_service_settings.qml +++ b/ui/tests/qml/tst_service_settings.qml @@ -60,9 +60,9 @@ Item { function init() { configPlatform.writes = [] configPlatform.callbacks = [] - mailService.spellingPersonalWordsWriting = false - mailService.spellingPersonalWordsPending = false - mailService.spellingPersonalWordsError = "" + mailService.spellingWordStore.writing = false + mailService.spellingWordStore.pending = false + mailService.spellingWordStore.error = "" } function test_scoped_manifest_resolves_bundled_helpers_without_private_metadata() { @@ -195,7 +195,7 @@ Item { } function test_spelling_personal_words_add_remove_and_dedupe() { - mailService.applySpellingPersonalWords("") + mailService.spellingWordStore.apply("") compare(mailService.spellingPersonalWords.length, 0) mailService.addPersonalWord("blorptar") mailService.addPersonalWord("blorptar") @@ -208,7 +208,7 @@ Item { } function test_spelling_personal_words_parse_dedupe_and_ignore_junk() { - mailService.applySpellingPersonalWords('{"words":["a","b","a","","c",42,null]}') + mailService.spellingWordStore.apply('{"words":["a","b","a","","c",42,null]}') compare(mailService.spellingPersonalWords.length, 3) compare(mailService.spellingPersonalWords[0], "a") compare(mailService.spellingPersonalWords[1], "b") @@ -218,7 +218,7 @@ Item { // Two words added while the first write is still in flight: the second is // queued and written after the first completes, so disk ends with both. function test_spelling_personal_words_queue_changes_during_a_write() { - mailService.applySpellingPersonalWords("") + mailService.spellingWordStore.apply("") configPlatform.writes = [] configPlatform.callbacks = [] mailService.addPersonalWord("alpha") @@ -236,7 +236,7 @@ Item { // A refused write is recorded rather than swallowed, and the next change // asks the host again. function test_spelling_personal_words_retry_after_a_failed_write() { - mailService.applySpellingPersonalWords("") + mailService.spellingWordStore.apply("") configPlatform.writes = [] configPlatform.callbacks = [] mailService.addPersonalWord("alpha") @@ -251,14 +251,14 @@ Item { // Write then read: what a completed write put in the file is what a later // read restores, which is the restart guarantee the old path never had. function test_spelling_personal_words_round_trip_through_a_restart() { - mailService.applySpellingPersonalWords("") + mailService.spellingWordStore.apply("") configPlatform.writes = [] configPlatform.callbacks = [] mailService.addPersonalWord("blorptar") compare(configPlatform.confirm(0, true, ""), true) var saved = configPlatform.writes[0].text // A restart reads the file back with no words in memory. - mailService.applySpellingPersonalWords(saved) + mailService.spellingWordStore.apply(saved) compare(mailService.spellingPersonalWords.length, 1) compare(mailService.spellingPersonalWords[0], "blorptar") } @@ -266,13 +266,13 @@ Item { // A word added before the initial read returns is the session's, not the // file's: the later load unions the two instead of replacing memory. function test_spelling_personal_words_merge_a_late_load() { - mailService.applySpellingPersonalWords("") + mailService.spellingWordStore.apply("") configPlatform.writes = [] configPlatform.callbacks = [] - mailService.spellingPersonalWordsLoaded = false + mailService.spellingWordStore.loaded = false mailService.addPersonalWord("alpha") compare(configPlatform.writes.length, 0, "nothing is written before the load completes") - mailService.mergeSpellingPersonalWords('{"words":["beta","alpha"]}') + mailService.spellingWordStore.merge('{"words":["beta","alpha"]}') compare(mailService.spellingPersonalWords.length, 2) verify(mailService.spellingPersonalWords.indexOf("alpha") >= 0) verify(mailService.spellingPersonalWords.indexOf("beta") >= 0) From 811e99abb0b178b65e7de948124e675750b57cde Mon Sep 17 00:00:00 2001 From: Chris Gray <216301595+latentoperator@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:03:23 -0500 Subject: [PATCH 17/18] Skip composer spelling tests cleanly when Sonnet is missing Without the Sonnet module the adapter never loads, so waiting for it timed out and failed 27 cases instead of skipping them. The waits now also accept the no-module status and the cases skip. Verified on Qt 6.11.2 both with Sonnet (15 + 16 passed) and with it hidden from the import path (13 + 14 skipped, 0 failed). --- ui/tests/qml/tst_spellcheck_composer.qml | 31 +++++++++++++----------- ui/tests/qml/tst_spellcheck_menu.qml | 2 +- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml index 125b06f..06bb9aa 100644 --- a/ui/tests/qml/tst_spellcheck_composer.qml +++ b/ui/tests/qml/tst_spellcheck_composer.qml @@ -78,7 +78,7 @@ Item { function test_body_adapter_attaches_and_checking_does_not_mutate() { var body = named(compose, "compose-body-editor") verify(body, "the composer owns a body editor") - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (!compose.spellingAvailable) { skip("spelling unavailable (" + compose.spellingStatus + ")") return @@ -94,7 +94,8 @@ Item { function test_session_ignore_refreshes_a_separate_composer_document() { var body = named(compose, "compose-body-editor") - tryVerify(function() { return compose.spellingAvailable }, 3000) + tryVerify(function() { return compose.spellingAvailable || compose.spellingStatus === "no-module" }, 3000) + if (!compose.spellingAvailable) { skip("spelling unavailable (" + compose.spellingStatus + ")"); return } body.text = "the zqxjremotereviewhere here " tryCompare(compose, "spellingRanges", [{ start: 4, end: 24 }]) var component = Qt.createComponent("../../compose/SpellcheckAdapter.qml") @@ -114,7 +115,8 @@ Item { function test_personal_words_preserve_focused_draft_selection_and_undo() { var body = named(compose, "compose-body-editor") - tryVerify(function() { return compose.spellingAvailable }, 3000) + tryVerify(function() { return compose.spellingAvailable || compose.spellingStatus === "no-module" }, 3000) + if (!compose.spellingAvailable) { skip("spelling unavailable (" + compose.spellingStatus + ")"); return } body.text = "the zqxjpersonalreviewhere here " body.forceActiveFocus() body.select(4, 9) @@ -138,7 +140,7 @@ Item { function test_a_correction_changes_the_body_and_undo_restores_it() { var body = named(compose, "compose-body-editor") verify(body) - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (!compose.spellingAvailable) { skip("spelling unavailable"); return } body.text = "a mispelled wrod here" var before = body.text @@ -153,7 +155,7 @@ Item { function test_underline_ranges_require_a_finished_word() { var body = named(compose, "compose-body-editor") verify(body) - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (!compose.spellingAvailable) { skip("spelling unavailable"); return } body.text = "a wrod" wait(250) // past the debounce @@ -167,7 +169,7 @@ Item { function test_right_click_offers_suggestions_for_the_clicked_word() { var body = named(compose, "compose-body-editor") - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (!compose.spellingAvailable) { skip("spelling unavailable"); return } body.text = "a mispelled wrod " wait(250) @@ -187,7 +189,7 @@ Item { function test_ignore_for_session_stops_marking_the_word() { var body = named(compose, "compose-body-editor") - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (!compose.spellingAvailable) { skip("spelling unavailable"); return } body.text = "the floobert here " wait(250) @@ -204,7 +206,7 @@ Item { function test_add_to_dictionary_stops_marking_the_word() { var body = named(compose, "compose-body-editor") - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (!compose.spellingAvailable) { skip("spelling unavailable"); return } body.text = "the blorptar here " wait(250) @@ -221,7 +223,7 @@ Item { function test_ctrl_period_opens_suggestions_at_the_caret_word() { var body = named(compose, "compose-body-editor") - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (!compose.spellingAvailable) { skip("spelling unavailable"); return } body.text = "the mispelled here " wait(250) @@ -239,7 +241,7 @@ Item { // is about the requested dictionary: a missing one reads no-dictionary and // switching back recovers, with no silent fallback to English. function test_language_follows_the_setting_and_reports_a_missing_dictionary() { - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (compose.spellingStatus === "no-module") { skip("Sonnet is not installed"); return } compose.spellingLanguage = "en_US" tryVerify(function() { return compose.spellingStatus === "ready" }, 3000) @@ -257,7 +259,7 @@ Item { function test_underline_follows_the_editor_when_it_resizes() { var body = named(compose, "compose-body-editor") verify(body) - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (!compose.spellingAvailable) { skip("spelling unavailable (" + compose.spellingStatus + ")"); return } body.text = "hello hello hello hello hello hello hello hello hello hello hello hello wrod here " wait(250) @@ -277,12 +279,13 @@ Item { } function test_disabling_unloads_the_adapter_and_re_enabling_restores_it() { - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) + if (compose.spellingStatus === "no-module") { skip("Sonnet is not installed"); return } compose.spellingEnabled = false tryVerify(function() { return compose.spellingAdapter === null }, 3000) compare(compose.spellingStatus, "disabled") compose.spellingEnabled = true - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) compare(compose.spellingAvailable, true) } @@ -291,7 +294,7 @@ Item { // the old dictionary's underlines from lingering. function test_a_valid_to_valid_language_switch_rechecks_ranges() { var body = named(compose, "compose-body-editor") - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (compose.spellingStatus === "no-module") { skip("Sonnet is not installed"); return } compose.spellingLanguage = "en_GB" diff --git a/ui/tests/qml/tst_spellcheck_menu.qml b/ui/tests/qml/tst_spellcheck_menu.qml index 3d4a8b7..501d71f 100644 --- a/ui/tests/qml/tst_spellcheck_menu.qml +++ b/ui/tests/qml/tst_spellcheck_menu.qml @@ -74,7 +74,7 @@ Item { function init() { compose.parent.forceActiveFocus() compose.begin("new", null, "", []) - tryVerify(function() { return compose.spellingAdapter !== null }, 3000) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000) if (!compose.spellingAvailable) skip("spelling unavailable (" + compose.spellingStatus + ")") } From a0457132b733ad4d20a0a32b210536da215c6f18 Mon Sep 17 00:00:00 2001 From: Dante Date: Thu, 1 Oct 2026 09:17:27 -0500 Subject: [PATCH 18/18] Let the spelling preview's Add to dictionary clear the underline The preview's stand-in service had no personal-word store, so Add to dictionary was a silent no-op there. The real service and the composer tests already cover it; this only makes the hands-on preview match. --- tests/spellcheck/composer-preview.qml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/spellcheck/composer-preview.qml b/tests/spellcheck/composer-preview.qml index 38136f6..f6430c1 100644 --- a/tests/spellcheck/composer-preview.qml +++ b/tests/spellcheck/composer-preview.qml @@ -34,6 +34,14 @@ Rectangle { function send(_f) { return true } function copyText(_t) { return true } function clipboardAttachment(_dir, callback) { callback({ ok: false, error: "no-image" }); return true } + // In-memory stand-in for the service's personal-word store, so Add to + // dictionary clears the underline here. The real store persists to + // spelling.json; this preview forgets the words when it closes. + property var spellingPersonalWords: [] + function addPersonalWord(word) { + if (word && spellingPersonalWords.indexOf(word) < 0) + spellingPersonalWords = spellingPersonalWords.concat([word]) + } } Omamail.ComposeView {