diff --git a/Makefile b/Makefile index ca55d4f..810e8ad 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/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/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/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/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/spellcheck/composer-preview.qml b/tests/spellcheck/composer-preview.qml new file mode 100644 index 0000000..f6430c1 --- /dev/null +++ b/tests/spellcheck/composer-preview.qml @@ -0,0 +1,63 @@ +import QtQuick +import "../../ui/components" as Omamail + +// 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 +Rectangle { + id: root + width: 1040 + height: 780 + color: compose.backgroundColor + + 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 } + // 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 { + id: compose + anchors.fill: parent + service: mailService + textColor: "#e8e8ee" + backgroundColor: "#101014" + accentColor: "#ff8a3d" + dimColor: "#a9a9ae" + dimmerColor: "#737377" + popupBackgroundColor: "#1a1a1e" + popupBorderColor: "#3c3c41" + panelFontFamily: "sans" + errorColor: "#ff5555" + } + + Component.onCompleted: compose.begin("new", null, "", []) +} diff --git a/tests/spellcheck/playground.qml b/tests/spellcheck/playground.qml new file mode 100644 index 0000000..7df6201 --- /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 + +// 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 adapter's correction rule — 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" + + 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 + } +} 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 6069d18..0c0679c 100644 --- a/ui/App.qml +++ b/ui/App.qml @@ -2157,6 +2157,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/Service.qml b/ui/Service.qml index ca46ebf..da77814 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 @@ -140,7 +141,9 @@ Item { unifiedCalendarView: false, showBarIcon: true, unifiedMailboxes: false, - suggestEvents: false + suggestEvents: false, + spellingEnabled: true, + spellingLanguage: "en_US" }) function normalizedSettings(values) { var next = ({}) @@ -424,7 +427,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 +630,36 @@ 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: 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 property var accountList: Accounts.emptyList() @@ -2692,6 +2725,23 @@ Item { onLoadFailed: root.applyWindowPrefs("") } + // 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 + // 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 c82697b..5afead3 100644 --- a/ui/components/ComposeView.qml +++ b/ui/components/ComposeView.qml @@ -38,6 +38,111 @@ DropArea { property bool opened: false property bool userModified: false property bool settingBodyText: false + // 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 + // 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 + && 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 + // 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 ui/compose/SpellcheckAdapter.qml. + 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() + // 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 + interval: 120 + 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.spellingRevision = root.bodyRevision + 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) return false + textMenu.spellingPosition = position + textMenu.spellingRevision = root.bodyRevision + 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: 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() + } // 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. @@ -1830,18 +1935,99 @@ 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 root.noteUserModified() } + root.bodyRevision += 1 + 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 + // 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 + 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. + // + // 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 + ? toRect.x - fromRect.x + : Math.max(fromRect.width, bodyEdit.width - fromRect.x)) + height: 1 + color: root.errorColor + } + } + } } } + // 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.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 + } + + Connections { + target: spellcheckLoader.item + function onCheckerChanged() { spellingDebounce.restart() } + } + Rectangle { objectName: "compose-body-restore-flash" anchors.fill: bodyFlick @@ -2017,6 +2203,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, "") } } @@ -2036,5 +2223,32 @@ DropArea { if (target) target.forceActiveFocus() root.paste() } + onSpellingCorrect: function(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. 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) + // 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: 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..2880683 100644 --- a/ui/components/SettingsPage.qml +++ b/ui/components/SettingsPage.qml @@ -686,6 +686,117 @@ 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. + // 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 + 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), then restart Omamail." + color: root.accentColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + 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 { + 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/components/TextMenu.qml b/ui/components/TextMenu.qml index 750857e..37cd828 100644 --- a/ui/components/TextMenu.qml +++ b/ui/components/TextMenu.qml @@ -27,9 +27,26 @@ 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 + // 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: [] + 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 +54,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 +101,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 +160,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/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/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml new file mode 100644 index 0000000..60950c9 --- /dev/null +++ b/ui/compose/SpellcheckAdapter.qml @@ -0,0 +1,159 @@ +import QtQuick +import org.kde.sonnet as Sonnet +import "SpellingSession.js" as Session + +// 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 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, +// which only underlines. So the highlighter here stays inactive and is used +// 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 + + // 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 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. 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 + // `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" + : (available ? "ready" : "no-dictionary") + + signal checkerChanged() + Component.onCompleted: { + Session.subscribe(adapter) + applySettings() + } + Component.onDestruction: Session.unsubscribe(adapter) + 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: never written to the user's dictionary. + 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 + // `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() { + // 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() { + if (!available) return + for (var i = 0; i < personalWords.length; i++) { + var word = String(personalWords[i]) + if (word !== "") highlighter.ignoreWord(word) + } + Session.changed() + } + + onDocumentChanged: if (document !== null) highlighter.document = document + + 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 + } +} 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/SpellcheckProbe.qml b/ui/tests/qml/SpellcheckProbe.qml new file mode 100644 index 0000000..2622f05 --- /dev/null +++ b/ui/tests/qml/SpellcheckProbe.qml @@ -0,0 +1,41 @@ +import QtQuick +import org.kde.sonnet as 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. +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_service_settings.qml b/ui/tests/qml/tst_service_settings.qml index 21597fc..99b3cb4 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.spellingWordStore.writing = false + mailService.spellingWordStore.pending = false + mailService.spellingWordStore.error = "" + } + function test_scoped_manifest_resolves_bundled_helpers_without_private_metadata() { verify(scopedMailService.pluginDir !== "") verify(scopedMailService.pluginDir.indexOf("%") < 0, @@ -142,5 +173,138 @@ 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.spellingWordStore.apply("") + 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.spellingWordStore.apply('{"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") + } + + // 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.spellingWordStore.apply("") + 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.spellingWordStore.apply("") + 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.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.spellingWordStore.apply(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.spellingWordStore.apply("") + configPlatform.writes = [] + configPlatform.callbacks = [] + mailService.spellingWordStore.loaded = false + mailService.addPersonalWord("alpha") + compare(configPlatform.writes.length, 0, "nothing is written before the load completes") + mailService.spellingWordStore.merge('{"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() { + tryVerify(function() { + var status = mailService.spellingStatus + 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_adapter.qml b/ui/tests/qml/tst_spellcheck_adapter.qml new file mode 100644 index 0000000..52dfa56 --- /dev/null +++ b/ui/tests/qml/tst_spellcheck_adapter.qml @@ -0,0 +1,136 @@ +import QtQuick +import QtTest + +// 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 { + 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_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 + // 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..06bb9aa --- /dev/null +++ b/ui/tests/qml/tst_spellcheck_composer.qml @@ -0,0 +1,325 @@ +import QtQuick +import QtTest +import "../../components" as Omamail + +// 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 Sonnet +// 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" + 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) + 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, "", []) + // 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") + verify(body, "the composer owns a body editor") + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 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_session_ignore_refreshes_a_separate_composer_document() { + var body = named(compose, "compose-body-editor") + 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") + 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 || 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) + 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) + 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 + 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_underline_ranges_require_a_finished_word() { + var body = named(compose, "compose-body-editor") + verify(body) + 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 + 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_right_click_offers_suggestions_for_the_clicked_word() { + var body = named(compose, "compose-body-editor") + 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) + 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 || compose.spellingStatus === "no-module" }, 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 || compose.spellingStatus === "no-module" }, 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 || compose.spellingStatus === "no-module" }, 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) + } + + // 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 || 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) + 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 || 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) + 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 || 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 || compose.spellingStatus === "no-module" }, 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 || compose.spellingStatus === "no-module" }, 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") + } + } +} diff --git a/ui/tests/qml/tst_spellcheck_menu.qml b/ui/tests/qml/tst_spellcheck_menu.qml new file mode 100644 index 0000000..501d71f --- /dev/null +++ b/ui/tests/qml/tst_spellcheck_menu.qml @@ -0,0 +1,295 @@ +import QtQuick +import QtTest +import "../../components" as Omamail + +// 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" + 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) + 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.parent.forceActiveFocus() + compose.begin("new", null, "", []) + tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 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) + } + + // 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 " + 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_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" + 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) + } + } +} diff --git a/ui/tests/qml/tst_spellcheck_probe.qml b/ui/tests/qml/tst_spellcheck_probe.qml new file mode 100644 index 0000000..8f5fa1f --- /dev/null +++ b/ui/tests/qml/tst_spellcheck_probe.qml @@ -0,0 +1,115 @@ +import QtQuick +import QtTest + +// 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. +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 + } + } +} 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.