From 9b941ccb6665e73fe4dfd20acfe6a7092709f84a Mon Sep 17 00:00:00 2001
From: Chris Gray <216301595+latentoperator@users.noreply.github.com>
Date: Wed, 7 Oct 2026 13:06:05 -0500
Subject: [PATCH 01/88] Show a saved-file notice, save from the reader, and
offer a folder for .eml
- A card above the status bar names the saved file and its folder, with
Open folder... and a dismiss button. It hides after eight seconds and stays
while hovered. The status-bar notice is unchanged.
- The reader toolbar has a Save as .eml button, and a right-click on the
message text offers Save as .eml and Save as .eml to folder...
- The message menu offers Save as .eml to folder... beside Save as .eml.
- mail.exportEml takes an optional directory: an absolute path in normal
form. A chosen folder must already exist and pass the same ownership
checks as Downloads, and it is never created. Downloads is unchanged.
- attachment.sh folder asks omarchy-file-select --directory (the desktop
portal) or zenity for one folder, out of process like the file picker.
The standalone app does not offer folder rows.
---
Makefile | 1 +
backend-api.json | 16 +-
scripts/attachment.sh | 26 +++-
src/backend/mail.rs | 5 +-
src/mail/export.rs | 115 +++++++++++++-
src/mail/types.rs | 32 +++-
tests/test_attachment.sh | 34 +++++
ui/App.qml | 2 +
ui/Service.qml | 9 +-
ui/account/MailAccount.qml | 12 +-
ui/account/MessageActions.js | 33 +++-
ui/components/EmlSavedToast.qml | 185 +++++++++++++++++++++++
ui/components/Icons.js | 2 +-
ui/components/MessageMenu.qml | 18 ++-
ui/components/MessageReader.qml | 36 +++++
ui/components/TextMenu.qml | 30 +++-
ui/keys/Keymap.js | 2 +-
ui/tests/qml/tst_eml_saved_toast.qml | 112 ++++++++++++++
ui/tests/qml/tst_message_menu_export.qml | 33 +++-
ui/tests/qml/tst_reader_mode.qml | 3 +
ui/tests/qml/tst_reader_text_menu.qml | 63 +++++++-
ui/tests/test_eml_export.js | 46 ++++++
ui/tests/test_icons.js | 4 +
23 files changed, 797 insertions(+), 22 deletions(-)
create mode 100644 ui/components/EmlSavedToast.qml
create mode 100644 ui/tests/qml/tst_eml_saved_toast.qml
diff --git a/Makefile b/Makefile
index 9c7690b..9a57d8c 100644
--- a/Makefile
+++ b/Makefile
@@ -50,6 +50,7 @@ QML_FILES := ui/Service.qml ui/BarWidget.qml ui/App.qml ui/compose/RecoveryContr
ui/components/LabelPicker.qml \
ui/components/UndoSendToast.qml \
ui/components/DraftSavedToast.qml \
+ ui/components/EmlSavedToast.qml \
ui/components/SearchBar.qml \
ui/components/AppMenu.qml \
ui/components/AccountSwitcher.qml \
diff --git a/backend-api.json b/backend-api.json
index 07f7250..fdc4dda 100644
--- a/backend-api.json
+++ b/backend-api.json
@@ -1361,6 +1361,19 @@
"equals": {
"message": "mail_account_unknown"
}
+ },
+ {
+ "name": "mail.exportEml refuses a folder that is not an absolute plain path",
+ "method": "mail.exportEml",
+ "params": {
+ "account": "imap:sender@example.org",
+ "id": "1:INBOX",
+ "directory": "../Downloads"
+ },
+ "errorCode": -32602,
+ "equals": {
+ "message": "Invalid params"
+ }
}
],
"unreleased": {
@@ -1375,7 +1388,8 @@
"mail.exportEml rejects unknown fields",
"mail.exportEml rejects a malformed UID before provider work",
"mail.exportEml rejects controlled filename hints",
- "mail.exportEml rejects account controls before normalization"
+ "mail.exportEml rejects account controls before normalization",
+ "mail.exportEml refuses a folder that is not an absolute plain path"
]
}
}
diff --git a/scripts/attachment.sh b/scripts/attachment.sh
index d0e69d7..60ab0f9 100755
--- a/scripts/attachment.sh
+++ b/scripts/attachment.sh
@@ -4,6 +4,7 @@
# attachment.sh read
# attachment.sh clipboard
# attachment.sh pick
+# attachment.sh folder
# attachment.sh forget
#
# One JSON object on stdout. Quickshell's Process.write() never closes stdin,
@@ -279,6 +280,26 @@ pick_files() {
emit_paths "$list"
}
+# One folder, through the same out-of-process chooser, for Save as .eml.
+pick_folder() {
+ list=
+ if command -v omarchy-file-select >/dev/null 2>&1; then
+ list=$(omarchy-file-select --title 'Save .eml to' --directory 2>/dev/null || true)
+ elif command -v zenity >/dev/null 2>&1; then
+ list=$(zenity --file-selection --directory --title='Save .eml to' 2>/dev/null || true)
+ else
+ fail_json "No folder picker is available"
+ fi
+ list=$(printf '%s\n' "$list" | sed -n '1p')
+ # The backend takes a folder only in its plain form, so no trailing slash.
+ while [ "${#list}" -gt 1 ] && [ "${list%/}" != "$list" ]; do list=${list%/}; done
+ case "$list" in
+ /*) ;;
+ *) fail_json "cancelled" ;;
+ esac
+ emit_paths "$list"
+}
+
command=${1:-}
case "$command" in
read)
@@ -292,12 +313,15 @@ case "$command" in
pick)
pick_files
;;
+ folder)
+ pick_folder
+ ;;
forget)
[ -n "${2:-}" ] && [ -n "${3:-}" ] || fail_json "That file is not a draft attachment"
forget_file "$2" "$3"
;;
*)
- printf '%s\n' 'usage: attachment.sh read | clipboard | pick | forget ' >&2
+ printf '%s\n' 'usage: attachment.sh read | clipboard | pick | folder | forget ' >&2
exit 2
;;
esac
diff --git a/src/backend/mail.rs b/src/backend/mail.rs
index 505a3e4..ed95bbc 100644
--- a/src/backend/mail.rs
+++ b/src/backend/mail.rs
@@ -394,7 +394,10 @@ impl Session {
"mail.exportEml" => {
let request = ExportRequest::try_from(params)?;
let refusals = crate::account::refusals_readonly(&request.account.id)?;
- let downloads = crate::platform::dirs::AppDirs::discover()?.downloads;
+ let downloads = match &request.directory {
+ Some(chosen) => chosen.clone(),
+ None => crate::platform::dirs::AppDirs::discover()?.downloads,
+ };
let control = crate::mail::export::ExportControl::new();
crate::mail::export::export_with(
request,
diff --git a/src/mail/export.rs b/src/mail/export.rs
index 3958e43..96d60f3 100644
--- a/src/mail/export.rs
+++ b/src/mail/export.rs
@@ -1,4 +1,5 @@
-//! Save one message's original bytes as `.eml` in the user's Downloads folder.
+//! Save one message's original bytes as `.eml` in the user's Downloads folder,
+//! or in a folder the user picked.
//!
//! The bytes come from the provider's raw-message operation (`imap.rawMessage`)
//! and are written unchanged. The `mail.exportEml` RPC contract is fixed; this
@@ -323,6 +324,10 @@ async fn run_export(
let downloads = downloads.to_path_buf();
let deadline_std = deadline.into_std();
let cancel = control.cancel.clone();
+ // Downloads is created on first use. A folder the user picked must already
+ // exist and pass the same ownership checks: a picker answer is never a
+ // reason to create directories.
+ let create = request.directory.is_none();
// Storage is synchronous create/write/fsync, so it runs on a blocking
// worker rather than a Tokio worker. The destination directory is anchored
// to a descriptor before the deadline is observed, so a path swap after the
@@ -330,7 +335,7 @@ async fn run_export(
// point: a cancellation or an expired deadline observed before it leaves no
// file; after it the write completes and success is returned.
let path = tokio::task::spawn_blocking(move || {
- let dir = crate::platform::private_fs::directories(&downloads, &[], true)
+ let dir = crate::platform::private_fs::directories(&downloads, &[], create)
.map_err(|_| "mail_export_write_failed")?
.ok_or("mail_export_write_failed")?;
write_unique_in(&downloads, &dir, &filename, &bytes, deadline_std, &cancel)
@@ -532,6 +537,52 @@ mod tests {
dir
}
+ #[cfg(unix)]
+ #[test]
+ fn a_chosen_folder_must_be_an_absolute_plain_path() {
+ if crate::mail::tests::isolated() {
+ return;
+ }
+ let fixture = crate::mail::tests::account_fixture(json!({
+ "version": 1,
+ "activeId": "imap:owner@example.org",
+ "accounts": [{"provider": "imap", "email": "owner@example.org",
+ "imap": {"username": "owner@example.org"}}]
+ }));
+ let before = crate::mail::tests::fixture_tree(&fixture.root);
+ let parse = |directory: Value| {
+ ExportRequest::try_from(&json!({
+ "account": "imap:owner@example.org", "id": "1:INBOX", "directory": directory
+ }))
+ .map(|request| request.directory)
+ };
+ assert_eq!(
+ parse(json!("/home/owner/Mail")),
+ Ok(Some(PathBuf::from("/home/owner/Mail")))
+ );
+ for refused in [
+ json!(""),
+ json!("Mail"),
+ json!("./Mail"),
+ json!("/home/owner/../other"),
+ json!("/home/owner/./Mail"),
+ json!("/home/owner//Mail"),
+ json!("/home/owner/Mail/"),
+ json!("/home/owner/Mail\n"),
+ json!("/home/owner/\u{0}Mail"),
+ json!(null),
+ json!(7),
+ ] {
+ assert_eq!(parse(refused.clone()), Err("invalid_params"), "{refused}");
+ }
+ let request = ExportRequest::try_from(&json!({
+ "account": "imap:owner@example.org", "id": "1:INBOX"
+ }))
+ .unwrap();
+ assert_eq!(request.directory, None, "no folder means Downloads");
+ assert_eq!(crate::mail::tests::fixture_tree(&fixture.root), before);
+ }
+
#[test]
fn export_requires_an_explicit_account_without_creating_state() {
if crate::mail::tests::isolated() {
@@ -771,6 +822,7 @@ mod tests {
},
id: "42:INBOX".into(),
suggested_name: "Project update".into(),
+ directory: None,
}
}
@@ -1113,6 +1165,65 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
+ // A picked folder receives the file, and one that is missing is refused
+ // rather than created: only Downloads is made on first use.
+ #[tokio::test]
+ async fn a_chosen_folder_is_written_to_but_never_created() {
+ let dir = scratch("chosen");
+ let limits = ExportLimits::new();
+ let adapter = Fake {
+ payload: json!({"bytes": 4, "data": STANDARD.encode(b"body")}),
+ };
+ let mut chosen = request();
+ chosen.directory = Some(dir.clone());
+ let saved = export_with(
+ chosen,
+ &adapter,
+ &dir,
+ &Value::Null,
+ &limits,
+ &ExportControl::new(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ Path::new(saved["path"].as_str().unwrap()),
+ dir.join("Project update.eml")
+ );
+ assert_eq!(fs::read(dir.join("Project update.eml")).unwrap(), b"body");
+
+ let missing = dir.join("not-there");
+ let mut chosen = request();
+ chosen.directory = Some(missing.clone());
+ assert_eq!(
+ export_with(
+ chosen,
+ &adapter,
+ &missing,
+ &Value::Null,
+ &limits,
+ &ExportControl::new()
+ )
+ .await,
+ Err("mail_export_write_failed")
+ );
+ assert!(!missing.exists(), "a picked folder is never created");
+
+ let downloads = dir.join("Downloads");
+ let made = export_with(
+ request(),
+ &adapter,
+ &downloads,
+ &Value::Null,
+ &limits,
+ &ExportControl::new(),
+ )
+ .await;
+ assert!(made.is_ok(), "{made:?}");
+ assert!(downloads.join("Project update.eml").is_file());
+ fs::remove_dir_all(dir).unwrap();
+ }
+
// A swap of the destination directory after it is anchored must not
// redirect the file: the handle still names the original directory.
#[cfg(unix)]
diff --git a/src/mail/types.rs b/src/mail/types.rs
index 10adbc2..bfb6f95 100644
--- a/src/mail/types.rs
+++ b/src/mail/types.rs
@@ -381,13 +381,15 @@ pub struct ExportRequest {
pub account: Account,
pub id: String,
pub suggested_name: String,
+ /// A folder the user picked. `None` saves to Downloads.
+ pub directory: Option,
}
impl TryFrom<&Value> for ExportRequest {
type Error = &'static str;
fn try_from(value: &Value) -> Result {
- let object = params_object(value, &["account", "id", "suggestedName"])?;
+ let object = params_object(value, &["account", "id", "suggestedName", "directory"])?;
let wanted = object
.get("account")
.and_then(Value::as_str)
@@ -404,14 +406,42 @@ impl TryFrom<&Value> for ExportRequest {
if suggested_name.chars().any(char::is_control) {
return Err("invalid_params");
}
+ let directory = export_directory(object.get("directory"))?;
Ok(Self {
account,
id,
suggested_name,
+ directory,
})
}
}
+/// A chosen destination is an absolute, already normalized folder path. The
+/// writer still anchors it by descriptor and refuses a missing or unsafe one;
+/// this only rejects what can never name a folder before any work starts.
+fn export_directory(value: Option<&Value>) -> Result
", "x".repeat(130_000));
+ assert_eq!(sanitize(&markup, &json!({})).unwrap()["tooHeavy"], true);
+}
+
+#[test]
+fn inline_and_remote_images_share_the_count_budget() {
+ let data = "DATA:image/png;base64,iVBORw0KGgoA";
+ let source = format!(
+ "
Body
{}",
+ format!("").repeat(1000)
+ );
+ let result = sanitize(
+ &source,
+ &json!({"maxImages":1,"withReader":true,
+ "allowRemoteImages":true,"remoteImageData":{"https://cdn.example.com/remote":data}}),
+ )
+ .unwrap();
+ for value in [&result, &result["reader"]] {
+ let html = value["html"].as_str().unwrap();
+ assert_eq!(html.matches("".repeat(3);
+ let result = sanitize(
+ &source,
+ &json!({"withReader":true,"allowRemoteImages":true,
+ "remoteImageData":{"https://cdn.example.com/hero":data}}),
+ )
+ .unwrap();
+ for value in [&result, &result["reader"]] {
+ let html = value["html"].as_str().unwrap();
+ assert_eq!(html.matches("
Date: Sun, 11 Oct 2026 10:39:48 +0200
Subject: [PATCH 17/88] Read the HTML part when the plain alternative contains
markup (#344)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Some senders put the markup itself in the `text/plain` alternative of a
`multipart/alternative` message. `prepare_content` takes the plain part
whenever it is not empty, so the plain-text view of such a message, and
anything else built on its text, is a page of tags and style rules.
A plain part is now treated as markup, and the HTML part read instead,
only when all of these hold: there is an HTML part; the trimmed text
opens with a comment, a doctype or a whole opening tag (`html`, `head`,
`body`, `div`, `table`, `style`, `center`, `span`, `p`); it ends with
`>`; and it contains a closing tag. Text outside this heuristic, such as
a quoted address, stays the sender's text, and a message with no HTML
part is unchanged. Review found that a legitimate sentence beginning
with an opening tag and ending with its closing tag also matches the
heuristic and loses its plain alternative; that false-positive case
still needs to be addressed.
## Reproduction
Seen on a PayPal marketing mail whose `text/plain` part (92,470 bytes)
begins `\n
Send money easily
\n",
+ "
Send money easily
",
+ "
Send money easily
",
+ "
Send money easily
",
+ "
Send money easily
",
+ "
Send money easily
",
+ ] {
+ let body = &super::content::prepare(&message(markup, Some(html)), 0).unwrap()["body"];
+ assert_eq!(body["source"], "html", "{markup}");
+ assert_eq!(body["text"], "Send money easily", "{markup}");
+ }
+ for text in [
+ " wrote:\n> see in the docs",
+ "
is a block element, is not.\nRegards",
+ "Send money easily",
+ "
is a block element; close it with
",
+ "
See the docs for
",
+ " is the root element; close it with ",
+ " contains metadata; close it with ",
+ " contains visible content; close it with ",
+ " contains content ",
+ "
is closed with
",
+ "
code
is an example ending with ",
+ ] {
+ let body = &super::content::prepare(&message(text, Some(html)), 0).unwrap()["body"];
+ assert_eq!(body["source"], "plain", "{text}");
+ assert_eq!(body["text"], text, "{text}");
+ }
+ // With no HTML part there is nothing better to read.
+ let only = "
Send money easily
";
+ let body = &super::content::prepare(&message(only, None), 0).unwrap()["body"];
+ assert_eq!(body["source"], "plain");
+ assert_eq!(body["text"], only);
+}
From 958643362ed6e61ea3441b47232782388e83e720 Mon Sep 17 00:00:00 2001
From: Farzad Hayat
Date: Sun, 11 Oct 2026 18:39:59 +1000
Subject: [PATCH 18/88] Fix IMAP sign-in with pasted password line breaks
(#345)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Fixes #341.
Pasting an IMAP app password with a trailing line break no longer fails
with a generic mail error. Sign-in removes only a final CR/LF suffix,
preserves valid password characters exactly, and reports an inline error
when an unsupported control character remains.
The resulting secret is used for both verification and keyring storage.
Embedded CR/LF, tab, NUL, other C0 controls and DEL are refused before
either operation. Spaces, quotes, backslashes and Unicode remain
unchanged. This prevents silent cleanup from verifying and saving a
different password. Existing saved-secret reads retain their
byte-preserving behavior.
## Verification
- Full `make validate` passed locally on the repaired head `d6544c8`,
including Rust unit/integration suites, JavaScript, shell regressions,
the full QML suite, controlled resource/HTTP tests, standalone
composition, qmllint and plugin validation.
- Current head `5e89fc2` normally integrates `main` at `b0504b9`. The
IMAP implementation and credential regressions are unchanged by that
integration; focused auth (76), credential RPC (8) and setup-form QML
checks (5), standalone composition and qmllint all passed on the
resulting head.
- Password cases cover final CR/LF/CRLF suffixes, every embedded C0
control and DEL, trailing nonnewline controls, empty-after-cleanup
input, and exact preservation of valid secrets. Refused input emits no
verification request and causes no credential-store write.
- That repaired regression produces 65 failures against the original
blanket-cleanup implementation, demonstrating that it silently changed
and accepted unsupported secrets.
- The author reported a live-mailbox sign-in on the original version
under Omarchy 4.0.4-1. Maintainer verification uses synthetic
credentials and controlled fixtures.
## Release Notes
- Accept pasted IMAP passwords with a trailing line break while
preserving the entered secret.
- Explain unsupported password control characters before attempting
sign-in.
## Maintainer supplemental screenshot evidence
Matching synthetic IMAP setup screenshots use the active Omarchy palette
at 900×820, scale 1, Qt 6.11.2. Before shows a generic controlled
backend refusal; after reports a specific unsupported control-character
error immediately. The fixture invokes production ImapAuth and
ImapSetupPage with synthetic settings and a controlled verification
refusal, using no real credentials or mailbox. The captured IMAP
auth/setup behavior remains unchanged in final reviewed head `5e89fc2`;
the base integration adds namespace-qualified theme references from
#346.
**AFTER**

**BEFORE**

---------
Co-authored-by: Jason Lee
---
ui/providers/ImapAuth.qml | 9 +-
ui/tests/qml/tst_credential_rpc.qml | 4 +-
.../qml/tst_imap_credential_control_bytes.qml | 122 ++++++++++++++++++
3 files changed, 132 insertions(+), 3 deletions(-)
create mode 100644 ui/tests/qml/tst_imap_credential_control_bytes.qml
diff --git a/ui/providers/ImapAuth.qml b/ui/providers/ImapAuth.qml
index 89adc79..d539ce3 100644
--- a/ui/providers/ImapAuth.qml
+++ b/ui/providers/ImapAuth.qml
@@ -175,7 +175,14 @@ Item {
lastError = "Missing " + missingTools.join(", ")
return false
}
- var value = String(secret || "")
+ // Pasting from a line can include its trailing line break. Remove only
+ // that suffix; silently changing controls inside a password would verify
+ // and save a different secret from the one the user entered.
+ var value = String(secret || "").replace(/[\r\n]+$/, "")
+ if (/[\x00-\x1f\x7f]/.test(value)) {
+ lastError = "The password contains a control character. Enter it again"
+ return false
+ }
if (value === "") {
lastError = "Enter the password for this mailbox"
return false
diff --git a/ui/tests/qml/tst_credential_rpc.qml b/ui/tests/qml/tst_credential_rpc.qml
index f7f0f17..88eef00 100644
--- a/ui/tests/qml/tst_credential_rpc.qml
+++ b/ui/tests/qml/tst_credential_rpc.qml
@@ -98,11 +98,11 @@ Item {
function test_store_and_delete_are_data_not_process_arguments() {
var auth = createTemporaryObject(imapFactory, root)
verify(auth)
- verify(auth.signIn("$(touch /tmp/never-credential)\r\n"))
+ verify(auth.signIn("$(touch /tmp/never-credential)"))
auth.completeSignIn(true, "")
compare(credentials.writes.length, 1)
compare(credentials.writes[0].kind, "imap-password")
- compare(credentials.writes[0].secret, "$(touch /tmp/never-credential)\r\n")
+ compare(credentials.writes[0].secret, "$(touch /tmp/never-credential)")
auth.logout()
compare(credentials.deletes, [{kind:"imap-password",accountId:"imap:one@example.org",clientId:""}])
}
diff --git a/ui/tests/qml/tst_imap_credential_control_bytes.qml b/ui/tests/qml/tst_imap_credential_control_bytes.qml
new file mode 100644
index 0000000..4d82913
--- /dev/null
+++ b/ui/tests/qml/tst_imap_credential_control_bytes.qml
@@ -0,0 +1,122 @@
+import QtQuick
+import QtTest
+import "../../providers" as Providers
+
+Item {
+ id: root
+
+ QtObject {
+ id: credentials
+ property bool backendCanStoreCredentials: true
+ property var writes: []
+ function reset() { writes = [] }
+ function credentialGet(kind, accountId, clientId, callback) {
+ return true
+ }
+ function credentialPut(kind, accountId, clientId, secret, callback) {
+ writes = writes.concat([{kind:kind,accountId:accountId,clientId:clientId,secret:secret}])
+ callback(true, "")
+ return true
+ }
+ function credentialDelete(kind, accountId, clientId, callback) {
+ callback(true, "")
+ return true
+ }
+ }
+
+ Component {
+ id: imapFactory
+ Providers.ImapAuth {
+ pluginDir: "/synthetic"
+ platform: credentials
+ accountId: "imap:one@example.org"
+ settings: ({imapHost:"imap.example.org",imapPort:993,smtpHost:"smtp.example.org",
+ smtpPort:465,username:"one@example.org",aliases:[],insecure:false})
+ }
+ }
+
+ TestCase {
+ name: "ImapCredentialControlBytes"
+
+ function init() { credentials.reset() }
+
+ function test_a_pasted_password_loses_only_its_trailing_line_break_data() {
+ return [
+ {tag: "CR", suffix: "\r"},
+ {tag: "LF", suffix: "\n"},
+ {tag: "CRLF", suffix: "\r\n"},
+ {tag: "several line breaks", suffix: "\r\n\n"}
+ ]
+ }
+
+ function test_a_pasted_password_loses_only_its_trailing_line_break(data) {
+ var auth = createTemporaryObject(imapFactory, root)
+ verify(auth)
+ var sent = ""
+ auth.verifyRequested.connect(function(settings, value) { sent = value })
+ verify(auth.signIn("app-password " + data.suffix))
+ compare(sent, "one@example.org:app-password ")
+ auth.completeSignIn(true, "")
+ compare(credentials.writes.length, 1)
+ compare(credentials.writes[0].secret, "app-password ")
+ }
+
+ function test_controls_are_refused_without_verification_or_storage_data() {
+ var cases = []
+ for (var byte = 0; byte < 32; byte++) {
+ cases.push({tag: "embedded-" + byte, value: "before" + String.fromCharCode(byte) + "after"})
+ if (byte !== 10 && byte !== 13)
+ cases.push({tag: "trailing-" + byte, value: "password" + String.fromCharCode(byte)})
+ }
+ cases.push({tag: "embedded-DEL", value: "before\u007fafter"})
+ cases.push({tag: "trailing-DEL", value: "password\u007f"})
+ cases.push({tag: "internal-CRLF", value: "before\r\nafter\r\n"})
+ return cases
+ }
+
+ function test_controls_are_refused_without_verification_or_storage(data) {
+ var auth = createTemporaryObject(imapFactory, root)
+ verify(auth)
+ var verifications = 0
+ auth.verifyRequested.connect(function(settings, value) { verifications++ })
+ verify(!auth.signIn(data.value))
+ compare(auth.lastError, "The password contains a control character. Enter it again")
+ compare(verifications, 0)
+ compare(credentials.writes.length, 0)
+ compare(auth.pendingPassword, "")
+ compare(auth.loginBusy, false)
+ compare(auth.password, "")
+ }
+
+ function test_clean_passwords_are_unchanged_data() {
+ return [
+ {tag: "plain", value: "app-password"},
+ {tag: "spaces", value: " leading and trailing "},
+ {tag: "Unicode", value: "päss密碼🔑"},
+ {tag: "quotes and backslashes", value: "a\"'b\\c:$()"}
+ ]
+ }
+
+ function test_clean_passwords_are_unchanged(data) {
+ var auth = createTemporaryObject(imapFactory, root)
+ verify(auth)
+ var sent = ""
+ auth.verifyRequested.connect(function(settings, value) { sent = value })
+ verify(auth.signIn(data.value))
+ compare(sent, "one@example.org:" + data.value)
+ auth.completeSignIn(true, "")
+ compare(credentials.writes.length, 1)
+ compare(credentials.writes[0].secret, data.value)
+ }
+
+ function test_only_line_breaks_do_not_verify_or_store() {
+ var auth = createTemporaryObject(imapFactory, root)
+ var verifications = 0
+ auth.verifyRequested.connect(function(settings, value) { verifications++ })
+ verify(!auth.signIn("\r\n"))
+ compare(auth.lastError, "Enter the password for this mailbox")
+ compare(verifications, 0)
+ compare(credentials.writes.length, 0)
+ }
+ }
+}
From 6d0a7e7b9fcd2b0ff489f62d13de597fb486ae42 Mon Sep 17 00:00:00 2001
From: taisau
Date: Sun, 11 Oct 2026 02:17:59 -0700
Subject: [PATCH 19/88] Copy the subject line from the reader header (#262)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## What changes
A right-click on the reader-header subject line opens a one-row menu,
**Copy subject**, and copies the subject as written to the clipboard —
use cases like ticket IDs, order numbers and other verbatim strings want
the subject whole, and today it had to be selected by hand or retyped.
The menu is `ui/components/SubjectMenu.qml`, in the AddressMenu shape: a
`QQC.Popup`, one `MenuActionRow`, keyboard navigation through the same
`Menu.js` helpers (J/K/arrows, Enter/O), `closePolicy`
outside-click/Escape. Copy is a signal the host routes — `MessageReader`
hands it to `service.copyText`, the path the body's `TextMenu` already
uses, so the text reaches `wl-copy` as a single argv entry with no shell
in between.
The reader owns the menu rather than App, the reason the body's menu was
moved into the reader: it is tested with the summary it reads. The
subject `Text` gains a `RightButton` `TapHandler` beside the ones the
From and To lines already carry. The menu anchors to the line's own
lower edge rather than the click point, and an empty or whitespace-only
subject refuses to open, the way `AddressMenu.openAt` refuses a line
that held no addresses.
## Verification
`make validate` green on the commit sent, run against **v0.10.7**
(`a3b7616`) as the base: QML `1166 passed, 0 failed`, the Rust suite
`597 passed, 0 failed` plus the standalone composition test, and
`qmllint`, `omarchy plugin validate .` and `git diff --check` are clean.
The QML count is up from `997` at the previous base because 0.10.7 adds
its own cases.
The branch was rebased onto 0.10.7 after the original review. The rebase
applied the four-file payload without a conflict, so the diff is
byte-identical to what was reviewed — same `Makefile` line, the same 27
added lines in `MessageReader.qml`, and both new files. What changed
underneath it is `MessageReader.qml` itself, which 0.10.7 rewrites
(+84/-25 across `afcd736`, `af8a7ae`); the `SubjectMenu` block sits at
the end of the file and the `subjectLine` `TapHandler` in the reader
header, and the 6 cases below pass against that rewritten reader.
`ui/tests/qml/tst_reader_subject_menu.qml` (6 cases) covers the
right-click opening the menu, the single row named for what it copies,
that copy routes the exact subject through the service and closes, that
an empty or whitespace-only subject opens nothing and copies nothing,
and that the menu lands at the line's edge rather than under the
pointer. The two cases added after review were each watched failing with
their fix reverted (`6 passed, 2 failed`) and pass with it (`8 passed, 0
failed`).
A fresh, context-free agent reviewed the diff against `AGENTS.md`. It
found no blocker — security verdict **PASS**: the subject reaches
`wl-copy` through the same no-shell `service.copyText` channel the
body's Copy already uses — and three findings, all answered:
- The popup anchored to the click point; it now anchors to the trigger
line's own lower edge (`MessageReader.qml`), per the Popups rule.
- The empty-subject guard was exact-match, so a whitespace-only subject
still opened the menu; it now refuses when the subject trims to empty,
while still copying the text verbatim.
- The subject line holds no selected style while its menu is open. Left
as it is: the neighbouring From, To and body triggers have the same
omission, and aligning all four is a change of its own.
Driven live on the running shell: right-click a subject → **Copy
subject** → paste elsewhere.
## Release Notes
- Right-click a message's subject to copy it.
---------
Co-authored-by: taisau
Co-authored-by: Jason Lee
---
Makefile | 6 +-
app/qml/imports/Quickshell/Quickshell.qml | 12 +-
app/tests/qml/tst_host_contract.qml | 10 +
tests/test_clipboard.py | 43 ++++
ui/Service.qml | 4 +-
ui/components/MessageReader.qml | 63 ++++--
ui/components/SubjectMenu.qml | 119 +++++++++++
.../qml/imports/Quickshell/Quickshell.qml | 6 +-
ui/tests/qml/tst_clipboard_arguments.qml | 41 ++++
ui/tests/qml/tst_reader_subject_menu.qml | 187 ++++++++++++++++++
10 files changed, 471 insertions(+), 20 deletions(-)
create mode 100644 tests/test_clipboard.py
create mode 100644 ui/components/SubjectMenu.qml
create mode 100644 ui/tests/qml/tst_clipboard_arguments.qml
create mode 100644 ui/tests/qml/tst_reader_subject_menu.qml
diff --git a/Makefile b/Makefile
index e6fb285..d71e08d 100644
--- a/Makefile
+++ b/Makefile
@@ -2,7 +2,8 @@ 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/tests/compatibility/tst_published_agent.qml \
- ui/tests/qml/tst_unified_batch.qml \
+ ui/tests/qml/tst_unified_batch.qml ui/tests/qml/tst_clipboard_arguments.qml \
+ ui/tests/qml/tst_reader_subject_menu.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/UnifiedBatchAction.qml ui/account/UnifiedBatchSelection.qml ui/account/Rsvp.qml ui/account/LabelActions.qml ui/account/Unsubscribe.qml ui/account/NewMailNotification.qml \
@@ -58,7 +59,7 @@ QML_FILES := ui/Service.qml ui/BarWidget.qml ui/App.qml ui/compose/RecoveryContr
ui/components/LabelMenu.qml \
ui/components/LabelMovePicker.qml \
ui/components/NamePrompt.qml \
- ui/components/AddressMenu.qml ui/components/TextMenu.qml \
+ ui/components/AddressMenu.qml ui/components/TextMenu.qml ui/components/SubjectMenu.qml \
ui/components/ComposeAgent.qml \
ui/agent/AgentRunner.qml ui/agent/AgentContext.qml \
ui/agent/EventSuggester.qml ui/components/EventSuggestionCard.qml \
@@ -194,6 +195,7 @@ test-shell-portable:
python3 tests/test_contacts.py
python3 tests/test_qml_names.py
python3 tests/test_qml_text_format.py
+ python3 tests/test_clipboard.py
bash tests/test_source.sh
bash tests/test_service_source.sh
bash tests/test_config_store.sh
diff --git a/app/qml/imports/Quickshell/Quickshell.qml b/app/qml/imports/Quickshell/Quickshell.qml
index 4f02ce7..544de73 100644
--- a/app/qml/imports/Quickshell/Quickshell.qml
+++ b/app/qml/imports/Quickshell/Quickshell.qml
@@ -14,11 +14,15 @@ QtObject {
}
function execDetached(command) {
- if (!nativeHost || !Array.isArray(command) || command.length !== 2) return false
- if (command[0] === "xdg-open" && typeof nativeHost.openExternal === "function")
+ if (!nativeHost || !Array.isArray(command)) return false
+ if (command.length === 2 && command[0] === "xdg-open" && typeof nativeHost.openExternal === "function")
return !!nativeHost.openExternal(String(command[1]))
- if (command[0] === "wl-copy" && typeof nativeHost.setClipboard === "function")
- return !!nativeHost.setClipboard(String(command[1]))
+ if (command[0] === "wl-copy" && typeof nativeHost.setClipboard === "function") {
+ if (command.length === 3 && command[1] === "--")
+ return !!nativeHost.setClipboard(String(command[2]))
+ if (command.length === 2)
+ return !!nativeHost.setClipboard(String(command[1]))
+ }
return false
}
diff --git a/app/tests/qml/tst_host_contract.qml b/app/tests/qml/tst_host_contract.qml
index d5f4d72..b112d17 100644
--- a/app/tests/qml/tst_host_contract.qml
+++ b/app/tests/qml/tst_host_contract.qml
@@ -157,6 +157,16 @@ TestCase {
compare(host.copied.length, 1)
}
+ function test_clipboard_option_terminator_keeps_text_verbatim() {
+ var subjects = ["--version", "--clear", "-p", "田中 \"quoted\" \\ body\nline two", ""]
+ for (var i = 0; i < subjects.length; i++)
+ verify(Quickshell.execDetached(["wl-copy", "--", subjects[i]]))
+ compare(host.copied, subjects)
+ verify(!Quickshell.execDetached(["wl-copy", "--type", "text/html"]))
+ verify(!Quickshell.execDetached(["wl-copy", "--", "text", "extra"]))
+ compare(host.copied, subjects)
+ }
+
function test_notification_process_routes_to_native_host() {
var process = createTemporaryObject(notificationProcessComponent, testCase)
verify(process)
diff --git a/tests/test_clipboard.py b/tests/test_clipboard.py
new file mode 100644
index 0000000..e50bc3c
--- /dev/null
+++ b/tests/test_clipboard.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+"""Verify Service's real wl-copy arguments cannot execute clipboard options."""
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+
+ROOT = Path(__file__).resolve().parents[1]
+runner = shutil.which("qmltestrunner6") or shutil.which("qmltestrunner")
+if not runner and Path("/usr/lib/qt6/bin/qmltestrunner").exists():
+ runner = "/usr/lib/qt6/bin/qmltestrunner"
+clipboard = shutil.which("wl-copy")
+if not runner or not clipboard:
+ print("Clipboard transport regression SKIP: requires QML test tooling and wl-copy")
+ raise SystemExit(0)
+
+with tempfile.TemporaryDirectory(prefix="omamail-clipboard-") as directory:
+ env = dict(os.environ, XDG_RUNTIME_DIR=directory,
+ XDG_CONFIG_HOME=directory, XDG_DATA_HOME=directory,
+ XDG_CACHE_HOME=directory, XDG_STATE_HOME=directory,
+ WAYLAND_DISPLAY="unavailable-review-display",
+ QT_QPA_PLATFORM="offscreen", QT_QUICK_BACKEND="software",
+ QT_QPA_PLATFORMTHEME="", GSETTINGS_BACKEND="memory")
+ result = subprocess.run([runner, "-input", str(ROOT / "ui/tests/qml/tst_clipboard_arguments.qml"),
+ "-import", str(ROOT / "ui/tests/qml/imports")],
+ env=env, text=True, capture_output=True, timeout=30)
+ assert result.returncode == 0, result.stdout + result.stderr
+ commands = [json.loads(line.split("OMAMAIL_CLIPBOARD_ARGUMENTS:", 1)[1])
+ for line in result.stdout.splitlines() if "OMAMAIL_CLIPBOARD_ARGUMENTS:" in line]
+ assert len(commands) == 7, result.stdout
+ for command in commands:
+ result = subprocess.run(command, env=env, text=True, capture_output=True, timeout=5)
+ assert result.returncode != 0, (command, result.stdout, result.stderr)
+ assert result.stdout == "", (command, result.stdout)
+ assert "Failed to connect to a Wayland server" in result.stderr, (command, result.stderr)
+ # Negative control: the vulnerable argument list executes --version and
+ # succeeds, even though this display cannot accept clipboard writes.
+ vulnerable = subprocess.run([clipboard, "--version"], env=env,
+ text=True, capture_output=True, timeout=5)
+ assert vulnerable.returncode == 0 and "wl-clipboard" in vulnerable.stdout
+print("Clipboard transport regression PASS; no clipboard connection or option action")
diff --git a/ui/Service.qml b/ui/Service.qml
index d02543d..c3ded4f 100644
--- a/ui/Service.qml
+++ b/ui/Service.qml
@@ -501,7 +501,9 @@ Item {
var text = String(value === undefined || value === null ? "" : value)
if (platform && typeof platform.setClipboard === "function")
return platform.setClipboard(text)
- return Quickshell.execDetached(["wl-copy", text])
+ // NUL cannot cross argv without truncating the sender's text.
+ if (text.indexOf("\0") >= 0) return false
+ return Quickshell.execDetached(["wl-copy", "--", text])
}
function configPath(name) {
diff --git a/ui/components/MessageReader.qml b/ui/components/MessageReader.qml
index e2533eb..2bfd57a 100644
--- a/ui/components/MessageReader.qml
+++ b/ui/components/MessageReader.qml
@@ -369,19 +369,44 @@ Item {
anchors.topMargin: backBar.visible ? Style.space(14) : 0
spacing: Style.space(4)
- Text {
+ Item {
width: parent.width
- // A stranger wrote this. Qt's default AutoText switches a string that
- // looks like markup into rich text, and rich text with an in it is
- // a fetch — the same beacon the message body is stripped of.
- textFormat: Text.PlainText
- text: root.summary ? root.summary.subject : ""
- color: root.textColor
- font.family: root.panelFontFamily
- font.pixelSize: Style.font.subtitle
- font.bold: true
- wrapMode: Text.WordWrap
- horizontalAlignment: root.subjectAlignment
+ height: subjectLine.implicitHeight
+ Rectangle {
+ objectName: "reader-subject-selection"
+ anchors.fill: parent
+ radius: Style.cornerRadius
+ visible: subjectLine.selected
+ color: Qt.rgba(root.textColor.r, root.textColor.g, root.textColor.b, 0.08)
+ }
+ Text {
+ id: subjectLine
+ objectName: "reader-subject"
+ width: parent.width
+ // A stranger wrote this. Qt's default AutoText switches a string that
+ // looks like markup into rich text, and rich text with an in it is
+ // a fetch — the same beacon the message body is stripped of.
+ textFormat: Text.PlainText
+ text: root.summary ? root.summary.subject : ""
+ color: root.textColor
+ font.family: root.panelFontFamily
+ font.pixelSize: Style.font.subtitle
+ font.bold: true
+ wrapMode: Text.WordWrap
+ horizontalAlignment: root.subjectAlignment
+
+ readonly property bool selected: subjectMenu.opened
+ TapHandler {
+ acceptedButtons: Qt.RightButton
+ onTapped: function(eventPoint) {
+ if (!root.summary) return
+ // Anchor to the line's own lower edge, not the pointer, so the menu
+ // lands in the same place however the line was pressed.
+ var scene = subjectLine.mapToGlobal(0, subjectLine.height)
+ subjectMenu.openAt(root.summary.subject, scene.x, scene.y)
+ }
+ }
+ }
}
Text {
@@ -1109,6 +1134,20 @@ Item {
onOpenLinkRequested: function(url) { root.openLink(url) }
}
+ // The subject's own menu: one row, the subject as written. Beside the
+ // body's menu for the same reason that menu lives here.
+ SubjectMenu {
+ id: subjectMenu
+ objectName: "reader-subject-menu"
+ textColor: root.textColor
+ popupBackgroundColor: root.popupBackgroundColor
+ popupBorderColor: root.popupBorderColor
+ panelFontFamily: root.panelFontFamily
+ onCopyRequested: function(subject) {
+ if (root.service && typeof root.service.copyText === "function") root.service.copyText(subject)
+ }
+ }
+
ImagePopover {
id: imagePopover
textColor: root.textColor
diff --git a/ui/components/SubjectMenu.qml b/ui/components/SubjectMenu.qml
new file mode 100644
index 0000000..6c0a595
--- /dev/null
+++ b/ui/components/SubjectMenu.qml
@@ -0,0 +1,119 @@
+import QtQuick
+import QtQuick.Controls as QQC
+import qs.Commons
+import qs.Ui
+import "Menu.js" as Menu
+
+// The menu a right-click on the reader's subject opens: the subject as
+// written, copied whole. One row, the way AddressMenu is one pattern — Copy
+// goes out as a signal because the host owns the platform clipboard. The
+// empty subject refuses an open, the way AddressMenu refuses a line that
+// held no addresses.
+Item {
+ id: root
+
+ required property color textColor
+ required property color popupBackgroundColor
+ required property color popupBorderColor
+ required property string panelFontFamily
+
+ // The subject the click landed on, set at open time rather than bound.
+ property string subject: ""
+ property int cursorIndex: -1
+ readonly property bool opened: menu.opened
+ readonly property var menuRows: [copyRow]
+ readonly property alias copyRow: copyRow
+ // Exposed so a test can assert where the menu landed, the way copyRow is.
+ readonly property alias popup: menu
+
+ signal copyRequested(string subject)
+
+ anchors.fill: parent
+ z: 50
+
+ property real anchorX: 0
+ property real anchorY: 0
+
+ function openAt(text, sceneX, sceneY) {
+ subject = String(text || "")
+ // A subject of only spaces is one the reader cannot show anything for; it
+ // is refused like an empty one. The text is still copied verbatim, so a
+ // real subject keeps the spacing it was sent with.
+ if (subject.trim() === "") return
+ var local = root.mapFromGlobal(sceneX, sceneY)
+ anchorX = local.x
+ anchorY = local.y
+ menu.open()
+ }
+
+ function place() {
+ if (!menu.visible) return
+ var tall = menu.height > 0 ? menu.height : menu.implicitHeight
+ var placed = Menu.position(anchorX, anchorY, menu.width, tall, root.width, root.height)
+ menu.x = placed.x
+ menu.y = placed.y
+ }
+
+ function selectableRows() {
+ var values = []
+ for (var i = 0; i < menuRows.length; i++) values.push({
+ selectable: true, visible: menuRows[i].visible, enabled: menuRows[i].enabled
+ })
+ return values
+ }
+ function moveCursor(step) { cursorIndex = Menu.nextSelectable(selectableRows(), cursorIndex, step) }
+ function runCursor() { if (cursorIndex >= 0) menuRows[cursorIndex].activated() }
+ function close() { menu.close() }
+
+ QQC.Popup {
+ id: menu
+ width: Style.space(180)
+ implicitHeight: rows.implicitHeight + Style.space(8)
+ padding: Style.space(4)
+ modal: false
+ focus: true
+ closePolicy: QQC.Popup.CloseOnEscape | QQC.Popup.CloseOnPressOutside
+ onHeightChanged: root.place()
+ onOpened: {
+ root.cursorIndex = Menu.firstSelectable(root.selectableRows())
+ root.place()
+ }
+ background: Rectangle {
+ radius: Style.cornerRadius
+ color: root.popupBackgroundColor
+ border.width: 1
+ border.color: root.popupBorderColor
+ }
+
+ contentItem: Column {
+ id: rows
+ spacing: Style.space(2)
+
+ focus: true
+ Keys.onPressed: function(event) {
+ if (event.key === Qt.Key_J || event.key === Qt.Key_Down) {
+ root.moveCursor(1); event.accepted = true
+ } else if (event.key === Qt.Key_K || event.key === Qt.Key_Up) {
+ root.moveCursor(-1); event.accepted = true
+ } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter
+ || event.key === Qt.Key_O) {
+ root.runCursor(); event.accepted = true
+ }
+ }
+
+ MenuRow {
+ id: copyRow
+ text: "Copy subject"
+ onActivated: { var subject = root.subject; menu.close(); root.copyRequested(subject) }
+ }
+ }
+ }
+
+ component MenuRow: MenuActionRow {
+ width: menu.width - menu.leftPadding - menu.rightPadding
+ textColor: root.textColor
+ panelFontFamily: root.panelFontFamily
+ collection: root.menuRows
+ cursorIndex: root.cursorIndex
+ }
+}
diff --git a/ui/tests/qml/imports/Quickshell/Quickshell.qml b/ui/tests/qml/imports/Quickshell/Quickshell.qml
index 4293058..461683b 100644
--- a/ui/tests/qml/imports/Quickshell/Quickshell.qml
+++ b/ui/tests/qml/imports/Quickshell/Quickshell.qml
@@ -5,7 +5,11 @@ QtObject {
property var notifications: []
signal notificationActivated(string accountId, string messageId)
function env(name) { return "" }
- function execDetached(command) {}
+ property var detachedCommands: []
+ function execDetached(command) {
+ detachedCommands = detachedCommands.concat([command.slice()])
+ return true
+ }
function showNotification(id, title, body, accountId, messageId) {
notifications = notifications.concat([{
id: String(id), title: String(title), body: String(body),
diff --git a/ui/tests/qml/tst_clipboard_arguments.qml b/ui/tests/qml/tst_clipboard_arguments.qml
new file mode 100644
index 0000000..1a4aae5
--- /dev/null
+++ b/ui/tests/qml/tst_clipboard_arguments.qml
@@ -0,0 +1,41 @@
+import QtQuick
+import QtTest
+import Quickshell
+import "../.." as Omamail
+
+Item {
+ Component { id: factory; Omamail.Service {} }
+ TestCase {
+ name: "ClipboardArguments"
+ function init() { Quickshell.detachedCommands = [] }
+ function test_sender_text_cannot_be_a_clipboard_option() {
+ var service = createTemporaryObject(factory, parent)
+ verify(service)
+ var values = ["--version", "--clear", "-p", "--type=text/html",
+ "田中 \"quoted\" \\ body\nline two", "", "trailing\r\n"]
+ for (var i = 0; i < values.length; i++) {
+ verify(service.copyText(values[i]))
+ var command = Quickshell.detachedCommands[i]
+ compare(command, ["wl-copy", "--", values[i]])
+ // The transport regression consumes the command actually emitted by
+ // Service, then runs wl-copy against an unavailable display.
+ console.log("OMAMAIL_CLIPBOARD_ARGUMENTS:" + JSON.stringify(command))
+ }
+ }
+ function test_nul_is_refused_before_any_process_starts() {
+ var service = createTemporaryObject(factory, parent)
+ verify(service)
+ verify(!service.copyText("--clear\0text"))
+ compare(Quickshell.detachedCommands, [])
+ }
+ function test_native_clipboard_receives_text_without_process_arguments() {
+ var service = createTemporaryObject(factory, parent)
+ verify(service)
+ var copied = []
+ service.platform = {setClipboard: function(text) { copied.push(text); return true }}
+ verify(service.copyText("--clear"))
+ compare(copied, ["--clear"])
+ compare(Quickshell.detachedCommands, [])
+ }
+ }
+}
diff --git a/ui/tests/qml/tst_reader_subject_menu.qml b/ui/tests/qml/tst_reader_subject_menu.qml
new file mode 100644
index 0000000..bd6310f
--- /dev/null
+++ b/ui/tests/qml/tst_reader_subject_menu.qml
@@ -0,0 +1,187 @@
+import QtQuick 2.15
+import QtTest 1.3
+import qs.Commons
+import "../../components" as Omamail
+import "../../message/Html.js" as Html
+
+// A right-click on the reader's subject: one row, the subject as written,
+// copied through the host.
+Item {
+ width: 900
+ height: 600
+
+ readonly property string senderHtml: '
Person 1 moved 4 cards.
'
+
+ readonly property var rendered: Html.sanitize(senderHtml, ({ withReader: true }))
+
+ QtObject {
+ id: mailService
+
+ property var copied: []
+
+ property string selectedId: "message-9"
+ property var selectedMessage: ({
+ id: "message-9",
+ subject: "Activity on Sprint board",
+ from: ({ display: "Boards", email: "boards@example.com" }),
+ to: [({ display: "Reader", email: "reader@example.com" })],
+ fullTime: "24 August 2026",
+ starred: false
+ })
+ property bool detailLoading: false
+ property bool detailPainted: true
+ property bool selectedHasHtml: rendered.html !== ""
+ property var selectedDocument: rendered.document
+ property var selectedReaderDocument: rendered.reader.document
+ property bool selectedReaderTooHeavy: rendered.reader.tooHeavy
+ property bool selectedReaderEmpty: rendered.reader.empty
+ property int selectedRemoteImages: rendered.remoteImages
+ property bool remoteImagesAllowed: false
+ property bool selectedTooHeavy: rendered.tooHeavy
+ property string unsubscribeLabel: ""
+ property string unsubscribeDetail: ""
+ property bool unsubscribing: false
+ property var selectedBody: ({ text: "Person 1 moved 4 cards.", source: "html" })
+ property var selectedImages: []
+ property var selectedInvite: null
+ property string selectedResponse: ""
+ property bool canRespondToInvite: false
+ property bool rsvpSending: false
+ property bool canArchive: true
+ property bool canOpenOnWeb: false
+ property var selectedAttachments: []
+
+ function getMessage() {}
+ function showRemoteImages() {}
+ function copyText(text) { copied = copied.concat([String(text)]); return true }
+ function openExternal(url) { return true }
+ }
+
+ Omamail.MessageReader {
+ id: reader
+ width: 900
+ height: 600
+ 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)
+ linkColor: Qt.rgba(0.3, 0.7, 1, 1)
+ dimColor: Qt.rgba(0.67, 0.67, 0.67, 1)
+ popupBackgroundColor: Qt.rgba(0.13, 0.13, 0.13, 1)
+ popupBorderColor: Qt.rgba(0.47, 0.47, 0.47, 1)
+ leadingBoundaryOverlap: 0
+ dimmerColor: Qt.rgba(0.47, 0.47, 0.47, 1)
+ panelFontFamily: "monospace"
+ bodyMode: "reader"
+ onBodyModeRequested: function(mode) { reader.bodyMode = mode }
+ }
+
+ TestCase {
+ name: "ReaderSubjectMenu"
+ when: windowShown
+
+ function named(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 hit = named(values[i], name)
+ if (hit) return hit
+ }
+ return null
+ }
+
+ function subjectLine() {
+ var line = named(reader, "reader-subject")
+ verify(line, "the reader draws its subject in a Text")
+ return line
+ }
+
+ function menu() {
+ var found = named(reader, "reader-subject-menu")
+ verify(found, "the reader owns a subject menu")
+ return found
+ }
+
+ function init() {
+ menu().close()
+ mailService.selectedMessage.subject = "Activity on Sprint board"
+ mailService.copied = []
+ }
+
+ function cleanup() { menu().close() }
+
+ function test_a_right_click_on_the_subject_opens_the_menu() {
+ mouseClick(subjectLine(), 30, subjectLine().height / 2, Qt.RightButton)
+ tryVerify(function() { return menu().opened }, 1000, "the menu opens")
+ wait(20)
+ compare(menu().copyRow.enabled, true)
+ }
+
+ function test_copy_copies_the_subject_through_the_service() {
+ mouseClick(subjectLine(), 30, subjectLine().height / 2, Qt.RightButton)
+ tryVerify(function() { return menu().opened }, 1000, "the menu opens")
+ wait(20)
+ menu().copyRow.activated()
+ tryVerify(function() { return menu().opened === false }, 1000, "the menu closes")
+ compare(mailService.copied, ["Activity on Sprint board"])
+ }
+
+ function test_the_menu_holds_one_row_named_for_what_it_copies() {
+ mouseClick(subjectLine(), 30, subjectLine().height / 2, Qt.RightButton)
+ tryVerify(function() { return menu().opened }, 1000, "the menu opens")
+ wait(20)
+ compare(menu().menuRows.length, 1)
+ compare(menu().copyRow.text, "Copy subject")
+ }
+
+ function test_an_empty_subject_does_not_open_the_menu() {
+ mailService.selectedMessage.subject = ""
+ mouseClick(subjectLine(), 30, subjectLine().height / 2, Qt.RightButton)
+ wait(20)
+ compare(menu().opened, false)
+ compare(mailService.copied, [])
+ }
+
+ function test_a_whitespace_only_subject_does_not_open_the_menu() {
+ mailService.selectedMessage.subject = " "
+ mouseClick(subjectLine(), 30, subjectLine().height / 2, Qt.RightButton)
+ wait(20)
+ compare(menu().opened, false)
+ compare(mailService.copied, [])
+ }
+
+ function test_the_subject_stays_selected_until_the_menu_closes() {
+ compare(subjectLine().selected, false)
+ mouseClick(subjectLine(), 30, subjectLine().height / 2, Qt.RightButton)
+ tryVerify(function() { return menu().opened })
+ compare(subjectLine().selected, true)
+ var selection = named(reader, "reader-subject-selection")
+ verify(selection.visible)
+ verify(selection.color.a > 0)
+ compare(selection.height, subjectLine().height)
+ keyClick(Qt.Key_Escape)
+ tryVerify(function() { return !menu().opened })
+ compare(subjectLine().selected, false)
+ compare(selection.visible, false)
+ }
+
+ function test_keyboard_activation_copies_the_snapshot_verbatim() {
+ var subject = " --version \\ <工单> \"quoted\"\nline two "
+ mailService.selectedMessage.subject = subject
+ mouseClick(subjectLine(), 30, subjectLine().height / 2, Qt.RightButton)
+ tryVerify(function() { return menu().opened })
+ keyClick(Qt.Key_Return)
+ tryVerify(function() { return !menu().opened })
+ compare(mailService.copied, [subject])
+ }
+
+ function test_the_menu_anchors_to_the_line_not_the_pointer() {
+ mouseClick(subjectLine(), 120, subjectLine().height / 2, Qt.RightButton)
+ tryVerify(function() { return menu().opened }, 1000, "the menu opens")
+ wait(20)
+ compare(menu().popup.x, subjectLine().mapToItem(menu().popup.parent, 0, 0).x,
+ "the menu anchors to the line's edge, not the click point")
+ }
+ }
+}
From c8d57c325933342a32dbd7f617589c4e9737029f Mon Sep 17 00:00:00 2001
From: Jason Lee
Date: Sun, 11 Oct 2026 17:40:06 +0800
Subject: [PATCH 20/88] chore: Fix release source size and Windows Rust test
coverage (#352)
Two existing issues prevent a fully verified release: `App.qml` exceeds
the 128 KiB source-size ceiling, and the Windows release job omits the
complete standalone Rust suite.
Extract reply/forward startup and deferred resume into
`compose/PendingCompose.qml`, bringing `App.qml` from 131,279 to 130,345
bytes. App retains ownership of pending state, and the controller
receives the composer and assistant surfaces explicitly. Replies still
wait for painted message detail and retain the existing assistant
conversation handoff. The module is included in lint inputs.
Run the complete standalone Rust suite in the Windows release job before
building the backend. PowerShell checks its exit code and stops on
failure, so packaging cannot continue after failed tests. Add a workflow
regression requiring this complete suite on each native release platform
and the Windows failure guard. This matches the native release
requirements in `docs/BACKEND-RUNTIME.md`.
Verification:
- Full `make validate` passed for the source extraction (`92d553d`) with
Qt 6.11.2, including 1,283 QML cases, standalone composition,
source-size checks, lint, plugin validation, and whitespace checks; the
focused compose suite passed all 99 cases.
- After incorporating current main and #262, the combined QML suite
passed all 1,298 cases, with Outlook HTTP, sidebar, native HTML
resource-denial, and lint checks passing. Source-size and real clipboard
transport regressions passed.
- All 13 release workflow contract cases, 26 backend release cases,
release-source checks, and publish-script tests passed. The workflow
regression fails with the Windows test invocation removed.
- The local standalone backend API 7 contract passed. Windows native
release results will be established by the authoritative release job;
this PR does not claim those results in advance.
Security: PASS for the affected compose state and release failure guard.
The extraction preserves existing app-owned account/message inputs; the
workflow adds test coverage without changing publication permissions,
secrets, or build destinations.
---
.github/workflows/release.yml | 2 ++
Makefile | 2 +-
app/tests/test_release_workflow.py | 12 +++++++++
ui/App.qml | 41 +++++++-----------------------
ui/compose/PendingCompose.qml | 41 ++++++++++++++++++++++++++++++
5 files changed, 65 insertions(+), 33 deletions(-)
create mode 100644 ui/compose/PendingCompose.qml
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index ffcbfa9..fdd5d30 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -295,6 +295,8 @@ jobs:
QT_QUICK_CONTROLS_FALLBACK_STYLE: Basic
run: |
$ErrorActionPreference = "Stop"
+ cargo test --locked --no-default-features --features standalone,integration-test-credentials
+ if ($LASTEXITCODE -ne 0) { throw "standalone Rust tests failed" }
cargo build --release --locked --no-default-features --features standalone
if ($LASTEXITCODE -ne 0) { throw "standalone backend build failed" }
cmake -S app -B build/app -G "Visual Studio 17 2022" -A x64 -DOMAMAIL_BACKEND="$PWD/target/release/omamail.exe"
diff --git a/Makefile b/Makefile
index d71e08d..c862068 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
QMLLINT := /usr/lib/qt6/bin/qmllint
.DEFAULT_GOAL := test
-QML_FILES := ui/Service.qml ui/BarWidget.qml ui/App.qml ui/compose/RecoveryController.qml \
+QML_FILES := ui/Service.qml ui/BarWidget.qml ui/App.qml ui/compose/RecoveryController.qml ui/compose/PendingCompose.qml \
ui/tests/compatibility/tst_published_agent.qml \
ui/tests/qml/tst_unified_batch.qml ui/tests/qml/tst_clipboard_arguments.qml \
ui/tests/qml/tst_reader_subject_menu.qml \
diff --git a/app/tests/test_release_workflow.py b/app/tests/test_release_workflow.py
index 76e4cc9..9afd3a5 100644
--- a/app/tests/test_release_workflow.py
+++ b/app/tests/test_release_workflow.py
@@ -102,6 +102,18 @@ def test_each_native_job_runs_backend_qt_qml_package_installer_and_live_smoke_ga
self.assertIn("package-release.sh", block)
self.assertIn('--host "$PWD/build/app/omamail-app"', block)
+ def test_every_native_release_runs_the_complete_standalone_rust_suite(self):
+ command = "cargo test --locked --no-default-features --features standalone,integration-test-credentials"
+ for job in APP_JOBS:
+ with self.subTest(job=job):
+ block = job_block(self.workflow, job)
+ self.assertIn(command, block)
+ self.assertLess(block.index(command), block.index("cargo build --release"))
+ if "windows" in job:
+ # A failed cargo invocation must stop PowerShell before it
+ # can build or publish an archive.
+ self.assertIn(command + '\n if ($LASTEXITCODE -ne 0) { throw "standalone Rust tests failed" }', block)
+
def test_pull_requests_build_and_exercise_each_production_standalone_archive(self):
forbidden = ("gh release create", "gh release edit", "publish-backend.sh")
for job, (runner, target, archive) in CI_APP_JOBS.items():
diff --git a/ui/App.qml b/ui/App.qml
index fa9232c..dadb1fa 100644
--- a/ui/App.qml
+++ b/ui/App.qml
@@ -12,6 +12,7 @@ import "account" as Account
import "account/Accounts.js" as Accounts
import "account/Navigation.js" as Nav
import "compose/Recovery.js" as Recovery
+import "compose" as Compose
import "keys/Keymap.js" as Keymap
import "providers/Registry.js" as Provider
import "agent/Agent.js" as Agent
@@ -674,33 +675,14 @@ Item {
return currentView === "reader" ? "reader" : "list"
}
- // A listed row supplies the summary the moment it is selected, before the
- // body is read; a draft begun on the summary alone quotes nothing.
- function detailReady() {
- return !!service.selectedMessage && !service.detailLoading && service.detailPainted
- }
-
- function startCompose(mode) {
- if (!service) return
- pendingDraftId = ""
- var next = String(mode || "new")
- if (next !== "new" && !detailReady()) {
- pendingComposeMode = next
- return
- }
- pendingComposeMode = ""
- var keepAssistant = agentPrompt.opened
- var conversation = keepAssistant ? agentPrompt.job : null
- compose.begin(next, service.selectedMessage, service.selectedBody.text,
- service.selectedAttachments)
- if (keepAssistant) {
- if ((next === "reply" || next === "replyAll") && conversation
- && String(conversation.accountId) === compose.accountId
- && String(conversation.messageId) === compose.replyMessageId)
- compose.agentParentJobId = String(conversation.id)
- composeAgent.open()
- }
+ Compose.PendingCompose {
+ id: pendingCompose
+ app: root
+ composer: compose
+ assistant: root.agentPrompt
+ composeAssistant: root.composeAgent
}
+ function startCompose(mode) { pendingCompose.start(mode) }
// A mailto: URL, or the blank draft `compose: true` asks for. The window is
// already open when this runs — summon delivers the payload to open().
@@ -710,12 +692,7 @@ Item {
compose.beginDraft(draft)
}
- function resumeHeldCompose() {
- if (pendingComposeMode === "" || !service || !detailReady()) return
- var mode = pendingComposeMode
- pendingComposeMode = ""
- startCompose(mode)
- }
+ function resumeHeldCompose() { pendingCompose.resume() }
function resumeHeldDraft() {
if (pendingDraftId === "" || !service) return
diff --git a/ui/compose/PendingCompose.qml b/ui/compose/PendingCompose.qml
new file mode 100644
index 0000000..9fb98b4
--- /dev/null
+++ b/ui/compose/PendingCompose.qml
@@ -0,0 +1,41 @@
+import QtQuick
+
+// A reply waits for the body, not merely the summary supplied by the list.
+QtObject {
+ required property var app
+ required property var composer
+ required property var assistant
+ required property var composeAssistant
+ readonly property var service: app.service
+ function detailReady() {
+ return !!service && !!service.selectedMessage && !service.detailLoading && service.detailPainted
+ }
+ function start(mode) {
+ if (!service) return
+ app.pendingDraftId = ""
+ var next = String(mode || "new")
+ if (next !== "new" && !detailReady()) {
+ app.pendingComposeMode = next
+ return
+ }
+ app.pendingComposeMode = ""
+ var keepAssistant = assistant.opened
+ var conversation = keepAssistant ? assistant.job : null
+ composer.begin(next, service.selectedMessage, service.selectedBody.text,
+ service.selectedAttachments)
+ if (keepAssistant) {
+ if ((next === "reply" || next === "replyAll") && conversation
+ && String(conversation.accountId) === composer.accountId
+ && String(conversation.messageId) === composer.replyMessageId)
+ composer.agentParentJobId = String(conversation.id)
+ composeAssistant.open()
+ }
+ }
+
+ function resume() {
+ if (app.pendingComposeMode === "" || !detailReady()) return
+ var mode = app.pendingComposeMode
+ app.pendingComposeMode = ""
+ start(mode)
+ }
+}
From 5db17740f99feb1252ba136db20d9fb67899cd91 Mon Sep 17 00:00:00 2001
From: Jason Lee
Date: Sun, 11 Oct 2026 20:11:10 +0800
Subject: [PATCH 21/88] chore: Publish v0.11.0 and repair Windows backend
runtime (#353)
Publish Omamail v0.11.0 from current main, including the merged
subject-copying and release-validation repairs. This release advances
the published backend to API 7, enabling sender names for IMAP and
Outlook accounts while retaining the fixed API gates in QML.
Stop the Windows persistent backend promptly when its response pipe
closes, including while stdin remains open. Give the Windows backend
entry thread an 8 MiB stack to avoid command and persistent-dispatch
stack overflows. Restore Windows OAuth admission and default MIME
boundary generation by using the same operating-system cryptographic
random provider already used by IMAP cursors. Correct the native test
fixtures for Windows filenames, absolute paths, UTF-8 Python transport,
and connection-refusal latency. Isolate Windows CLI integration children
from native user directories with a debug-only test feature; production
builds ignore that hint. Give synthetic storage its required owner-only
protected ACL and compare owner/DACL and timestamps in no-write
assertions. Hostile attachment display names and the assertions against
unwanted writes, sends, and credential-bearing requests remain covered.
Release CI builds the two static Linux backends and all three standalone
desktop packages from one source commit. It verifies native security
contracts, backend APIs, package installation and rollback, and smoke
tests before publishing the complete immutable asset set. It downloads
and verifies the public assets before committing `backend-version` and
the folded API metadata on this branch. Merge only after that pin commit
and the checks for its exact revision pass.
## Validation
Release source `70c295b` passed both static Linux backend jobs and the
complete macOS, Linux and Windows standalone jobs in
https://github.com/huacnlee/omamail/actions/runs/38136130747 (attempt
2). Native credential, private-file/IPC, process, network, QML, API,
installation/rollback and smoke checks completed before publication.
Windows passed 497 library tests, all 33 CLI tests and all three stdio
regressions.
The authoritative workflow published all ten immutable assets, verified
their public downloads, then committed only `backend-version` and the
folded API metadata as `88bdf6a`. The pin is now 0.11.0 and released API
7, with no unreleased API entries. Exact-pin PR checks are running
before merge. Local Linux CLI integration tests (33) and MIME parity
tests (9) passed; full local `make validate` is still running.
Security: PASS for the affected release boundaries on all three native
platform runners. Standalone archives retain the documented
unsigned/unnotarized distribution limitations.
## Release Notes
- Add a sender name for IMAP and Outlook mailboxes and support
selections across accounts in the unified view.
- Right-click a message's subject to copy it in full, including text
beginning with a dash.
- Fix Windows backend stack overflows, OAuth sign-in, and outgoing MIME
generation.
- Update the Omarchy backend and standalone desktop applications to
v0.11.0.
---------
Co-authored-by: Omamail Release <41898282+github-actions[bot]@users.noreply.github.com>
---
Cargo.lock | 2 +-
Cargo.toml | 2 +-
app/CMakeLists.txt | 2 +-
backend-api.json | 6 +-
backend-version | 2 +-
manifest.json | 2 +-
src/auth/callback.rs | 13 ++--
src/backend/mail_action_tests.rs | 7 +-
src/backend/stdio.rs | 60 +++++++++++++++--
src/calendar/discovery_runtime_tests.rs | 1 +
src/compose/tests.rs | 3 +-
src/main.rs | 16 +++++
src/message/compose.rs | 6 +-
src/platform/dirs.rs | 21 ++++++
src/providers/gmail_http_runtime_tests.rs | 7 +-
tests/cli.rs | 79 ++++++++++++++++++++---
tests/cli/search.rs | 6 +-
tests/platform_native.rs | 22 +++++++
18 files changed, 224 insertions(+), 33 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 815ba2c..8c4573b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1320,7 +1320,7 @@ dependencies = [
[[package]]
name = "omamail"
-version = "0.10.8"
+version = "0.11.0"
dependencies = [
"base64",
"chrono",
diff --git a/Cargo.toml b/Cargo.toml
index 47cf702..9aa7b1b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "omamail"
-version = "0.10.8"
+version = "0.11.0"
edition = "2024"
publish = false
diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt
index c1e3f40..a4695bc 100644
--- a/app/CMakeLists.txt
+++ b/app/CMakeLists.txt
@@ -1,6 +1,6 @@
cmake_minimum_required(VERSION 3.21)
-project(omamail-app VERSION 0.10.8 LANGUAGES CXX)
+project(omamail-app VERSION 0.11.0 LANGUAGES CXX)
if(WIN32)
enable_language(RC)
diff --git a/backend-api.json b/backend-api.json
index aa043c5..24bdb28 100644
--- a/backend-api.json
+++ b/backend-api.json
@@ -1,6 +1,6 @@
{
"apiVersion": 7,
- "releasedApiVersion": 6,
+ "releasedApiVersion": 7,
"protocolVersion": 1,
"methods": [
"system.info",
@@ -1291,8 +1291,6 @@
],
"unreleased": {
"methods": [],
- "cases": [
- "mail send dry run names the IMAP sender"
- ]
+ "cases": []
}
}
diff --git a/backend-version b/backend-version
index 1a46c7f..d9df1bb 100644
--- a/backend-version
+++ b/backend-version
@@ -1 +1 @@
-0.10.8
+0.11.0
diff --git a/manifest.json b/manifest.json
index a5434af..3746eff 100644
--- a/manifest.json
+++ b/manifest.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"id": "omamail",
"name": "Omamail",
- "version": "0.10.8",
+ "version": "0.11.0",
"author": "huacnlee",
"license": "MIT",
"homepage": "https://huacnlee.github.io/omamail/",
diff --git a/src/auth/callback.rs b/src/auth/callback.rs
index 42acd96..5cbee81 100644
--- a/src/auth/callback.rs
+++ b/src/auth/callback.rs
@@ -2,7 +2,7 @@
use super::*;
use base64::Engine;
use sha2::{Digest, Sha256};
-use std::{collections::HashMap, io::Read};
+use std::collections::HashMap;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
@@ -15,8 +15,9 @@ pub(super) struct Flows(Mutex Result {
let mut bytes = [0; 32];
- std::fs::File::open("/dev/urandom")
- .and_then(|mut f| f.read_exact(&mut bytes))
+ rustls::crypto::ring::default_provider()
+ .secure_random
+ .fill(&mut bytes)
.map_err(|_| "auth_random_failed")?;
Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes))
}
@@ -320,7 +321,7 @@ mod tests {
let address = listener.local_addr().unwrap();
assert!(!listener_closes(address, Duration::from_millis(60)).await);
drop(listener);
- assert!(listener_closes(address, Duration::from_secs(1)).await);
+ assert!(listener_closes(address, Duration::from_secs(5)).await);
}
#[tokio::test]
@@ -343,7 +344,9 @@ mod tests {
// connection refusal within a bound, not closure at one scheduling
// instant. The separate live-listener regression prevents this probe
// from treating a timeout or a successful connection as closure.
- assert!(listener_closes(address, Duration::from_secs(1)).await);
+ // Windows can take more than a second to report connection refusal;
+ // the probe still requires refusal, never a timeout or a successful connect.
+ assert!(listener_closes(address, Duration::from_secs(5)).await);
}
#[tokio::test]
diff --git a/src/backend/mail_action_tests.rs b/src/backend/mail_action_tests.rs
index a3218b5..af3c409 100644
--- a/src/backend/mail_action_tests.rs
+++ b/src/backend/mail_action_tests.rs
@@ -481,7 +481,12 @@ async fn production_jmap_send_preview_only_reads_identity_and_preserves_storage(
}
let fixture = account_fixture(json!({"version":1,"activeId":ACCOUNT,
"accounts":[{"provider":"jmap","email":"user@example.test"}]}));
- let attachment = fixture.root.join("quote\\工\".txt");
+ // Keep the hostile display name separate from a Windows-valid filename.
+ let attachment = fixture.root.join(if cfg!(windows) {
+ "attachment-工.txt"
+ } else {
+ "quote\\工\".txt"
+ });
fs::write(&attachment, b"synthetic attachment").unwrap();
fs::create_dir_all(fixture.state.join("omamail")).unwrap();
fs::write(fixture.state.join("omamail/outbox.json"), b"[]\n").unwrap();
diff --git a/src/backend/stdio.rs b/src/backend/stdio.rs
index 677b26f..ff91e21 100644
--- a/src/backend/stdio.rs
+++ b/src/backend/stdio.rs
@@ -55,10 +55,62 @@ impl Read for Input {
}
#[cfg(windows)]
{
- // Windows anonymous pipes do not support poll(2). A failed stdout
- // will be observed before the next request; otherwise the blocking
- // stdin read is exactly the backend protocol's required wait.
- return io::stdin().read(bytes);
+ use std::os::windows::io::AsRawHandle;
+ use windows_sys::Win32::{
+ Foundation::ERROR_BROKEN_PIPE,
+ Storage::FileSystem::{FILE_TYPE_PIPE, GetFileType, ReadFile},
+ System::Pipes::PeekNamedPipe,
+ };
+ let mut input = io::stdin();
+ let handle = input.as_raw_handle();
+ if unsafe { GetFileType(handle) } != FILE_TYPE_PIPE {
+ return input.read(bytes);
+ }
+ // We are the sole reader. Read only bytes already available so an
+ // open, idle stdin cannot conceal a failed response pipe forever.
+ loop {
+ if self.failed.load(Ordering::Acquire) {
+ return Err(io::Error::new(io::ErrorKind::BrokenPipe, "output closed"));
+ }
+ let mut available = 0;
+ if unsafe {
+ PeekNamedPipe(
+ handle,
+ std::ptr::null_mut(),
+ 0,
+ std::ptr::null_mut(),
+ &mut available,
+ std::ptr::null_mut(),
+ )
+ } == 0
+ {
+ let error = io::Error::last_os_error();
+ return if error.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
+ Ok(0)
+ } else {
+ Err(error)
+ };
+ }
+ if available == 0 {
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ continue;
+ }
+ let count = bytes.len().min(available as usize) as u32;
+ let mut read = 0;
+ if unsafe {
+ ReadFile(
+ handle,
+ bytes.as_mut_ptr(),
+ count,
+ &mut read,
+ std::ptr::null_mut(),
+ )
+ } == 0
+ {
+ return Err(io::Error::last_os_error());
+ }
+ return Ok(read as usize);
+ }
}
#[cfg(unix)]
loop {
diff --git a/src/calendar/discovery_runtime_tests.rs b/src/calendar/discovery_runtime_tests.rs
index 1ad1e1c..9521db1 100644
--- a/src/calendar/discovery_runtime_tests.rs
+++ b/src/calendar/discovery_runtime_tests.rs
@@ -24,6 +24,7 @@ impl reqwest::dns::Resolve for LoopbackDns {
impl Peer {
fn new() -> Self {
let mut process = Command::new("python3")
+ .env("PYTHONUTF8", "1")
.arg(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/calendar/discovery_tls_test.py"
diff --git a/src/compose/tests.rs b/src/compose/tests.rs
index 0454e28..fc06594 100644
--- a/src/compose/tests.rs
+++ b/src/compose/tests.rs
@@ -263,7 +263,8 @@ fn attachment_metadata_never_opens_paths_and_invalid_paths_write_nothing() {
}
#[test]
fn js_oracle_parity_for_normalized_drafts() {
- let fixtures = json!([saved("hello"),saved(" "),{"version":1,"active":true,"returnView":"calendar","draft":{"to":"a@example.org","draftAttachments":[{"path":"/tmp/synthetic","data":"discard","filename":"a","size":12}],"replyRecipients":[{"email":"a@example.org"}]},"parked":[{"subject":"parked","accountId":"other"},{}]}, {"version":1,"active":false}, {"version":2,"active":true}]);
+ let path = std::env::temp_dir().join("synthetic");
+ let fixtures = json!([saved("hello"),saved(" "),{"version":1,"active":true,"returnView":"calendar","draft":{"to":"a@example.org","draftAttachments":[{"path":path,"data":"discard","filename":"a","size":12}],"replyRecipients":[{"email":"a@example.org"}]},"parked":[{"subject":"parked","accountId":"other"},{}]}, {"version":1,"active":false}, {"version":2,"active":true}]);
let script = r#"const fs=require('fs'),vm=require('vm');const ctx={};vm.createContext(ctx);vm.runInContext(fs.readFileSync('ui/tests/oracles/Recovery.js','utf8').replace(/^\.pragma library\s*/,''),ctx);const fixtures=JSON.parse(fs.readFileSync(0,'utf8'));process.stdout.write(JSON.stringify(fixtures.map(v=>ctx.parse(JSON.stringify(v)))));"#;
use std::process::{Command, Stdio};
let mut child = Command::new("node")
diff --git a/src/main.rs b/src/main.rs
index d247d70..58f1fa9 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,19 @@
fn main() {
+ #[cfg(windows)]
+ {
+ // Windows reserves only 1 MiB for the executable's initial thread.
+ // The shared CLI/backend dispatch futures need the same stack budget
+ // as the Unix entry point, including in unoptimized native test builds.
+ let result = std::thread::Builder::new()
+ .name("omamail-main".into())
+ .stack_size(8 * 1024 * 1024)
+ .spawn(omamail::cli::run)
+ .expect("start backend entry thread")
+ .join();
+ if let Err(panic) = result {
+ std::panic::resume_unwind(panic);
+ }
+ }
+ #[cfg(not(windows))]
omamail::cli::run();
}
diff --git a/src/message/compose.rs b/src/message/compose.rs
index f557985..11b8307 100644
--- a/src/message/compose.rs
+++ b/src/message/compose.rs
@@ -8,7 +8,6 @@ use base64::{
};
use chrono::{DateTime, Datelike, Local};
use serde_json::{Value, json};
-use std::io::Read;
type Result = std::result::Result;
fn field<'a>(v: &'a Value, key: &str) -> &'a str {
v[key].as_str().unwrap_or("")
@@ -136,8 +135,9 @@ fn boundary(value: &str) -> Result {
return Ok(stated);
}
let mut random = [0; 16];
- std::fs::File::open("/dev/urandom")
- .and_then(|mut f| f.read_exact(&mut random))
+ rustls::crypto::ring::default_provider()
+ .secure_random
+ .fill(&mut random)
.map_err(|_| "random_unavailable")?;
Ok(format!("=_Omamail_{}", URL_SAFE_NO_PAD.encode(random)))
}
diff --git a/src/platform/dirs.rs b/src/platform/dirs.rs
index 24b8a44..bc0e75e 100644
--- a/src/platform/dirs.rs
+++ b/src/platform/dirs.rs
@@ -65,6 +65,13 @@ impl AppDirs {
{
return Ok(override_dirs.dirs);
}
+ #[cfg(all(windows, feature = "integration-test-credentials"))]
+ if let Some(root) = integration_root()? {
+ return Self::from_roots(
+ root.join("config"), root.join("cache"), root.join("state"),
+ root.join("runtime"), root.join("downloads"),
+ );
+ }
Self::discover_with(|name| std::env::var_os(name), &std::env::temp_dir())
}
pub fn home() -> Result {
@@ -76,6 +83,10 @@ impl AppDirs {
{
return Ok(override_dirs.home);
}
+ #[cfg(all(windows, feature = "integration-test-credentials"))]
+ if let Some(root) = integration_root()? {
+ return absolute(root.join("home"));
+ }
#[cfg(windows)]
{
return known_folder(&windows_sys::Win32::UI::Shell::FOLDERID_Profile);
@@ -173,6 +184,16 @@ impl AppDirs {
self.config.join(APP_DIRECTORY)
}
}
+// CLI integration children cannot use the unit-test in-memory override. This
+// is compiled only with the test credential feature, which is forbidden in
+// release builds by credentials/mod.rs. Production keeps native Known Folders.
+#[cfg(all(windows, feature = "integration-test-credentials"))]
+fn integration_root() -> Result
, &'static str> {
+ std::env::var_os("OMAMAIL_INTEGRATION_HOME")
+ .map(|root| absolute(PathBuf::from(root)))
+ .transpose()
+}
+
fn absolute(path: PathBuf) -> Result {
if !path.is_absolute()
|| path
diff --git a/src/providers/gmail_http_runtime_tests.rs b/src/providers/gmail_http_runtime_tests.rs
index 3cb0b64..fee5924 100644
--- a/src/providers/gmail_http_runtime_tests.rs
+++ b/src/providers/gmail_http_runtime_tests.rs
@@ -143,7 +143,12 @@ async fn mail_send_preview_reads_google_identity_without_mutation_or_local_write
std::fs::write(directory.join("sentinel"), b"unchanged existing state").unwrap();
}
std::fs::write(fixture.state.join("omamail/outbox.json"), b"[]\n").unwrap();
- let attachment = fixture.root.join("quote\\工\".txt");
+ // Keep the hostile display name separate from a Windows-valid filename.
+ let attachment = fixture.root.join(if cfg!(windows) {
+ "attachment-工.txt"
+ } else {
+ "quote\\工\".txt"
+ });
std::fs::write(&attachment, b"private attachment bytes").unwrap();
let before = fixture_tree(&fixture.root);
let body = json!({"access_token":"synthetic-access-token","expires_in":3600,
diff --git a/tests/cli.rs b/tests/cli.rs
index d70f087..71a3dc5 100644
--- a/tests/cli.rs
+++ b/tests/cli.rs
@@ -56,8 +56,10 @@ fn no_arguments_print_help_without_starting_a_gui() {
#[test]
fn serve_runs_the_persistent_backend() {
+ let fixture = mail_list_fixture(9, false);
let mut child = Command::new(env!("CARGO_BIN_EXE_omamail"))
.arg("serve")
+ .env("OMAMAIL_INTEGRATION_HOME", &fixture.0)
.env_remove("HOME")
.env_remove("XDG_CONFIG_HOME")
.env_remove("XDG_CACHE_HOME")
@@ -74,7 +76,7 @@ fn serve_runs_the_persistent_backend() {
.unwrap();
drop(child.stdin.take());
let output = child.wait_with_output().unwrap();
- assert!(output.status.success());
+ assert!(output.status.success(), "{output:?}");
assert!(output.stderr.is_empty());
let replies: Vec = output
.stdout
@@ -112,6 +114,7 @@ fn call_in_empty_home(method: &str, params: &[u8]) -> Output {
std::fs::create_dir_all(&home).unwrap();
let mut child = Command::new(env!("CARGO_BIN_EXE_omamail"))
.args(["call", method, "--json"])
+ .env("OMAMAIL_INTEGRATION_HOME", &home)
.env("XDG_CONFIG_HOME", &home)
.env("HOME", &home)
.stdin(Stdio::piped())
@@ -143,6 +146,13 @@ fn mail_list_fixture(imap_port: u16, keyring_succeeds: bool) -> MailListFixture
));
let config = config_root(&root).join("omamail");
fs::create_dir_all(&config).unwrap();
+ #[cfg(windows)]
+ {
+ // These synthetic ancestors are created by std::fs, so unlike the
+ // native private-directory creator they inherit the temp directory ACL.
+ set_mode(&root, 0o700);
+ set_mode(&config_root(&root), 0o700);
+ }
fs::write(
config.join("accounts.json"),
serde_json::json!({
@@ -220,6 +230,7 @@ fn assert_no_runtime_storage(root: &Path) {
fn call_mail_list(root: &Path, account: &str) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_omamail"))
.args(["call", "mail.list", "--json"])
+ .env("OMAMAIL_INTEGRATION_HOME", root)
.env("XDG_CONFIG_HOME", root.join("config"))
.env("HOME", root.join("home"))
.env("PATH", root.join("bin"))
@@ -253,6 +264,7 @@ fn call_mail_list(root: &Path, account: &str) -> Output {
fn call_mail_read(root: &Path, account: &str, id: &str) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_omamail"))
.args(["call", "mail.read", "--json"])
+ .env("OMAMAIL_INTEGRATION_HOME", root)
.env("XDG_CONFIG_HOME", root.join("config"))
.env("HOME", root.join("home"))
.env("PATH", root.join("bin"))
@@ -288,7 +300,21 @@ fn set_mode(path: &Path, mode: u32) {
fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap();
}
#[cfg(windows)]
-fn set_mode(_: &Path, _: u32) {}
+fn set_mode(path: &Path, _: u32) {
+ // Native private storage requires a protected DACL and this user's owner
+ // SID. A no-op Unix-mode stub does not make an inherited Windows file private.
+ let user = std::env::var("USERNAME").unwrap();
+ let grant = if path.is_dir() {
+ format!("{user}:(OI)(CI)F")
+ } else {
+ format!("{user}:F")
+ };
+ for arguments in [vec!["/setowner".to_owned(), user.clone()],
+ vec!["/inheritance:r".to_owned(), "/grant:r".to_owned(), grant]] {
+ let output = Command::new("icacls").arg(path).args(arguments).output().unwrap();
+ assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
+ }
+}
#[cfg(unix)]
fn metadata(path: &Path) -> (u64, (i64, i64), (i64, i64)) {
@@ -301,8 +327,26 @@ fn metadata(path: &Path) -> (u64, (i64, i64), (i64, i64)) {
}
#[cfg(windows)]
fn metadata(path: &Path) -> (u64, (i64, i64), (i64, i64)) {
+ use std::hash::{Hash, Hasher};
+ use std::os::windows::{ffi::OsStrExt, fs::MetadataExt};
+ use windows_sys::Win32::Security::{GetFileSecurityW, DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION};
let metadata = fs::metadata(path).unwrap();
- (metadata.len(), (0, 0), (0, 0))
+ let name: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect();
+ let flags = DACL_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION;
+ let mut needed = 0;
+ unsafe { GetFileSecurityW(name.as_ptr(), flags, std::ptr::null_mut(), 0, &mut needed) };
+ assert!(needed > 0);
+ let mut descriptor = vec![0u8; needed as usize];
+ assert_ne!(unsafe { GetFileSecurityW(name.as_ptr(), flags, descriptor.as_mut_ptr().cast(), needed, &mut needed) }, 0);
+ descriptor.truncate(needed as usize);
+ let mut hash = std::collections::hash_map::DefaultHasher::new();
+ descriptor.hash(&mut hash);
+ // Capture bytes separately in fixture_snapshot, and here preserve native
+ // timestamps, attributes, owner and DACL: a same-size write or permission
+ // repair must not pass a read-only regression merely because length stayed put.
+ (metadata.len(),
+ (metadata.last_write_time() as i64, metadata.creation_time() as i64),
+ (metadata.file_attributes() as i64, hash.finish() as i64))
}
type FixtureSnapshot = Vec<(
@@ -406,7 +450,11 @@ async fn malformed_final_imap_action_id_prevents_all_network_and_cache_changes()
let mut mutations = 0;
loop {
let mut line = String::new();
- if reader.read_line(&mut line).await.unwrap() == 0 {
+ if match reader.read_line(&mut line).await {
+ Ok(n) => n == 0,
+ Err(error) if error.kind() == std::io::ErrorKind::ConnectionReset => true,
+ Err(error) => panic!("synthetic IMAP read failed: {error}"),
+ } {
break;
}
let response = if line.starts_with("O1 LOGIN ") {
@@ -779,6 +827,7 @@ fn pretty_call_errors_go_to_stderr() {
fn root_mail(root: &Path, args: &[&str], body: &[u8]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_omamail"))
.args(args)
+ .env("OMAMAIL_INTEGRATION_HOME", root)
.env("XDG_CONFIG_HOME", root.join("config"))
.env("XDG_CACHE_HOME", root.join("cache"))
.env("XDG_STATE_HOME", root.join("state"))
@@ -952,7 +1001,11 @@ fn root_mail_errors_use_stable_envelopes_and_never_fall_back_accounts() {
#[test]
fn send_previews_repeatable_inputs_and_strict_bounded_utf8_without_writes() {
let fixture = mail_list_fixture(9, false);
- let attachment = fixture.0.join("quoted\\工\".txt");
+ let attachment = fixture.0.join(if cfg!(windows) {
+ "attachment-工.txt"
+ } else {
+ "quoted\\工\".txt"
+ });
fs::write(&attachment, b"private attachment").unwrap();
let second = fixture.0.join("second.txt");
fs::write(&second, b"two").unwrap();
@@ -984,7 +1037,7 @@ fn send_previews_repeatable_inputs_and_strict_bounded_utf8_without_writes() {
serde_json::json!({"ok":true,"result":{
"dryRun":true,"executed":false,"accountId":"imap:imap@example.org","from":"imap@example.org",
"to":["one@example.org","two@example.org"],"cc":["three@example.org"],"bcc":["four@example.org"],
- "subject":"Unicode 工","body":body,"attachments":[{"name":"quoted\\工\".txt","size":18},{"name":"second.txt","size":3}]
+ "subject":"Unicode 工","body":body,"attachments":[{"name":attachment.file_name().unwrap().to_str().unwrap(),"size":18},{"name":"second.txt","size":3}]
}})
);
for body in [
@@ -1072,6 +1125,7 @@ fn only_send_consumes_stdin_and_human_previews_escape_untrusted_text() {
] {
let mut child = Command::new(env!("CARGO_BIN_EXE_omamail"))
.args(args)
+ .env("OMAMAIL_INTEGRATION_HOME", &fixture.0)
.env("XDG_CONFIG_HOME", fixture.0.join("config"))
.env("HOME", fixture.0.join("home"))
.env("PATH", fixture.0.join("bin"))
@@ -1181,6 +1235,7 @@ async fn real_smtp_send(generic: bool, acknowledge: bool, owner: bool, crash: bo
let mut desktop = if owner {
let mut child = tokio::process::Command::new(env!("CARGO_BIN_EXE_omamail"))
.arg("serve")
+ .env("OMAMAIL_INTEGRATION_HOME", &fixture.0)
.env("XDG_CONFIG_HOME", fixture.0.join("config"))
.env("XDG_STATE_HOME", fixture.0.join("state"))
.env("XDG_CACHE_HOME", fixture.0.join("cache"))
@@ -1455,7 +1510,11 @@ async fn imap_action_preview_requires_discovered_destinations_and_execution_uses
let mut moves = 0;
loop {
let mut line = String::new();
- if reader.read_line(&mut line).await.unwrap() == 0 {
+ if match reader.read_line(&mut line).await {
+ Ok(n) => n == 0,
+ Err(error) if error.kind() == std::io::ErrorKind::ConnectionReset => true,
+ Err(error) => panic!("synthetic IMAP read failed: {error}"),
+ } {
break;
}
let response = if line.starts_with("O1 LOGIN ") {
@@ -1573,7 +1632,11 @@ async fn imap_archive_keeps_confirmed_folder_results_when_later_select_refuses()
let mut commands = Vec::new();
loop {
let mut line = String::new();
- if reader.read_line(&mut line).await.unwrap() == 0 {
+ if match reader.read_line(&mut line).await {
+ Ok(n) => n == 0,
+ Err(error) if error.kind() == std::io::ErrorKind::ConnectionReset => true,
+ Err(error) => panic!("synthetic IMAP read failed: {error}"),
+ } {
break;
}
let response = if line.starts_with("O1 LOGIN ") {
diff --git a/tests/cli/search.rs b/tests/cli/search.rs
index 4bb021e..76a0e86 100644
--- a/tests/cli/search.rs
+++ b/tests/cli/search.rs
@@ -23,7 +23,11 @@ async fn search_pages_survive_process_exit_and_deletion_of_the_cursor_message()
};
loop {
let mut cmd = String::new();
- if reader.read_line(&mut cmd).await.unwrap() == 0 {
+ if match reader.read_line(&mut cmd).await {
+ Ok(n) => n == 0,
+ Err(error) if error.kind() == std::io::ErrorKind::ConnectionReset => true,
+ Err(error) => panic!("synthetic IMAP read failed: {error}"),
+ } {
break;
}
let mut data = String::new();
diff --git a/tests/platform_native.rs b/tests/platform_native.rs
index f6e1888..61c51f9 100644
--- a/tests/platform_native.rs
+++ b/tests/platform_native.rs
@@ -44,3 +44,25 @@ fn windows_process_command_line_query_reads_live_child_arguments() {
"queried command line omitted the child marker"
);
}
+
+#[cfg(all(windows, not(feature = "integration-test-credentials")))]
+#[test]
+fn production_directories_ignore_integration_root_hint_without_writes() {
+ use omamail::platform::dirs::AppDirs;
+ let root = std::env::temp_dir().canonicalize().unwrap()
+ .join(format!("omamail-forbidden-integration-root-{}", std::process::id()));
+ if std::env::var_os("OMAMAIL_DIRECTORY_PROBE_CHILD").is_some() {
+ let hint = std::path::PathBuf::from(std::env::var_os("OMAMAIL_INTEGRATION_HOME").unwrap());
+ assert!(!AppDirs::discover().unwrap().config.starts_with(&hint));
+ assert!(!AppDirs::home().unwrap().starts_with(&hint));
+ assert!(!hint.exists(), "the production directory lookup must not write to the hint");
+ return;
+ }
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", "production_directories_ignore_integration_root_hint_without_writes"])
+ .env("OMAMAIL_DIRECTORY_PROBE_CHILD", "1")
+ .env("OMAMAIL_INTEGRATION_HOME", &root)
+ .output().unwrap();
+ assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr));
+ assert!(!root.exists());
+}
From 3848414224923ba67276b31fe9b620d223b9dfe5 Mon Sep 17 00:00:00 2001
From: Chris Gray <216301595+latentoperator@users.noreply.github.com>
Date: Sun, 11 Oct 2026 18:41:37 -0500
Subject: [PATCH 22/88] Remove personal dictionary storage and keep
session-only spelling ignore
---
Makefile | 2 +-
README.md | 2 +-
app/qml/StandaloneShell.qml | 2 +-
app/tests/qml/tst_standalone_composition.qml | 7 --
docs/KEYS.md | 2 +-
scripts/config-store.sh | 4 +-
tests/test_config_store.sh | 13 ---
ui/Service.qml | 7 +-
ui/components/ComposeView.qml | 12 --
ui/components/SettingsPage.qml | 19 +--
ui/components/TextMenu.qml | 10 +-
ui/compose/PersonalWords.qml | 85 --------------
ui/compose/SpellcheckAdapter.qml | 14 ---
ui/compose/Spelling.js | 22 ----
ui/compose/SpellingState.qml | 6 -
ui/tests/qml/tst_service_settings.qml | 117 -------------------
ui/tests/qml/tst_spellcheck_adapter.qml | 6 +-
ui/tests/qml/tst_spellcheck_composer.qml | 48 --------
ui/tests/qml/tst_spellcheck_menu.qml | 15 +--
ui/tests/test_spelling.js | 12 --
20 files changed, 16 insertions(+), 389 deletions(-)
delete mode 100644 ui/compose/PersonalWords.qml
diff --git a/Makefile b/Makefile
index 4116c50..43c1b94 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/PendingCompose.qml \
- ui/compose/SpellcheckAdapter.qml ui/compose/PersonalWords.qml ui/compose/SpellingState.qml \
+ ui/compose/SpellcheckAdapter.qml ui/compose/SpellingState.qml \
ui/tests/compatibility/tst_published_agent.qml \
ui/tests/qml/tst_unified_batch.qml ui/tests/qml/tst_clipboard_arguments.qml \
ui/tests/qml/tst_reader_subject_menu.qml \
diff --git a/README.md b/README.md
index bab0f61..4d32c5c 100644
--- a/README.md
+++ b/README.md
@@ -44,7 +44,7 @@ Each installer verifies the release package before replacing an existing version
Composer body spellchecking uses KDE Sonnet and a local Hunspell dictionary. On Arch, install `sonnet` and `hunspell-en_us`. On Debian and Ubuntu releases that provide Qt 6 Sonnet, install `qml6-module-org-kde-sonnet`, `sonnet6-plugins`, and `hunspell-en-us`. Restart Omamail after installing a dictionary.
-Spelling checks default to US English and can be turned off in Settings. Without the Sonnet QML module or the selected dictionary, composing remains available and Settings explains what is missing. Omamail does not install system packages. Personal words are saved in Omamail's own `spelling.json`; Add to dictionary does not change a global Hunspell dictionary.
+Spelling checks default to US English and can be turned off in Settings. Without the Sonnet QML module or the selected dictionary, composing remains available and Settings explains what is missing. Omamail does not install system packages. Ignore for this session stays in memory; there is no personal dictionary yet.
## Run from source
diff --git a/app/qml/StandaloneShell.qml b/app/qml/StandaloneShell.qml
index 888f461..f3c32f3 100644
--- a/app/qml/StandaloneShell.qml
+++ b/app/qml/StandaloneShell.qml
@@ -85,7 +85,7 @@ QtObject {
}
function writeConfig(name, text, callback) {
- var allowed = ["credentials.json", "window.json", "window-size.json", "calendars.json", "spelling.json"]
+ var allowed = ["credentials.json", "window.json", "window-size.json", "calendars.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/tests/qml/tst_standalone_composition.qml b/app/tests/qml/tst_standalone_composition.qml
index 199ecc3..a8d4ce2 100644
--- a/app/tests/qml/tst_standalone_composition.qml
+++ b/app/tests/qml/tst_standalone_composition.qml
@@ -660,13 +660,6 @@ 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/docs/KEYS.md b/docs/KEYS.md
index adb6470..c791a5a 100644
--- a/docs/KEYS.md
+++ b/docs/KEYS.md
@@ -47,7 +47,7 @@ readonly property string keyContext:
| `page` | Setup or settings | `Escape`, and the modified keys |
| `calendar` | The calendar month | Calendar navigation and the modified keys |
-`Ctrl+.` opens spelling suggestions for the word at the caret when the composer body has focus. Right-click a word for the same corrections, Ignore for this session, and Add to dictionary. Fcitx5 commonly uses `Ctrl+.` to toggle punctuation width and may consume it before Omamail receives it; use right-click or change the input method binding in that case. There is no application menu-key or `Shift+F10` binding.
+`Ctrl+.` opens spelling suggestions for the word at the caret when the composer body has focus. Right-click a word for the same corrections and Ignore for this session. Fcitx5 commonly uses `Ctrl+.` to toggle punctuation width and may consume it before Omamail receives it; use right-click or change the input method binding in that case. There is no application menu-key or `Shift+F10` binding.
`Ctrl+,` opens Settings from every context, including a focused draft field.
Back returns to the previous screen with the draft intact.
diff --git a/scripts/config-store.sh b/scripts/config-store.sh
index 8235566..4ae64f9 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|spelling.json) ;;
+ credentials.json|accounts.json|window.json|calendars.json|compose.json) ;;
*)
- printf '%s\n' 'usage: config-store.sh credentials.json|accounts.json|window.json|calendars.json|compose.json|spelling.json' >&2
+ printf '%s\n' 'usage: config-store.sh credentials.json|accounts.json|window.json|calendars.json|compose.json' >&2
exit 2
;;
esac
diff --git a/tests/test_config_store.sh b/tests/test_config_store.sh
index 708fb37..d80cbe1 100755
--- a/tests/test_config_store.sh
+++ b/tests/test_config_store.sh
@@ -56,19 +56,6 @@ 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/Service.qml b/ui/Service.qml
index 33d3fdc..7e0ae38 100644
--- a/ui/Service.qml
+++ b/ui/Service.qml
@@ -488,7 +488,7 @@ Item {
}
function writeConfig(name, text, callback) {
- var allowed = ["credentials.json", "window.json", "calendars.json", "spelling.json"]
+ var allowed = ["credentials.json", "window.json", "calendars.json"]
if (allowed.indexOf(String(name || "")) < 0) {
if (typeof callback === "function") callback(false, "Invalid configuration file")
return false
@@ -696,13 +696,8 @@ Item {
readonly property alias spellingLanguage: spelling.language
readonly property alias spellingAvailable: spelling.available
readonly property alias spellingStatus: spelling.status
- readonly property alias spellingWordStore: spelling.wordStore
- readonly property alias spellingPersonalWords: spelling.words
- readonly property alias spellingPersonalWordsError: spelling.error
function setSpellingEnabled(value) { persistSetting("spellingEnabled", value !== false) }
function setSpellingLanguage(value) { persistSetting("spellingLanguage", String(value || "en_US")) }
- function addPersonalWord(word) { spelling.wordStore.add(word) }
- function removePersonalWord(word) { spelling.wordStore.remove(word) }
// ---------------------------------------------------------- the accounts
diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml
index 36b5345..715798e 100644
--- a/ui/components/ComposeView.qml
+++ b/ui/components/ComposeView.qml
@@ -45,7 +45,6 @@ DropArea {
// that instantiate it bare. A caller may still assign over the binding.
property bool spellingEnabled: Spelling.decodeSettings(service ? { spellingEnabled: service.spellingEnabled } : null).enabled
property string spellingLanguage: Spelling.decodeSettings(service ? { spellingLanguage: service.spellingLanguage } : null).language
- 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.
property int bodyRevision: 0
@@ -140,12 +139,6 @@ DropArea {
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.
@@ -2077,7 +2070,6 @@ DropArea {
if (!item) return
item.document = bodyEdit.textDocument
item.enabled = root.spellingEnabled
- item.personalWords = root.spellingPersonalWords
root.refreshSpellingRanges()
}
}
@@ -2314,9 +2306,5 @@ DropArea {
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 79087b8..84bdaf9 100644
--- a/ui/components/SettingsPage.qml
+++ b/ui/components/SettingsPage.qml
@@ -859,8 +859,8 @@ Column {
Text {
width: parent.width
- text: "Underline misspelled words in the message body with corrections, "
- + "Ignore, and Add to dictionary. Uses the local Hunspell engine; "
+ text: "Underline misspelled words in the message body with corrections "
+ + "and Ignore for this session. Uses the local Hunspell engine; "
+ "nothing is sent anywhere."
color: root.dimColor
font.family: root.panelFontFamily
@@ -889,21 +889,6 @@ Column {
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 37cd828..d7b3c0c 100644
--- a/ui/components/TextMenu.qml
+++ b/ui/components/TextMenu.qml
@@ -45,7 +45,7 @@ Item {
readonly property bool hasSelection: !!target && String(target.selectedText || "") !== ""
readonly property var menuRows: [
suggestion0, suggestion1, suggestion2, suggestion3, suggestion4,
- ignoreRow, addRow, cutRow, copyRow, pasteRow, selectAllRow, openLinkRow, copyLinkRow
+ ignoreRow, cutRow, copyRow, pasteRow, selectAllRow, openLinkRow, copyLinkRow
]
readonly property alias cutRow: cutRow
@@ -55,7 +55,6 @@ Item {
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
@@ -64,7 +63,6 @@ Item {
signal openLinkRequested(string url)
signal spellingCorrect(string replacement)
signal spellingIgnore(string word)
- signal spellingAddToDictionary(string word)
anchors.fill: parent
z: 50
@@ -201,12 +199,6 @@ Item {
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
diff --git a/ui/compose/PersonalWords.qml b/ui/compose/PersonalWords.qml
deleted file mode 100644
index f7fafac..0000000
--- a/ui/compose/PersonalWords.qml
+++ /dev/null
@@ -1,85 +0,0 @@
-import QtQuick
-import Quickshell.Io
-import "Spelling.js" as Spelling
-
-// 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: ""
-
- // Replace the list. The file load uses `merge` below; this is the explicit
- // reset form and what the tests drive.
- function apply(raw) {
- words = Spelling.normalizePersonalWords(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) {
- words = Spelling.mergePersonalWords(words, raw)
- 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
index 39b9118..7998782 100644
--- a/ui/compose/SpellcheckAdapter.qml
+++ b/ui/compose/SpellcheckAdapter.qml
@@ -27,10 +27,6 @@ Item {
// 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`.
//
@@ -56,7 +52,6 @@ Item {
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.
@@ -106,15 +101,6 @@ Item {
// 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()
}
diff --git a/ui/compose/Spelling.js b/ui/compose/Spelling.js
index 7eb1842..ab7755a 100644
--- a/ui/compose/Spelling.js
+++ b/ui/compose/Spelling.js
@@ -35,28 +35,6 @@ function isWordChar(character) {
function isApostrophe(character) { return character === "'" || character === "\u2019" }
-function normalizePersonalWords(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
-}
-
-function mergePersonalWords(current, raw) {
- var onDisk = normalizePersonalWords(raw)
- var next = current.slice()
- for (var i = 0; i < onDisk.length; i++) {
- if (next.indexOf(onDisk[i]) < 0) next.push(onDisk[i])
- }
- return next
-}
-
function decodeSettings(settings) {
var values = settings || ({})
return {
diff --git a/ui/compose/SpellingState.qml b/ui/compose/SpellingState.qml
index d617812..1862353 100644
--- a/ui/compose/SpellingState.qml
+++ b/ui/compose/SpellingState.qml
@@ -14,12 +14,6 @@ Item {
&& probe.item !== null && probe.item.available
readonly property string status: probe.status === Loader.Error
? "no-module" : (probe.item ? probe.item.status : "loading")
- readonly property alias wordStore: personalWords
- readonly property alias words: personalWords.words
- readonly property alias error: personalWords.error
-
- PersonalWords { id: personalWords; service: root.service }
-
// Sonnet enumerates dictionaries once per process. Installing one requires
// restarting Omamail; a new adapter alone cannot discover it.
Loader { id: probe; source: "SpellcheckAdapter.qml" }
diff --git a/ui/tests/qml/tst_service_settings.qml b/ui/tests/qml/tst_service_settings.qml
index 696ab29..2c8510e 100644
--- a/ui/tests/qml/tst_service_settings.qml
+++ b/ui/tests/qml/tst_service_settings.qml
@@ -19,32 +19,9 @@ 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" })
}
@@ -57,14 +34,6 @@ 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,
@@ -210,92 +179,6 @@ Item {
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() {
diff --git a/ui/tests/qml/tst_spellcheck_adapter.qml b/ui/tests/qml/tst_spellcheck_adapter.qml
index 52dfa56..4b80a14 100644
--- a/ui/tests/qml/tst_spellcheck_adapter.qml
+++ b/ui/tests/qml/tst_spellcheck_adapter.qml
@@ -117,7 +117,7 @@ Item {
compare(ranges[0].end, 11)
}
- function test_personal_words_are_treated_as_correct() {
+ function test_session_ignore_treats_a_word_as_correct() {
var a = adapter()
if (!a) return
// A word unique to this test: ignore is process-global and irreversible,
@@ -125,9 +125,9 @@ Item {
// order.
edit.text = "zqxjw zqxjw"
compare(a.inspect(0).misspelled, true)
- a.personalWords = ["zqxjw"]
+ a.ignoreForSession("zqxjw")
compare(a.inspect(0).misspelled, false)
- // Applying personal words never disables the checker for other words.
+ // Ignoring 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
index 5d88f82..3c969b2 100644
--- a/ui/tests/qml/tst_spellcheck_composer.qml
+++ b/ui/tests/qml/tst_spellcheck_composer.qml
@@ -23,18 +23,12 @@ 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.KeyRouter {
@@ -50,7 +44,6 @@ Item {
onKeyPressed: function(event) { keyRouter.routeKeyEvent(event) }
anchors.fill: parent
service: mailService
- spellingPersonalWords: mailService.spellingPersonalWords
textColor: Qt.rgba(1, 1, 1, 1)
errorColor: Qt.rgba(1, 1, 1, 1)
backgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1)
@@ -125,30 +118,6 @@ Item {
}
}
- function test_personal_words_preserve_focused_draft_selection_and_undo() {
- var body = named(compose, "compose-body-editor")
- tryVerify(function() { return compose.spellingAdapter !== null || 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)
@@ -216,23 +185,6 @@ Item {
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)
diff --git a/ui/tests/qml/tst_spellcheck_menu.qml b/ui/tests/qml/tst_spellcheck_menu.qml
index 08dba3e..dd7f3d3 100644
--- a/ui/tests/qml/tst_spellcheck_menu.qml
+++ b/ui/tests/qml/tst_spellcheck_menu.qml
@@ -3,7 +3,7 @@ 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
+// it targets, the correction/ignore 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.
@@ -24,18 +24,12 @@ 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.KeyRouter {
@@ -51,7 +45,6 @@ Item {
onKeyPressed: function(event) { keyRouter.routeKeyEvent(event) }
anchors.fill: parent
service: mailService
- spellingPersonalWords: mailService.spellingPersonalWords
textColor: Qt.rgba(1, 1, 1, 1)
errorColor: Qt.rgba(1, 1, 1, 1)
backgroundColor: Qt.rgba(0.06, 0.06, 0.06, 1)
@@ -203,7 +196,7 @@ Item {
compare(editor.text.indexOf("wrod"), before.indexOf("wrod"))
}
- function test_no_suggestions_offers_ignore_and_add_but_no_rows() {
+ function test_no_suggestions_offers_ignore_but_no_rows() {
var editor = body()
editor.text = "a zxqjklv here "
wait(250)
@@ -213,7 +206,6 @@ Item {
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)
@@ -233,7 +225,7 @@ Item {
compare(editor.text, "a " + suggestion + " here")
}
- function test_keyboard_opens_ignore_and_add_without_suggestions() {
+ function test_keyboard_opens_ignore_without_suggestions() {
var editor = body()
editor.text = "the zxqjklv here "
editor.cursorPosition = 8
@@ -243,7 +235,6 @@ Item {
tryCompare(menu(), "opened", true)
compare(menu().spellingMisspelled, true)
verify(menu().ignoreWordRow.visible)
- verify(menu().addToDictionaryRow.visible)
menu().close()
}
diff --git a/ui/tests/test_spelling.js b/ui/tests/test_spelling.js
index ab0b666..99ee7f1 100644
--- a/ui/tests/test_spelling.js
+++ b/ui/tests/test_spelling.js
@@ -29,18 +29,6 @@ test("Ranges keep UTF-16 offsets, apostrophes, combining marks and repeated word
deepEqual(rules.misspelledRanges("'' ’ 😀 ", wrong), [])
})
-test("Personal words reject malformed data and merge late disk reads with session additions", () => {
- const rules = spelling()
- for (const raw of ["", "{", "null", "[]", '{"words":{}}']) {
- deepEqual(rules.normalizePersonalWords(raw), [])
- }
- deepEqual(rules.normalizePersonalWords('{"words":["a","b","a","",42,null,{},"café"]}'), ["a", "b", "café"])
- const current = ["session", "shared"]
- deepEqual(rules.mergePersonalWords(current, '{"words":["disk","shared","disk"]}'), ["session", "shared", "disk"])
- assert.deepEqual(current, ["session", "shared"], "a merge does not mutate the session snapshot")
- deepEqual(rules.mergePersonalWords(current, "invalid"), current)
-})
-
test("Settings default to enabled en_US and only explicit false disables checking", () => {
const rules = spelling()
for (const settings of [null, {}, { spellingEnabled: "no" }, { spellingEnabled: 0 }]) {
From 62eea313b4bad647a0b8f496a5bc56b291540351 Mon Sep 17 00:00:00 2001
From: Chris Gray <216301595+latentoperator@users.noreply.github.com>
Date: Sun, 11 Oct 2026 18:43:00 -0500
Subject: [PATCH 23/88] Fix spelling language resolution with validated
system-locale defaults
---
README.md | 4 ++--
manifest.json | 10 +++++-----
ui/Service.qml | 2 +-
ui/components/ComposeView.qml | 3 ++-
ui/components/SettingsPage.qml | 21 ++++++++++++++++++---
ui/compose/SpellcheckAdapter.qml | 9 +++++----
ui/compose/Spelling.js | 17 +++++++++++++++--
ui/compose/SpellingState.qml | 3 ++-
ui/settings/Settings.js | 2 +-
ui/tests/qml/tst_service_settings.qml | 13 ++++++++++++-
ui/tests/qml/tst_spellcheck_composer.qml | 2 +-
ui/tests/qml/tst_spellcheck_menu.qml | 1 +
ui/tests/test_settings.js | 2 +-
ui/tests/test_spelling.js | 22 +++++++++++++++++++---
14 files changed, 85 insertions(+), 26 deletions(-)
diff --git a/README.md b/README.md
index 4d32c5c..5249ef0 100644
--- a/README.md
+++ b/README.md
@@ -42,9 +42,9 @@ Each installer verifies the release package before replacing an existing version
### Optional spelling support
-Composer body spellchecking uses KDE Sonnet and a local Hunspell dictionary. On Arch, install `sonnet` and `hunspell-en_us`. On Debian and Ubuntu releases that provide Qt 6 Sonnet, install `qml6-module-org-kde-sonnet`, `sonnet6-plugins`, and `hunspell-en-us`. Restart Omamail after installing a dictionary.
+Composer body spellchecking uses KDE Sonnet and a local Hunspell dictionary. On Arch, install `sonnet` and the matching `hunspell-` package, such as `hunspell-en_us` or `hunspell-de`. On Debian and Ubuntu releases that provide Qt 6 Sonnet, install `qml6-module-org-kde-sonnet`, `sonnet6-plugins`, and the matching dictionary, such as `hunspell-en-us`. Restart Omamail after installing a dictionary.
-Spelling checks default to US English and can be turned off in Settings. Without the Sonnet QML module or the selected dictionary, composing remains available and Settings explains what is missing. Omamail does not install system packages. Ignore for this session stays in memory; there is no personal dictionary yet.
+Only the message body is checked, not the subject. Spelling uses the system language by default (`Qt.locale().name`, for example `en_US` or `de_DE`) and can be turned off in Settings. The advanced `spellingLanguage` setting is empty for system language, or an installed dictionary code to override it; malformed values are treated as system language and never passed to Sonnet. There is no silent fallback to English: without the Sonnet QML module or the requested dictionary, composing remains available and Settings names what is missing. Omamail does not install system packages. Checks and corrections stay local; nothing leaves the machine. Ignore for this session stays in memory; there is no personal dictionary yet.
## Run from source
diff --git a/manifest.json b/manifest.json
index 24b8079..334d160 100644
--- a/manifest.json
+++ b/manifest.json
@@ -51,7 +51,7 @@
"openOnClick": "Window",
"showBarIcon": true,
"spellingEnabled": true,
- "spellingLanguage": "en_US",
+ "spellingLanguage": "",
"suggestEvents": false,
"aiAgent": "System default",
"aiModel": ""
@@ -206,14 +206,14 @@
"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."
+ "description": "Underline misspelled body words with corrections and Ignore for this session. Uses local dictionaries; 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."
+ "label": "Spelling dictionary language override",
+ "defaultValue": "",
+ "description": "Empty uses the system language. Advanced override: an installed Hunspell dictionary code such as en_US or de_DE. No fallback dictionary is used."
}
]
}
diff --git a/ui/Service.qml b/ui/Service.qml
index 7e0ae38..6d3b871 100644
--- a/ui/Service.qml
+++ b/ui/Service.qml
@@ -697,7 +697,7 @@ Item {
readonly property alias spellingAvailable: spelling.available
readonly property alias spellingStatus: spelling.status
function setSpellingEnabled(value) { persistSetting("spellingEnabled", value !== false) }
- function setSpellingLanguage(value) { persistSetting("spellingLanguage", String(value || "en_US")) }
+ function setSpellingLanguage(value) { persistSetting("spellingLanguage", String(value || "")) }
// ---------------------------------------------------------- the accounts
diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml
index 715798e..1a7d52f 100644
--- a/ui/components/ComposeView.qml
+++ b/ui/components/ComposeView.qml
@@ -44,7 +44,8 @@ DropArea {
// one is wired, and falls back to the defaults for the tests
// that instantiate it bare. A caller may still assign over the binding.
property bool spellingEnabled: Spelling.decodeSettings(service ? { spellingEnabled: service.spellingEnabled } : null).enabled
- property string spellingLanguage: Spelling.decodeSettings(service ? { spellingLanguage: service.spellingLanguage } : null).language
+ property string spellingLanguage: Spelling.resolveLanguage(
+ service ? service.spellingLanguage : "", Qt.locale().name)
// Bumped on every body change so a menu opened before an edit can tell that
// the text under its saved position moved.
property int bodyRevision: 0
diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml
index 84bdaf9..ebbf1e1 100644
--- a/ui/components/SettingsPage.qml
+++ b/ui/components/SettingsPage.qml
@@ -4,6 +4,7 @@ import qs.Commons
import qs.Ui
import "../message/Direction.js" as Direction
import "../settings/Appearance.js" as Appearance
+import "../compose/Spelling.js" as Spelling
import "../message/Html.js" as Html
import "../account/Accounts.js" as Accounts
@@ -869,8 +870,22 @@ Column {
textFormat: Text.PlainText
}
+ Text {
+ objectName: "spellingLanguagePolicy"
+ width: parent.width
+ text: "Checking spelling in "
+ + Spelling.resolveLanguage(root.service ? root.service.spellingLanguage : "", Qt.locale().name)
+ + (root.service && Spelling.decodeSettings(root.service.settings).language !== ""
+ ? " (set in settings)." : " (system language).")
+ 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.
+ // a machine without Sonnet or its language dictionary still composes.
// Sonnet lists installed dictionaries once per process, so a dictionary
// installed while Omamail runs is only found after a restart.
Text {
@@ -879,9 +894,9 @@ Column {
visible: !!root.service && !root.service.spellingAvailable
text: root.service && root.service.spellingStatus === "no-module"
? "Spell-checking is unavailable: install the Sonnet QML module, then restart Omamail."
- : "The " + (root.service ? root.service.spellingLanguage : "en_US")
+ : "The " + Spelling.resolveLanguage(root.service ? root.service.spellingLanguage : "", Qt.locale().name)
+ " dictionary is not installed. Install the matching Hunspell "
- + "dictionary package (for example hunspell-en_us), then restart Omamail."
+ + "dictionary package (hunspell-, for example hunspell-de), then restart Omamail."
color: root.accentColor
font.family: root.panelFontFamily
font.pixelSize: Style.font.caption
diff --git a/ui/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml
index 7998782..b54e6c4 100644
--- a/ui/compose/SpellcheckAdapter.qml
+++ b/ui/compose/SpellcheckAdapter.qml
@@ -26,7 +26,8 @@ Item {
// 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"
+ property string language: ""
+ readonly property string resolvedLanguage: Spelling.resolveLanguage(language, Qt.locale().name)
// Availability is about the *requested* language, and it is computed after
// `setCurrentLanguage` rather than bound to `spellCheckerFound`.
//
@@ -51,7 +52,7 @@ Item {
}
Component.onDestruction: Session.unsubscribe(adapter)
onEnabledChanged: applySettings()
- onLanguageChanged: applySettings()
+ onResolvedLanguageChanged: applySettings()
// Returns { word, misspelled, suggestions }. Call this for the position of a
// click or the caret; it also primes applyCorrection for the same position.
@@ -96,11 +97,11 @@ Item {
// 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)
+ if (resolvedLanguage !== "") highlighter.setCurrentLanguage(resolvedLanguage)
// 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
+ && resolvedLanguage !== "" && highlighter.currentLanguage === resolvedLanguage
Session.changed()
}
diff --git a/ui/compose/Spelling.js b/ui/compose/Spelling.js
index ab7755a..069643d 100644
--- a/ui/compose/Spelling.js
+++ b/ui/compose/Spelling.js
@@ -1,6 +1,6 @@
.pragma library
-// Spelling presentation rules, shared by the optional adapter and its stores.
+// Spelling presentation rules shared by the composer and optional adapter.
// Positions are UTF-16 offsets, matching Qt's text document API.
function misspelledRanges(text, isMisspelled) {
var ranges = []
@@ -35,11 +35,24 @@ function isWordChar(character) {
function isApostrophe(character) { return character === "'" || character === "\u2019" }
+// Persisted dictionary names are untrusted. Do not trim: trailing controls
+// and whitespace must be rejected before a value can reach Sonnet.
+function validLanguage(value) {
+ return typeof value === "string" && value.length <= 24
+ && /^[A-Za-z]{2,3}([_-][A-Za-z0-9]{2,8}){0,2}$/.test(value)
+ && !/[\r\n]/.test(value)
+}
+
+function resolveLanguage(setting, systemLocaleName) {
+ if (validLanguage(setting)) return setting
+ return validLanguage(systemLocaleName) ? systemLocaleName : ""
+}
+
function decodeSettings(settings) {
var values = settings || ({})
return {
enabled: values.spellingEnabled !== false,
- language: String(values.spellingLanguage || "en_US")
+ language: validLanguage(values.spellingLanguage) ? values.spellingLanguage : ""
}
}
diff --git a/ui/compose/SpellingState.qml b/ui/compose/SpellingState.qml
index 1862353..80040ce 100644
--- a/ui/compose/SpellingState.qml
+++ b/ui/compose/SpellingState.qml
@@ -9,7 +9,8 @@ Item {
visible: false
required property var service
readonly property bool enabledRequest: Spelling.decodeSettings(service.settings).enabled
- readonly property string language: Spelling.decodeSettings(service.settings).language
+ readonly property string languageOverride: Spelling.decodeSettings(service.settings).language
+ readonly property string language: Spelling.resolveLanguage(languageOverride, Qt.locale().name)
readonly property bool available: probe.status === Loader.Ready
&& probe.item !== null && probe.item.available
readonly property string status: probe.status === Loader.Error
diff --git a/ui/settings/Settings.js b/ui/settings/Settings.js
index 5a3b8c1..8ab6125 100644
--- a/ui/settings/Settings.js
+++ b/ui/settings/Settings.js
@@ -19,7 +19,7 @@ var DEFAULTS = ({
showBarIcon: true,
unifiedMailboxes: false,
spellingEnabled: true,
- spellingLanguage: "en_US",
+ spellingLanguage: "",
suggestEvents: false,
aiAgent: "System default",
aiModel: ""
diff --git a/ui/tests/qml/tst_service_settings.qml b/ui/tests/qml/tst_service_settings.qml
index 2c8510e..09ba2c2 100644
--- a/ui/tests/qml/tst_service_settings.qml
+++ b/ui/tests/qml/tst_service_settings.qml
@@ -164,7 +164,7 @@ Item {
function test_spelling_defaults_on_and_persists_changes() {
mailService.applySettings({})
compare(mailService.spellingEnabled, true)
- compare(mailService.spellingLanguage, "en_US")
+ compare(mailService.spellingLanguage, Qt.locale().name)
mailService.setSpellingEnabled(false)
compare(mailService.spellingEnabled, false)
@@ -179,6 +179,17 @@ Item {
compare(shellStore.updatedEntry.spellingLanguage, "en_GB")
}
+ function test_hostile_spelling_language_is_resolved_before_the_adapter() {
+ for (var i = 0; i < 5; i++) {
+ var values = ["../x", "en_US\n", "en_US\u0000", "éé", "x".repeat(500)]
+ mailService.applySettings({ spellingLanguage: values[i] })
+ compare(mailService.spellingLanguage, Qt.locale().name)
+ }
+ mailService.setSpellingLanguage("")
+ compare(shellStore.updatedEntry.spellingLanguage, "")
+ compare(mailService.spellingLanguage, Qt.locale().name)
+ }
+
// 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() {
diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml
index 3c969b2..c2cb6b5 100644
--- a/ui/tests/qml/tst_spellcheck_composer.qml
+++ b/ui/tests/qml/tst_spellcheck_composer.qml
@@ -106,7 +106,7 @@ Item {
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 })
+ var second = component.createObject(compose, { document: secondDoc.textDocument, language: "en_US" })
try {
verify(second.available)
second.ignoreForSession("zqxjremotereviewhere")
diff --git a/ui/tests/qml/tst_spellcheck_menu.qml b/ui/tests/qml/tst_spellcheck_menu.qml
index dd7f3d3..0e82c7b 100644
--- a/ui/tests/qml/tst_spellcheck_menu.qml
+++ b/ui/tests/qml/tst_spellcheck_menu.qml
@@ -77,6 +77,7 @@ Item {
function init() {
compose.parent.forceActiveFocus()
compose.begin("new", null, "", [])
+ compose.spellingLanguage = "en_US"
tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000)
if (!compose.spellingAvailable) skip("spelling unavailable (" + compose.spellingStatus + ")")
}
diff --git a/ui/tests/test_settings.js b/ui/tests/test_settings.js
index 81d703c..8419e79 100644
--- a/ui/tests/test_settings.js
+++ b/ui/tests/test_settings.js
@@ -12,7 +12,7 @@ for (const key of ["spellingEnabled", "spellingLanguage"]) {
deepEqual(settings.normalize(null), settings.DEFAULTS)
assert.equal(settings.normalize({ spellingEnabled: false }).spellingEnabled, false)
assert.equal(settings.normalize({ aiAgent: "Claude", calendarSnoozeMinutes: 10 }).aiAgent, "Claude")
-assert.equal(settings.normalize({ spellingLanguage: null, aiModel: undefined }).spellingLanguage, "en_US")
+assert.equal(settings.normalize({ spellingLanguage: null, aiModel: undefined }).spellingLanguage, "")
assert.equal(settings.normalize({ aiModel: undefined }).aiModel, "")
assert.equal(settings.DEFAULTS.aiAgent, "System default", "normalization does not mutate defaults")
deepEqual(bridge.settings({ spellingEnabled: false, spellingLanguage: "en_GB", secret: "synthetic" }, settings.DEFAULTS), {
diff --git a/ui/tests/test_spelling.js b/ui/tests/test_spelling.js
index 99ee7f1..339b808 100644
--- a/ui/tests/test_spelling.js
+++ b/ui/tests/test_spelling.js
@@ -29,13 +29,29 @@ test("Ranges keep UTF-16 offsets, apostrophes, combining marks and repeated word
deepEqual(rules.misspelledRanges("'' ’ 😀 ", wrong), [])
})
-test("Settings default to enabled en_US and only explicit false disables checking", () => {
+test("Settings default to enabled system language and only explicit false disables checking", () => {
const rules = spelling()
for (const settings of [null, {}, { spellingEnabled: "no" }, { spellingEnabled: 0 }]) {
- deepEqual(rules.decodeSettings(settings), { enabled: true, language: "en_US" })
+ deepEqual(rules.decodeSettings(settings), { enabled: true, language: "" })
}
deepEqual(rules.decodeSettings({ spellingEnabled: false, spellingLanguage: "en_GB" }), { enabled: false, language: "en_GB" })
- deepEqual(rules.decodeSettings({ spellingLanguage: "" }), { enabled: true, language: "en_US" })
+ deepEqual(rules.decodeSettings({ spellingLanguage: "" }), { enabled: true, language: "" })
+})
+
+test("Language uses the system locale unless a short dictionary code overrides it", () => {
+ const rules = spelling()
+ for (const valid of ["en", "en_US", "de-DE", "eng_Latn_US", "sr_Latn", "es_419"]) {
+ assert.equal(rules.validLanguage(valid), true)
+ assert.equal(rules.resolveLanguage(valid, "de_DE"), valid)
+ }
+ for (const hostile of [null, 42, {}, "", "C", " en_US", "en_US ", "en_US\n",
+ "en_US\r\n", "en_US\0", "../x", "en/US", "en\\US", "en..US", "éé", "a".repeat(500)]) {
+ assert.equal(rules.validLanguage(hostile), false, JSON.stringify(hostile))
+ assert.equal(rules.resolveLanguage(hostile, "de_DE"), "de_DE")
+ deepEqual(rules.decodeSettings({ spellingLanguage: hostile }), { enabled: true, language: "" })
+ }
+ assert.equal(rules.resolveLanguage("", "zz_ZZ"), "zz_ZZ", "no silent English fallback")
+ assert.equal(rules.resolveLanguage("", "C"), "", "an unsupported system locale never reaches Sonnet")
})
test("Underlines cover every visual line of a word and descending caret positions", () => {
From e8c8edf7a83afc547153e4f3d5ad76c93ec9f30a Mon Sep 17 00:00:00 2001
From: Chris Gray <216301595+latentoperator@users.noreply.github.com>
Date: Sun, 11 Oct 2026 19:01:57 -0500
Subject: [PATCH 24/88] Fix long-body spelling with viewport windows and
budgeted underline slices
---
README.md | 2 +-
ui/components/ComposeView.qml | 128 ++++++++++++++-------
ui/components/SettingsPage.qml | 4 +-
ui/compose/SpellcheckAdapter.qml | 12 +-
ui/compose/Spelling.js | 135 +++++++++++++++++++----
ui/compose/SpellingSession.js | 5 +-
ui/tests/qml/tst_service_settings.qml | 7 +-
ui/tests/qml/tst_spellcheck_composer.qml | 86 +++++++++++++++
ui/tests/test_spelling.js | 78 +++++++++++++
9 files changed, 388 insertions(+), 69 deletions(-)
diff --git a/README.md b/README.md
index 5249ef0..d29c381 100644
--- a/README.md
+++ b/README.md
@@ -44,7 +44,7 @@ Each installer verifies the release package before replacing an existing version
Composer body spellchecking uses KDE Sonnet and a local Hunspell dictionary. On Arch, install `sonnet` and the matching `hunspell-` package, such as `hunspell-en_us` or `hunspell-de`. On Debian and Ubuntu releases that provide Qt 6 Sonnet, install `qml6-module-org-kde-sonnet`, `sonnet6-plugins`, and the matching dictionary, such as `hunspell-en-us`. Restart Omamail after installing a dictionary.
-Only the message body is checked, not the subject. Spelling uses the system language by default (`Qt.locale().name`, for example `en_US` or `de_DE`) and can be turned off in Settings. The advanced `spellingLanguage` setting is empty for system language, or an installed dictionary code to override it; malformed values are treated as system language and never passed to Sonnet. There is no silent fallback to English: without the Sonnet QML module or the requested dictionary, composing remains available and Settings names what is missing. Omamail does not install system packages. Checks and corrections stay local; nothing leaves the machine. Ignore for this session stays in memory; there is no personal dictionary yet.
+Only completed words in the message body are checked, not the subject or quoted reply lines whose first non-space character is `>`. Checking is limited to the visible viewport plus one viewport of context on each side, with a 20,000-character window, at most 400 visible underline segments, and 8 ms / 12-token work slices. Tokens longer than 128 UTF-16 units are skipped; lines indented by more than 128 spaces or tabs are conservatively skipped. Scrolling checks the newly visible text. Corrections remain available on demand without waiting for the underline pass. Spelling uses the system language by default (`Qt.locale().name`, for example `en_US` or `de_DE`) and can be turned off in Settings. The advanced `spellingLanguage` setting is empty for system language, or an installed dictionary code to override it; malformed values are treated as system language and never passed to Sonnet. There is no silent fallback to English: without the Sonnet QML module or the requested dictionary, composing remains available and Settings names what is missing. Omamail does not install system packages. Checks and corrections stay local; nothing leaves the machine. Ignore for this session stays in memory; there is no personal dictionary yet.
## Run from source
diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml
index 1a7d52f..98ae83e 100644
--- a/ui/components/ComposeView.qml
+++ b/ui/components/ComposeView.qml
@@ -79,33 +79,89 @@ DropArea {
signal keyPressed(var event)
- // 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.
+ property var spellingPass: null
+ property var spellingWindow: ({ start: 0, end: 0 })
+ property int spellingGeneration: 0
+ readonly property int spellingDelegateCount: spellingSegments.count
+
+ function cancelSpellingPass() {
+ spellingGeneration += 1
+ spellingPass = null
+ spellingSlice.stop()
+ spellingSegments.clear()
+ spellingRanges = []
+ }
+
+ function scheduleSpellingLayout() {
+ cancelSpellingPass()
+ spellingScrollDebounce.restart()
+ }
+
function refreshSpellingRanges() {
+ cancelSpellingPass()
var adapter = spellingAdapter
- spellingRanges = (adapter && spellingAvailable && spellingEnabled)
- ? adapter.misspelledRanges(bodyEdit.text) : []
+ if (!adapter || !spellingAvailable || !spellingEnabled || bodyFlick.height <= 0) return
+ var text = bodyEdit.text
+ var top = Math.max(0, bodyFlick.contentY)
+ var bottom = top + bodyFlick.height
+ var visibleStart = Math.min(bodyEdit.positionAt(0, top), bodyEdit.positionAt(bodyEdit.width, top))
+ var visibleEnd = Math.max(bodyEdit.positionAt(0, bottom), bodyEdit.positionAt(bodyEdit.width, bottom))
+ var marginTop = Math.max(0, top - bodyFlick.height)
+ var marginBottom = bottom + bodyFlick.height
+ var start = Math.min(bodyEdit.positionAt(0, marginTop), bodyEdit.positionAt(bodyEdit.width, marginTop))
+ var end = Math.max(bodyEdit.positionAt(0, marginBottom), bodyEdit.positionAt(bodyEdit.width, marginBottom))
+ spellingWindow = Spelling.wordWindow(text, start, end)
+ spellingPass = Spelling.createPass(text, spellingWindow, visibleStart, visibleEnd, bodyRevision)
+ spellingPass.generation = spellingGeneration
+ spellingSlice.restart()
+ }
+
+ function processSpellingSlice() {
+ var pass = spellingPass
+ var adapter = spellingAdapter
+ if (!pass || !adapter || pass.revision !== bodyRevision || pass.generation !== spellingGeneration) {
+ cancelSpellingPass()
+ return
+ }
+ Spelling.advancePass(pass, function(word) { return adapter.isMisspelled(word) },
+ function() { return Date.now() }, function(range) {
+ var segments = Spelling.underlineSegments(range.start, range.end,
+ function(position) { return bodyEdit.positionToRectangle(position) },
+ bodyEdit.leftPadding, bodyEdit.width - bodyEdit.rightPadding)
+ var before = spellingSegments.count
+ for (var i = 0; i < segments.length && spellingSegments.count < Spelling.MAX_UNDERLINE_RANGES; i++) {
+ // Margin words warm the checker cache; only viewport geometry paints.
+ var segment = segments[i]
+ if (segment.y >= bodyFlick.contentY && segment.y < bodyFlick.contentY + bodyFlick.height)
+ spellingSegments.append({ segmentX: segment.x, segmentY: segment.y, segmentWidth: segment.width })
+ }
+ return spellingSegments.count > before
+ })
+ if (pass.revision !== bodyRevision || pass.generation !== spellingGeneration) {
+ cancelSpellingPass()
+ return
+ }
+ spellingRanges = pass.ranges.slice()
+ if (!pass.done) spellingSlice.restart()
}
+
+ onBodyRevisionChanged: cancelSpellingPass()
+ onSpellingLayoutKeyChanged: scheduleSpellingLayout()
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()
+ onSpellingLanguageChanged: { cancelSpellingPass(); spellingDebounce.restart() }
- Timer {
- id: spellingDebounce
- interval: 120
- repeat: false
- onTriggered: root.refreshSpellingRanges()
- }
+ ListModel { id: spellingSegments }
+ Timer { id: spellingSlice; interval: 1; onTriggered: root.processSpellingSlice() }
+ Timer { id: spellingScrollDebounce; interval: 40; onTriggered: root.refreshSpellingRanges() }
+ Timer { id: spellingDebounce; interval: 120; 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) {
+ if (!adapter || !spellingAvailable || editor !== bodyEdit
+ || Spelling.quotedAt(bodyEdit.text, editor.positionAt(x, y))) {
textMenu.spellingPosition = -1
textMenu.spellingWord = ""
textMenu.spellingMisspelled = false
@@ -127,6 +183,7 @@ DropArea {
var adapter = spellingAdapter
if (!bodyEdit.activeFocus || !spellingEnabled || !adapter || !spellingAvailable) return false
var position = bodyEdit.cursorPosition
+ if (Spelling.quotedAt(bodyEdit.text, position)) return false
var info = adapter.inspect(position)
if (!info.misspelled) return false
textMenu.spellingPosition = position
@@ -1977,6 +2034,8 @@ DropArea {
anchors.topMargin: Style.space(12)
contentWidth: width
contentHeight: bodyEdit.height
+ onContentYChanged: root.scheduleSpellingLayout()
+ onHeightChanged: root.scheduleSpellingLayout()
clip: true
boundsBehavior: Flickable.StopAtBounds
ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded }
@@ -2029,30 +2088,17 @@ DropArea {
id: spellingUnderlines
anchors.fill: parent
Repeater {
- model: root.spellingRanges
- delegate: Item {
- required property var modelData
- anchors.fill: parent
- readonly property var segments: {
- // Qt reads layout inputs internally; name them to refresh after
- // a width or font change even when the ranges are unchanged.
- root.spellingLayoutKey
- return Spelling.underlineSegments(modelData.start, modelData.end,
- function(position) { return bodyEdit.positionToRectangle(position) },
- bodyEdit.leftPadding, bodyEdit.width - bodyEdit.rightPadding)
- }
- Repeater {
- model: segments
- delegate: Rectangle {
- required property var modelData
- objectName: "spelling-underline"
- x: modelData.x
- y: modelData.y
- width: modelData.width
- height: 1
- color: root.errorColor
- }
- }
+ model: spellingSegments
+ delegate: Rectangle {
+ required property real segmentX
+ required property real segmentY
+ required property real segmentWidth
+ x: segmentX
+ y: segmentY
+ width: segmentWidth
+ objectName: "spelling-underline"
+ height: 1
+ color: root.errorColor
}
}
}
@@ -2086,7 +2132,7 @@ DropArea {
Connections {
target: spellcheckLoader.item
- function onCheckerChanged() { spellingDebounce.restart() }
+ function onCheckerChanged() { root.cancelSpellingPass(); spellingDebounce.restart() }
}
Rectangle {
diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml
index ebbf1e1..9372503 100644
--- a/ui/components/SettingsPage.qml
+++ b/ui/components/SettingsPage.qml
@@ -874,7 +874,7 @@ Column {
objectName: "spellingLanguagePolicy"
width: parent.width
text: "Checking spelling in "
- + Spelling.resolveLanguage(root.service ? root.service.spellingLanguage : "", Qt.locale().name)
+ + (Spelling.resolveLanguage(root.service ? root.service.spellingLanguage : "", Qt.locale().name) || Qt.locale().name)
+ (root.service && Spelling.decodeSettings(root.service.settings).language !== ""
? " (set in settings)." : " (system language).")
color: root.dimColor
@@ -894,7 +894,7 @@ Column {
visible: !!root.service && !root.service.spellingAvailable
text: root.service && root.service.spellingStatus === "no-module"
? "Spell-checking is unavailable: install the Sonnet QML module, then restart Omamail."
- : "The " + Spelling.resolveLanguage(root.service ? root.service.spellingLanguage : "", Qt.locale().name)
+ : "The " + (Spelling.resolveLanguage(root.service ? root.service.spellingLanguage : "", Qt.locale().name) || Qt.locale().name)
+ " dictionary is not installed. Install the matching Hunspell "
+ "dictionary package (hunspell-, for example hunspell-de), then restart Omamail."
color: root.accentColor
diff --git a/ui/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml
index b54e6c4..7cb943a 100644
--- a/ui/compose/SpellcheckAdapter.qml
+++ b/ui/compose/SpellcheckAdapter.qml
@@ -45,6 +45,15 @@ Item {
readonly property string status: !enabled ? "disabled"
: (available ? "ready" : "no-dictionary")
+ property var verdictCache: Spelling.createCache()
+ function resetCache() { verdictCache = Spelling.createCache() }
+ function isMisspelled(word) {
+ if (!available || !enabled) return false
+ return Spelling.cachedVerdict(verdictCache, word, function(value) {
+ return highlighter.isWordMisspelled(value)
+ })
+ }
+
signal checkerChanged()
Component.onCompleted: {
Session.subscribe(adapter)
@@ -89,11 +98,12 @@ Item {
function misspelledRanges(text) {
if (!available || !enabled) return []
return Spelling.misspelledRanges(text, function(word) {
- return highlighter.isWordMisspelled(word)
+ return adapter.isMisspelled(word)
})
}
function applySettings() {
+ resetCache()
// 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.
diff --git a/ui/compose/Spelling.js b/ui/compose/Spelling.js
index 069643d..1a135a9 100644
--- a/ui/compose/Spelling.js
+++ b/ui/compose/Spelling.js
@@ -2,29 +2,124 @@
// Spelling presentation rules shared by the composer and optional adapter.
// Positions are UTF-16 offsets, matching Qt's text document API.
-function misspelledRanges(text, isMisspelled) {
- var ranges = []
- if (!text) return ranges
+var MAX_WINDOW_CHARACTERS = 20000
+var MAX_UNDERLINE_RANGES = 400
+var MAX_WORD_CHARACTERS = 128
+var MAX_CACHE_WORDS = 4096
+var SLICE_MILLISECONDS = 8
+var MAX_SLICE_WORDS = 12
+var MAX_SLICE_CHARACTERS = 512
+
+// Do not split a token at a window edge or traverse an arbitrarily long word.
+// If expansion cannot fit the cap, skip that token rather than check a fragment.
+function wordWindow(text, start, end) {
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 (isMisspelled(word)) ranges.push({ start: wordStart, end: wordEnd })
+ var from = Math.max(0, Math.min(length, Math.floor(start)))
+ var to = Math.max(from, Math.min(length, Math.ceil(end)))
+ var walked = 0
+ while (from > 0 && isWordChar(text.charAt(from - 1)) && walked < MAX_WORD_CHARACTERS) {
+ from -= 1; walked += 1
+ }
+ if (from > 0 && isWordChar(text.charAt(from - 1))) {
+ from = Math.max(0, Math.min(length, Math.floor(start)))
+ while (from < length && isWordChar(text.charAt(from)) && from - start < MAX_WORD_CHARACTERS) from += 1
+ }
+ to = Math.min(to, from + MAX_WINDOW_CHARACTERS)
+ var originalEnd = to
+ while (to < length && isWordChar(text.charAt(to))
+ && to - originalEnd < MAX_WORD_CHARACTERS && to - from < MAX_WINDOW_CHARACTERS) to += 1
+ if (to < length && isWordChar(text.charAt(to))) {
+ while (to > from && isWordChar(text.charAt(to - 1))) to -= 1
+ }
+ return { start: from, end: to }
+}
+
+// Find the containing paragraph with the native string search, then examine
+// only its bounded indentation. No quoted words reach the dictionary checker.
+function quotedAt(text, position) {
+ var at = text.lastIndexOf("\n", Math.max(0, position) - 1) + 1
+ var first = at
+ while (at < text.length && (text.charAt(at) === " " || text.charAt(at) === "\t")
+ && at - first < MAX_WORD_CHARACTERS) at += 1
+ return text.charAt(at) === ">" || text.charAt(at) === " " || text.charAt(at) === "\t"
+}
+
+function createPass(text, window, visibleStart, visibleEnd, revision) {
+ return { text: text.substring(window.start, window.end), offset: window.start,
+ index: 0, documentLength: text.length, quoted: quotedAt(text, window.start),
+ lineStart: false, visibleStart: visibleStart, visibleEnd: visibleEnd,
+ revision: revision, ranges: [], skipLong: window.start > 0
+ && isWordChar(text.charAt(window.start - 1)) && isWordChar(text.charAt(window.start)),
+ done: window.end <= window.start }
+}
+
+function nextWord(pass, limit) {
+ var text = pass.text
+ while (pass.index < text.length && pass.index < limit) {
+ var ch = text.charAt(pass.index)
+ if (ch === "\n") {
+ pass.index += 1; pass.lineStart = true; pass.quoted = false; pass.skipLong = false; continue
+ }
+ if (pass.lineStart) {
+ if (ch === " " || ch === "\t") { pass.index += 1; continue }
+ pass.quoted = ch === ">"; pass.lineStart = false
+ }
+ if (pass.skipLong) {
+ if (isWordChar(ch)) { pass.index += 1; continue }
+ pass.skipLong = false
+ }
+ if (pass.quoted || !isWordChar(ch)) { pass.index += 1; continue }
+ var start = pass.index
+ while (pass.index < text.length && isWordChar(text.charAt(pass.index))
+ && pass.index - start <= MAX_WORD_CHARACTERS) pass.index += 1
+ var end = pass.index
+ if (pass.offset + end >= pass.documentLength) continue // unfinished final word
+ if (end - start > MAX_WORD_CHARACTERS) { pass.skipLong = true; continue }
+ while (start < end && isApostrophe(text.charAt(start))) start += 1
+ while (end > start && isApostrophe(text.charAt(end - 1))) end -= 1
+ if (end > start) return { start: pass.offset + start, end: pass.offset + end,
+ word: text.substring(start, end) }
+ }
+ return null
+}
+
+// The injected clock makes the time rule deterministic in tests. `paint` runs
+// inside the same slice so native geometry and delegate creation share its budget.
+function advancePass(pass, isMisspelled, clock, paint) {
+ var began = clock()
+ var count = 0
+ var limit = pass.index + MAX_SLICE_CHARACTERS
+ while (!pass.done && count < MAX_SLICE_WORDS && clock() - began < SLICE_MILLISECONDS) {
+ var range = nextWord(pass, limit)
+ if (!range) { pass.done = pass.index >= pass.text.length; break }
+ count += 1
+ if (isMisspelled(range.word) && range.end > pass.visibleStart && range.start < pass.visibleEnd) {
+ var stored = { start: range.start, end: range.end }
+ if (paint && paint(stored) === false) continue
+ pass.ranges.push(stored)
+ if (pass.ranges.length >= MAX_UNDERLINE_RANGES) pass.done = true
}
}
- return ranges
+ return pass.done
+}
+
+function createCache() { return { words: ({}), size: 0 } }
+function cachedVerdict(cache, word, check) {
+ // Prefixing keeps arbitrary words such as __proto__ away from object keys.
+ var key = "$" + word
+ if (Object.prototype.hasOwnProperty.call(cache.words, key)) return cache.words[key]
+ if (cache.size >= MAX_CACHE_WORDS) { cache.words = ({}); cache.size = 0 }
+ var verdict = check(word)
+ cache.words[key] = verdict; cache.size += 1
+ return verdict
+}
+
+// Small-text helper for non-visual callers; production uses incremental passes.
+function misspelledRanges(text, isMisspelled) {
+ var window = wordWindow(text, 0, text.length)
+ var pass = createPass(text, window, window.start, window.end, 0)
+ while (!pass.done) advancePass(pass, isMisspelled, function() { return 0 }, null)
+ return pass.ranges
}
function isWordChar(character) {
diff --git a/ui/compose/SpellingSession.js b/ui/compose/SpellingSession.js
index 65982a2..2a587d9 100644
--- a/ui/compose/SpellingSession.js
+++ b/ui/compose/SpellingSession.js
@@ -13,5 +13,8 @@ function unsubscribe(adapter) {
function changed() {
var current = adapters.slice()
- for (var i = 0; i < current.length; i++) current[i].checkerChanged()
+ for (var i = 0; i < current.length; i++) {
+ current[i].resetCache()
+ current[i].checkerChanged()
+ }
}
diff --git a/ui/tests/qml/tst_service_settings.qml b/ui/tests/qml/tst_service_settings.qml
index 09ba2c2..5c6a366 100644
--- a/ui/tests/qml/tst_service_settings.qml
+++ b/ui/tests/qml/tst_service_settings.qml
@@ -2,6 +2,7 @@ import QtQuick 2.15
import QtTest 1.3
import "../.." as Omamail
import "../../account/Unified.js" as Unified
+import "../../compose/Spelling.js" as Spelling
Item {
width: 400
@@ -164,7 +165,7 @@ Item {
function test_spelling_defaults_on_and_persists_changes() {
mailService.applySettings({})
compare(mailService.spellingEnabled, true)
- compare(mailService.spellingLanguage, Qt.locale().name)
+ compare(mailService.spellingLanguage, Spelling.resolveLanguage("", Qt.locale().name))
mailService.setSpellingEnabled(false)
compare(mailService.spellingEnabled, false)
@@ -183,11 +184,11 @@ Item {
for (var i = 0; i < 5; i++) {
var values = ["../x", "en_US\n", "en_US\u0000", "éé", "x".repeat(500)]
mailService.applySettings({ spellingLanguage: values[i] })
- compare(mailService.spellingLanguage, Qt.locale().name)
+ compare(mailService.spellingLanguage, Spelling.resolveLanguage("", Qt.locale().name))
}
mailService.setSpellingLanguage("")
compare(shellStore.updatedEntry.spellingLanguage, "")
- compare(mailService.spellingLanguage, Qt.locale().name)
+ compare(mailService.spellingLanguage, Spelling.resolveLanguage("", Qt.locale().name))
}
// The probe loads Sonnet through the same adapter the composer uses; it
diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml
index c2cb6b5..311a821 100644
--- a/ui/tests/qml/tst_spellcheck_composer.qml
+++ b/ui/tests/qml/tst_spellcheck_composer.qml
@@ -1,6 +1,7 @@
import QtQuick
import QtTest
import "../../components" as Omamail
+import "../../compose/Spelling.js" as Spelling
// The real composer attaches the optional spelling adapter to its body
// document, does not change the draft while checking, and unloads cleanly when
@@ -78,6 +79,91 @@ Item {
compose.contentDirection = ""
compose.spellingEnabled = true
compose.spellingLanguage = "en_US"
+ named(compose, "compose-body").contentY = 0
+ }
+
+ function readyAdapter() {
+ tryVerify(function() { return compose.spellingAdapter !== null || compose.spellingStatus === "no-module" }, 3000)
+ if (!compose.spellingAvailable) { skip("spelling unavailable (" + compose.spellingStatus + ")"); return null }
+ return compose.spellingAdapter
+ }
+
+ function test_long_body_only_paints_visible_bounded_ranges_and_scrolls_to_end() {
+ if (!readyAdapter()) return
+ var body = named(compose, "compose-body-editor")
+ var flick = named(compose, "compose-body")
+ body.text = "mispelled ".repeat(10000)
+ flick.contentY = 0
+ compose.refreshSpellingRanges()
+ tryVerify(function() { return compose.spellingPass && compose.spellingPass.done }, 5000)
+ verify(compose.spellingDelegateCount > 0)
+ verify(compose.spellingDelegateCount <= Spelling.MAX_UNDERLINE_RANGES)
+ verify(compose.spellingRanges.length <= Spelling.MAX_UNDERLINE_RANGES)
+ verify(compose.spellingWindow.end - compose.spellingWindow.start <= Spelling.MAX_WINDOW_CHARACTERS)
+ for (var i = 0; i < compose.spellingRanges.length; i++) {
+ var box = body.positionToRectangle(compose.spellingRanges[i].start)
+ verify(box.y >= flick.contentY && box.y < flick.contentY + flick.height)
+ }
+ verify(compose.spellingRanges[compose.spellingRanges.length - 1].end < body.text.length / 2)
+ flick.contentY = flick.contentHeight - flick.height
+ tryVerify(function() {
+ return compose.spellingRanges.length > 0
+ && compose.spellingRanges[compose.spellingRanges.length - 1].end > 99000
+ }, 5000)
+ verify(compose.spellingDelegateCount <= Spelling.MAX_UNDERLINE_RANGES)
+ verify(compose.spellingRanges[0].start > 90000)
+ }
+
+ function test_revision_change_abandons_an_incomplete_pass_before_it_can_paint() {
+ var adapter = readyAdapter()
+ if (!adapter) return
+ var body = named(compose, "compose-body-editor")
+ body.text = "mispelled ".repeat(10000)
+ compose.refreshSpellingRanges()
+ compose.processSpellingSlice()
+ var oldPass = compose.spellingPass
+ verify(oldPass && !oldPass.done, "long work yields to the next tick")
+ body.insert(0, "correct ")
+ compare(compose.spellingDelegateCount, 0)
+ compare(compose.spellingRanges.length, 0)
+ compare(compose.spellingPass, null)
+ // Even an explicitly delivered stale continuation cannot paint.
+ compose.spellingPass = oldPass
+ compose.processSpellingSlice()
+ compare(compose.spellingDelegateCount, 0)
+ compare(compose.spellingPass, null)
+ }
+
+ function test_quoted_reply_lines_never_reach_the_checker() {
+ var adapter = readyAdapter()
+ if (!adapter) return
+ var body = named(compose, "compose-body-editor")
+ body.text = ("> mispelled wrod \n").repeat(6000)
+ adapter.resetCache()
+ compose.refreshSpellingRanges()
+ tryVerify(function() { return compose.spellingPass && compose.spellingPass.done }, 5000)
+ compare(adapter.verdictCache.size, 0)
+ compare(compose.spellingDelegateCount, 0)
+ body.cursorPosition = 4
+ body.forceActiveFocus()
+ compare(compose.openSpellingAtCaret(), false)
+ }
+
+ function test_suggestions_inspect_a_word_outside_the_processed_window_on_demand() {
+ if (!readyAdapter()) return
+ var body = named(compose, "compose-body-editor")
+ body.text = "correct ".repeat(12500) + "mispelled "
+ named(compose, "compose-body").contentY = 0
+ compose.refreshSpellingRanges()
+ var firstWindowEnd = compose.spellingWindow.end
+ body.cursorPosition = body.text.length - 5
+ body.forceActiveFocus()
+ verify(body.cursorPosition > firstWindowEnd)
+ verify(compose.openSpellingAtCaret())
+ var menu = named(compose, "compose-text-menu")
+ compare(menu.spellingWord, "mispelled")
+ verify(menu.spellingSuggestions.length > 0)
+ menu.close()
}
function test_body_adapter_attaches_and_checking_does_not_mutate() {
diff --git a/ui/tests/test_spelling.js b/ui/tests/test_spelling.js
index 339b808..88e91c7 100644
--- a/ui/tests/test_spelling.js
+++ b/ui/tests/test_spelling.js
@@ -54,6 +54,84 @@ test("Language uses the system locale unless a short dictionary code overrides i
assert.equal(rules.resolveLanguage("", "C"), "", "an unsupported system locale never reaches Sonnet")
})
+test("Windows expand whole words, preserve offsets and cap hostile tokens", () => {
+ const r = spelling()
+ deepEqual(r.wordWindow("hello mispelled here ", 8, 12), { start: 6, end: 15 })
+ const text = "wrod ".repeat(20000)
+ const window = r.wordWindow(text, 0, text.length)
+ assert.ok(window.end - window.start <= r.MAX_WINDOW_CHARACTERS)
+ assert.equal(text[window.end - 1], " ")
+ const hostile = "a".repeat(100000) + " wrod "
+ const seen = []
+ r.misspelledRanges(hostile, w => { seen.push(w); return true })
+ assert.equal(seen.length, 0, "a huge token never reaches the native checker")
+ r.misspelledRanges("a".repeat(129) + " wrod ", w => { seen.push(w); return true })
+ assert.deepEqual(seen, ["wrod"], "an over-budget token is skipped, not split")
+ deepEqual(r.misspelledRanges("a".repeat(129) + "\nwrod ", () => true), [{ start: 130, end: 134 }])
+})
+
+test("Quoted lines skip lookup including an initial window in the middle of a quote", () => {
+ const r = spelling()
+ const text = "wrod \n > mispelled wrod \n\t> more wrod \nunquoted "
+ const seen = []
+ const ranges = r.misspelledRanges(text, w => { seen.push(w); return true })
+ assert.deepEqual(seen, ["wrod", "unquoted"])
+ assert.equal(ranges.length, 2)
+ assert.equal(r.quotedAt(text, text.indexOf("mispelled")), true)
+ assert.equal(r.quotedAt(text, text.indexOf("unquoted")), false)
+ const window = r.wordWindow(text, text.indexOf("mispelled") + 2, text.indexOf("more") + 2)
+ const pass = r.createPass(text, window, 0, text.length, 1)
+ while (!pass.done) r.advancePass(pass, () => { throw Error("quote reached checker") }, () => 0)
+})
+
+test("Range, token, character and deterministic time budgets yield without losing work", () => {
+ const r = spelling()
+ const text = "wrod ".repeat(10000)
+ const window = r.wordWindow(text, 0, text.length)
+ const pass = r.createPass(text, window, 0, text.length, 7)
+ const paint = []
+ r.advancePass(pass, () => true, () => 0, range => paint.push(range))
+ assert.equal(pass.ranges.length, r.MAX_SLICE_WORDS)
+ assert.equal(pass.done, false)
+ let clock = 0
+ const timed = r.createPass(text, window, 0, text.length, 7)
+ r.advancePass(timed, () => true, () => { clock += 4; return clock })
+ assert.equal(timed.ranges.length, 1)
+ while (!pass.done) r.advancePass(pass, () => true, () => 0)
+ assert.equal(pass.ranges.length, r.MAX_UNDERLINE_RANGES)
+ const blank = r.createPass(" ".repeat(20000), { start: 0, end: 20000 }, 0, 20000, 0)
+ r.advancePass(blank, () => true, () => 0)
+ assert.equal(blank.done, false)
+ assert.ok(blank.index <= r.MAX_SLICE_CHARACTERS)
+ const narrow = r.createPass(text, window, 1000, 1100, 0)
+ while (!narrow.done) r.advancePass(narrow, () => true, () => 0)
+ assert.ok(narrow.ranges.length > 0)
+ assert.ok(narrow.ranges.every(x => x.start >= 1000 && x.end <= 1100))
+})
+
+test("Cached verdicts avoid repeat queries, are bounded and invalidate with the session", () => {
+ const r = spelling()
+ const session = load("compose/SpellingSession.js")
+ let count = 0
+ let cache = r.createCache()
+ const checker = () => { count++; return true }
+ assert.equal(r.cachedVerdict(cache, "__proto__", checker), true)
+ assert.equal(r.cachedVerdict(cache, "__proto__", checker), true)
+ assert.equal(count, 1)
+ let notifications = 0
+ const adapter = { resetCache() { cache = r.createCache() }, checkerChanged() { notifications++ } }
+ session.subscribe(adapter)
+ session.changed()
+ assert.equal(notifications, 1)
+ r.cachedVerdict(cache, "__proto__", checker)
+ assert.equal(count, 2, "Ignore and language notifications discard stale verdicts")
+ for (let i = 0; i <= r.MAX_CACHE_WORDS; i++) r.cachedVerdict(cache, "w" + i, checker)
+ assert.ok(cache.size <= r.MAX_CACHE_WORDS)
+ session.unsubscribe(adapter)
+ session.changed()
+ assert.equal(notifications, 1)
+})
+
test("Underlines cover every visual line of a word and descending caret positions", () => {
const rules = spelling()
const positions = [
From 74917ec991547a7bf5d882310d065c3a3057bf06 Mon Sep 17 00:00:00 2001
From: Chris Gray <216301595+latentoperator@users.noreply.github.com>
Date: Sun, 11 Oct 2026 19:03:15 -0500
Subject: [PATCH 25/88] Add local spelling session and native settings refusal
regressions
---
app/tests/native/tst_settings.cpp | 14 ++++++++
ui/tests/qml/tst_spellcheck_adapter.qml | 27 +++++++++++++++
ui/tests/qml/tst_spellcheck_composer.qml | 44 ++++++++++++++++++++++++
3 files changed, 85 insertions(+)
diff --git a/app/tests/native/tst_settings.cpp b/app/tests/native/tst_settings.cpp
index e20cb18..615539c 100644
--- a/app/tests/native/tst_settings.cpp
+++ b/app/tests/native/tst_settings.cpp
@@ -75,6 +75,20 @@ void SettingsTest::acceptsSpellingSettings()
QVERIFY2(store.replace(settings, &error), qPrintable(error));
QCOMPARE(store.load(&error), settings);
QVERIFY(error.isEmpty());
+ auto systemLanguage = settings;
+ systemLanguage[QStringLiteral("spellingLanguage")] = QString();
+ QVERIFY2(store.replace(systemLanguage, &error), qPrintable(error));
+ QCOMPARE(store.load(&error), systemLanguage);
+
+ QFile saved(path);
+ QVERIFY(saved.open(QIODevice::ReadOnly));
+ const QByteArray original = saved.readAll();
+ saved.close();
+ auto unreviewed = systemLanguage;
+ unreviewed[QStringLiteral("unreviewedSpellingSetting")] = true;
+ QVERIFY(!store.replace(unreviewed, &error));
+ QVERIFY(saved.open(QIODevice::ReadOnly));
+ QCOMPARE(saved.readAll(), original); // refusal must not modify the saved settings
}
void SettingsTest::invalidJsonIsPreserved()
diff --git a/ui/tests/qml/tst_spellcheck_adapter.qml b/ui/tests/qml/tst_spellcheck_adapter.qml
index 4b80a14..a92c966 100644
--- a/ui/tests/qml/tst_spellcheck_adapter.qml
+++ b/ui/tests/qml/tst_spellcheck_adapter.qml
@@ -49,6 +49,33 @@ Item {
return a
}
+ function test_language_changes_discard_native_verdict_cache() {
+ var a = adapter()
+ if (!a) return
+ compare(a.isMisspelled("mispelled"), true)
+ verify(a.verdictCache.size > 0)
+ a.language = "zz_ZZ"
+ compare(a.available, false)
+ compare(a.verdictCache.size, 0)
+ a.language = "en_US"
+ compare(a.available, true)
+ compare(a.verdictCache.size, 0)
+ compare(a.isMisspelled("mispelled"), true)
+ }
+
+ function test_hostile_override_never_becomes_the_native_dictionary_name() {
+ var a = adapter()
+ if (!a) return
+ try {
+ var values = ["../x", "en_US\r\n", "en_US\u0000", "éé", "x".repeat(500)]
+ for (var i = 0; i < values.length; i++) {
+ a.language = values[i]
+ verify(a.resolvedLanguage !== values[i])
+ verify(a.resolvedLanguage === Qt.locale().name || a.resolvedLanguage === "")
+ }
+ } finally { a.language = "en_US" }
+ }
+
function test_ready_and_status() {
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 311a821..9ac3bd4 100644
--- a/ui/tests/qml/tst_spellcheck_composer.qml
+++ b/ui/tests/qml/tst_spellcheck_composer.qml
@@ -24,6 +24,12 @@ Item {
]
property string accountEmail: "me@example.com"
property string activeAccountId: "me@example.com"
+ property var configWrites: []
+ function writeConfig(name, text, callback) {
+ configWrites = configWrites.concat([String(name)])
+ if (typeof callback === "function") callback(false, "No filesystem writer in this fixture")
+ return false
+ }
function preferredSendAs(_r) { return null }
function switchTo(_id) { return true }
function refreshRecipientContacts() {}
@@ -166,6 +172,44 @@ Item {
menu.close()
}
+ function test_complete_local_spelling_session() {
+ if (!readyAdapter()) return
+ mailService.configWrites = []
+ var body = named(compose, "compose-body-editor")
+ var menu = named(compose, "compose-text-menu")
+ body.forceActiveFocus()
+ var typed = "mispelled "
+ for (var i = 0; i < typed.length; i++) keyClick(typed.toUpperCase().charCodeAt(i), Qt.NoModifier, 0)
+ compare(body.text, typed)
+ tryVerify(function() { return compose.spellingRanges.length > 0 })
+ body.cursorPosition = 3
+ verify(compose.openSpellingAtCaret())
+ compare(menu.spellingWord, "mispelled")
+ verify(menu.spellingSuggestions.length > 0)
+ menu.chooseSuggestion(0)
+ verify(body.text !== typed)
+ compare(compose.bodyWasEdited, true)
+ body.undo()
+ compare(body.text, typed)
+ body.insert(body.text.length, "zqxjlocalonlyspell ")
+ body.cursorPosition = body.text.indexOf("zqxjlocalonlyspell") + 2
+ body.forceActiveFocus()
+ verify(compose.openSpellingAtCaret())
+ menu.ignoreWordRow.activated()
+ compare(compose.spellingAdapter.inspect(body.cursorPosition).misspelled, false)
+ compose.spellingEnabled = false
+ tryVerify(function() { return compose.spellingAdapter === null })
+ compare(compose.spellingDelegateCount, 0)
+ compose.spellingEnabled = true
+ tryVerify(function() { return compose.spellingAvailable })
+ compose.spellingLanguage = "zz_ZZ"
+ tryCompare(compose, "spellingStatus", "no-dictionary")
+ compare(compose.spellingDelegateCount, 0)
+ compose.spellingLanguage = "en_US"
+ tryCompare(compose, "spellingStatus", "ready")
+ compare(mailService.configWrites.length, 0, "no spelling file writer was invoked")
+ }
+
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")
From 9cf9dd2a0def830278ae16e0a81840fc1024773e Mon Sep 17 00:00:00 2001
From: Chris Gray <216301595+latentoperator@users.noreply.github.com>
Date: Sun, 11 Oct 2026 20:49:08 -0500
Subject: [PATCH 26/88] Skip email addresses and web links in composer spelling
---
ui/components/ComposeView.qml | 1 +
ui/compose/SpellcheckAdapter.qml | 4 ++
ui/compose/Spelling.js | 33 +++++++++-
ui/tests/qml/tst_spellcheck_adapter.qml | 20 ++++++
ui/tests/qml/tst_spellcheck_composer.qml | 48 ++++++++++++++
ui/tests/test_spelling.js | 82 ++++++++++++++++++++++++
6 files changed, 187 insertions(+), 1 deletion(-)
diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml
index 98ae83e..2acd23f 100644
--- a/ui/components/ComposeView.qml
+++ b/ui/components/ComposeView.qml
@@ -2116,6 +2116,7 @@ DropArea {
onLoaded: {
if (!item) return
item.document = bodyEdit.textDocument
+ item.editor = bodyEdit
item.enabled = root.spellingEnabled
root.refreshSpellingRanges()
}
diff --git a/ui/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml
index 7cb943a..7223783 100644
--- a/ui/compose/SpellcheckAdapter.qml
+++ b/ui/compose/SpellcheckAdapter.qml
@@ -22,6 +22,8 @@ Item {
// highlighter by destroying the adapter (unload its Loader), not by clearing
// this.
property var document: null
+ // Read plain text only on inspection, not through a whole-body change binding.
+ property var editor: 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
@@ -68,6 +70,8 @@ Item {
function inspect(position) {
if (!available || document === null) return { word: "", misspelled: false, suggestions: [] }
var at = Math.max(0, Math.floor(position))
+ if (editor !== null && Spelling.nonProseAt(editor.text, at))
+ return { word: "", misspelled: false, suggestions: [] }
var list = highlighter.suggestions(at, 5)
return {
word: String(highlighter.wordUnderMouse),
diff --git a/ui/compose/Spelling.js b/ui/compose/Spelling.js
index 1a135a9..460343d 100644
--- a/ui/compose/Spelling.js
+++ b/ui/compose/Spelling.js
@@ -5,6 +5,7 @@
var MAX_WINDOW_CHARACTERS = 20000
var MAX_UNDERLINE_RANGES = 400
var MAX_WORD_CHARACTERS = 128
+var MAX_CHUNK_CHARACTERS = 256
var MAX_CACHE_WORDS = 4096
var SLICE_MILLISECONDS = 8
var MAX_SLICE_WORDS = 12
@@ -44,8 +45,37 @@ function quotedAt(text, position) {
return text.charAt(at) === ">" || text.charAt(at) === " " || text.charAt(at) === "\t"
}
+// A bounded chunk rule, not URL parsing: none of its word fragments are prose.
+// Retain the document string in a pass so window edges cannot hide a prefix/@.
+function nonProseAt(text, position) {
+ var at = Math.max(0, Math.min(text.length, Math.floor(position)))
+ if ((at === text.length || chunkDelimiter(text.charAt(at)))
+ && at > 0 && isWordChar(text.charAt(at - 1))) at -= 1
+ if (at === text.length || chunkDelimiter(text.charAt(at))) return false
+ var from = at
+ var to = at
+ while (from > 0 && !chunkDelimiter(text.charAt(from - 1))) {
+ if (at - from >= MAX_CHUNK_CHARACTERS) return true
+ from -= 1
+ }
+ while (to < text.length && !chunkDelimiter(text.charAt(to))) {
+ if (to - from >= MAX_CHUNK_CHARACTERS) return true
+ to += 1
+ }
+ var chunk = text.substring(from, to)
+ if (/^(?:[A-Za-z][A-Za-z0-9+.-]*:\/\/|mailto:|www\.)/i.test(chunk)) return true
+ var email = chunk.indexOf("@")
+ while (email >= 0) {
+ if (isWordChar(chunk.charAt(email - 1)) && isWordChar(chunk.charAt(email + 1))) return true
+ email = chunk.indexOf("@", email + 1)
+ }
+ return false
+}
+
+function chunkDelimiter(character) { return /[\s<>()\[\]"',;]/.test(character) }
+
function createPass(text, window, visibleStart, visibleEnd, revision) {
- return { text: text.substring(window.start, window.end), offset: window.start,
+ return { documentText: text, text: text.substring(window.start, window.end), offset: window.start,
index: 0, documentLength: text.length, quoted: quotedAt(text, window.start),
lineStart: false, visibleStart: visibleStart, visibleEnd: visibleEnd,
revision: revision, ranges: [], skipLong: window.start > 0
@@ -93,6 +123,7 @@ function advancePass(pass, isMisspelled, clock, paint) {
var range = nextWord(pass, limit)
if (!range) { pass.done = pass.index >= pass.text.length; break }
count += 1
+ if (nonProseAt(pass.documentText, range.start)) continue
if (isMisspelled(range.word) && range.end > pass.visibleStart && range.start < pass.visibleEnd) {
var stored = { start: range.start, end: range.end }
if (paint && paint(stored) === false) continue
diff --git a/ui/tests/qml/tst_spellcheck_adapter.qml b/ui/tests/qml/tst_spellcheck_adapter.qml
index a92c966..d6158f1 100644
--- a/ui/tests/qml/tst_spellcheck_adapter.qml
+++ b/ui/tests/qml/tst_spellcheck_adapter.qml
@@ -25,6 +25,7 @@ Item {
source: "../../compose/SpellcheckAdapter.qml"
onLoaded: {
item.document = edit.textDocument
+ item.editor = edit
item.enabled = true
item.language = "en_US"
}
@@ -83,6 +84,25 @@ Item {
compare(a.status, "ready")
}
+ function test_inspection_skips_non_prose_and_follows_edits() {
+ var a = adapter()
+ if (!a) return
+ var chunks = ["sam@example.com", "first.last+tag@sub.example.co.uk",
+ "https://x.y/recieve?teh=wrod#shedule", "www.x.y/wrod", "mailto:sam", "wrod-".repeat(10000)]
+ for (var i = 0; i < chunks.length; i++) {
+ edit.text = "<" + chunks[i] + "> mispelled "
+ var at = edit.text.indexOf("@")
+ if (at < 0) at = edit.text.indexOf("wrod")
+ if (at < 0) at = 1
+ var info = a.inspect(at)
+ compare(info.misspelled, false)
+ compare(info.suggestions.length, 0)
+ compare(a.inspect(edit.text.indexOf("mispelled")).misspelled, true)
+ }
+ edit.text = "mispelled "
+ compare(a.inspect(2).misspelled, true, "non-prose does not poison later inspection")
+ }
+
function test_inspect_word_misspelling_and_suggestions() {
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 9ac3bd4..9e587d6 100644
--- a/ui/tests/qml/tst_spellcheck_composer.qml
+++ b/ui/tests/qml/tst_spellcheck_composer.qml
@@ -140,6 +140,54 @@ Item {
compare(compose.spellingPass, null)
}
+ function test_reply_addresses_and_links_are_not_underlined_but_adjacent_typos_are() {
+ if (!readyAdapter()) return
+ var body = named(compose, "compose-body-editor")
+ body.text = "On Fri, Sam Rivera wrote: shedule https://x.y/recieve?teh=wrod#shedule. "
+ compose.refreshSpellingRanges()
+ tryVerify(function() { return compose.spellingPass && compose.spellingPass.done })
+ var typo = body.text.indexOf("shedule")
+ var address = body.text.indexOf("sam@example.com")
+ var link = body.text.indexOf("https:")
+ var found = false
+ for (var i = 0; i < compose.spellingRanges.length; i++) {
+ var range = compose.spellingRanges[i]
+ if (range.start === typo) found = true
+ verify(range.end <= address || range.start >= address + 15)
+ verify(range.end <= link)
+ }
+ verify(found, "a real prose typo on the same line still has an underline")
+ var before = body.text
+ var box = body.positionToRectangle(address + 1)
+ mouseClick(body, box.x + 2, box.y + box.height / 2, Qt.RightButton)
+ var menu = named(compose, "compose-text-menu")
+ tryCompare(menu, "opened", true)
+ compare(menu.spellingMisspelled, false)
+ compare(menu.spellingSuggestions.length, 0)
+ compare(menu.ignoreWordRow.visible, false)
+ menu.close()
+ body.cursorPosition = link + 14
+ body.forceActiveFocus()
+ keyClick(Qt.Key_Period, Qt.ControlModifier)
+ wait(20)
+ compare(menu.opened, false, "Ctrl+. has no correction menu for a link")
+ compare(compose.openSpellingAtCaret(), false)
+ compare(body.text, before)
+ }
+
+ function test_non_prose_never_warms_the_dictionary_cache() {
+ var adapter = readyAdapter()
+ if (!adapter) return
+ var body = named(compose, "compose-body-editor")
+ body.text = " https://x.y/recieve?teh=wrod#shedule www.x.y/wrod mailto:sam "
+ adapter.resetCache()
+ compose.refreshSpellingRanges()
+ tryVerify(function() { return compose.spellingPass && compose.spellingPass.done })
+ compare(adapter.verdictCache.size, 0)
+ compare(compose.spellingRanges.length, 0)
+ compare(compose.spellingDelegateCount, 0)
+ }
+
function test_quoted_reply_lines_never_reach_the_checker() {
var adapter = readyAdapter()
if (!adapter) return
diff --git a/ui/tests/test_spelling.js b/ui/tests/test_spelling.js
index 88e91c7..7132205 100644
--- a/ui/tests/test_spelling.js
+++ b/ui/tests/test_spelling.js
@@ -29,6 +29,88 @@ test("Ranges keep UTF-16 offsets, apostrophes, combining marks and repeated word
deepEqual(rules.misspelledRanges("'' ’ 😀 ", wrong), [])
})
+test("Email chunks skip every token without dictionary calls", () => {
+ const r = spelling()
+ for (const address of ["sam@example.com", "first.last+tag@sub.example.co.uk", "élise@exemple.fr"]) {
+ for (const wrap of [["", ""], ["<", ">"], ["(", ")"], ["[", "]"], ['"', '"'], ["'", "'"], [",", ";"]]) {
+ const text = "shedule " + wrap[0] + address + wrap[1] + " recieve "
+ const seen = []
+ const ranges = r.misspelledRanges(text, word => { seen.push(word); return true })
+ assert.deepEqual(seen, ["shedule", "recieve"])
+ deepEqual(ranges, [{ start: 0, end: 7 }, { start: text.indexOf("recieve"), end: text.indexOf("recieve") + 7 }])
+ assert.equal(r.nonProseAt(text, text.indexOf(address)), true)
+ }
+ }
+})
+
+test("Link chunks skip schemes, mailto, www and misspelled paths/query/fragment", () => {
+ const r = spelling()
+ for (const link of ["http://x.y/recieve", "https://x.y/recieve?teh=wrod#shedule",
+ "ftp://x.y/wrod", "file:///recieve", "a+b.c-d://wrod", "HTTPS://x.y/wrod",
+ "www.x.y/recieve", "mailto:sam", "mailto:sam@example.com"]) {
+ for (const suffix of [" ", ". ", ", ", "; "]) {
+ const text = "shedule (" + link + ")" + suffix + "recieve "
+ const seen = []
+ r.misspelledRanges(text, word => { seen.push(word); return true })
+ assert.deepEqual(seen, ["shedule", "recieve"], text)
+ assert.equal(r.nonProseAt(text, text.indexOf(link)), true)
+ }
+ }
+ deepEqual(r.misspelledRanges("see https://x.y/recieve. ", w => w !== "see"), [])
+})
+
+test("Incomplete @ and non-link prefixes do not suppress prose", () => {
+ const r = spelling()
+ for (const text of ["@ noon ", "me@ ", "@me ", "me@.noon ", "1http://wrod ", "http:wrod "]) {
+ assert.equal(r.nonProseAt(text, text.indexOf(" ") - 1), false, text)
+ const seen = []
+ r.misspelledRanges(text, word => { seen.push(word); return true })
+ assert.ok(seen.length > 0, text)
+ }
+ const seen = []
+ r.misspelledRanges("Thanks shedule, sam@example.com ", word => { seen.push(word); return true })
+ assert.deepEqual(seen, ["Thanks", "shedule"])
+})
+
+test("Non-prose spans survive window edges and caret ends", () => {
+ const r = spelling()
+ const text = "https://x.y/recieve?teh=wrod#shedule sam@example.com recieve "
+ for (const word of ["recieve", "teh", "wrod", "shedule", "sam", "example", "com"]) {
+ const at = text.indexOf(word)
+ for (const position of [at, at + word.length]) assert.equal(r.nonProseAt(text, position), true)
+ const window = r.wordWindow(text, at, at + word.length)
+ const pass = r.createPass(text, window, at, at + word.length, 0)
+ while (!pass.done) r.advancePass(pass, () => { throw Error("window fragment reached dictionary") }, () => 0)
+ }
+ assert.equal(r.nonProseAt(text, text.lastIndexOf("recieve")), false)
+})
+
+test("Overlong chunks are skipped with bounded scans and skipped words still yield", () => {
+ const r = spelling()
+ const cap = r.MAX_CHUNK_CHARACTERS
+ const chunk = "wrod-".repeat(20000)
+ for (const at of [0, 100, 50000, chunk.length - 1]) {
+ let reads = 0
+ const input = { length: chunk.length, charAt: index => { reads++; return chunk.charAt(index) } }
+ assert.equal(r.nonProseAt(input, at), true)
+ assert.ok(reads <= cap + 8, "the cap bounds character reads even in a huge chunk")
+ }
+ const exact = "-".repeat(cap - 4) + "wrod"
+ assert.equal(r.nonProseAt(exact + " ", cap - 2), false)
+ assert.equal(r.nonProseAt("-" + exact + " ", cap - 1), true)
+ const text = chunk + " shedule "
+ const window = { start: chunk.length - 40, end: text.length }
+ const pass = r.createPass(text, window, 0, text.length, 0)
+ const seen = []
+ while (!pass.done) r.advancePass(pass, w => { seen.push(w); return true }, () => 0)
+ assert.deepEqual(seen, ["shedule"])
+ const repeated = "sam@example.com ".repeat(10000)
+ const bounded = r.createPass(repeated, r.wordWindow(repeated, 0, repeated.length), 0, repeated.length, 0)
+ r.advancePass(bounded, () => { throw Error("address reached dictionary") }, () => 0)
+ assert.equal(bounded.done, false)
+ assert.ok(bounded.index <= r.MAX_SLICE_CHARACTERS)
+})
+
test("Settings default to enabled system language and only explicit false disables checking", () => {
const rules = spelling()
for (const settings of [null, {}, { spellingEnabled: "no" }, { spellingEnabled: 0 }]) {
From 98f313afff928e7ccf6beb2344b8bbce26b66ff8 Mon Sep 17 00:00:00 2001
From: Chris Gray <216301595+latentoperator@users.noreply.github.com>
Date: Sun, 11 Oct 2026 22:35:35 -0500
Subject: [PATCH 27/88] Fix spelling underlines disappearing during typing and
scrolling
---
ui/components/ComposeView.qml | 43 +++++++++++++---
ui/tests/qml/tst_spellcheck_composer.qml | 62 +++++++++++++++++++++++-
2 files changed, 95 insertions(+), 10 deletions(-)
diff --git a/ui/components/ComposeView.qml b/ui/components/ComposeView.qml
index 2acd23f..28990d0 100644
--- a/ui/components/ComposeView.qml
+++ b/ui/components/ComposeView.qml
@@ -88,8 +88,24 @@ DropArea {
spellingGeneration += 1
spellingPass = null
spellingSlice.stop()
- spellingSegments.clear()
- spellingRanges = []
+ }
+
+ // Keep only unchanged prefixes; native string comparisons avoid a body scan.
+ // Include the delimiter so typing at a word's end drops that word too.
+ function retainSpellingBeforeEdit(text, previous) {
+ var low = 0
+ var high = spellingRanges.length
+ while (low < high) {
+ var mid = Math.floor((low + high) / 2)
+ var end = spellingRanges[mid].end + 1
+ if (text.substring(0, end) === previous.substring(0, end)) low = mid + 1
+ else high = mid
+ }
+ spellingRanges = spellingRanges.slice(0, low)
+ var keptEnd = low > 0 ? spellingRanges[low - 1].end : 0
+ while (spellingSegments.count > 0
+ && spellingSegments.get(spellingSegments.count - 1).wordEnd > keptEnd)
+ spellingSegments.remove(spellingSegments.count - 1)
}
function scheduleSpellingLayout() {
@@ -100,7 +116,11 @@ DropArea {
function refreshSpellingRanges() {
cancelSpellingPass()
var adapter = spellingAdapter
- if (!adapter || !spellingAvailable || !spellingEnabled || bodyFlick.height <= 0) return
+ if (!adapter || !spellingAvailable || !spellingEnabled || bodyFlick.height <= 0) {
+ spellingSegments.clear()
+ spellingRanges = []
+ return
+ }
var text = bodyEdit.text
var top = Math.max(0, bodyFlick.contentY)
var bottom = top + bodyFlick.height
@@ -113,6 +133,7 @@ DropArea {
spellingWindow = Spelling.wordWindow(text, start, end)
spellingPass = Spelling.createPass(text, spellingWindow, visibleStart, visibleEnd, bodyRevision)
spellingPass.generation = spellingGeneration
+ spellingPass.segments = []
spellingSlice.restart()
}
@@ -128,21 +149,26 @@ DropArea {
var segments = Spelling.underlineSegments(range.start, range.end,
function(position) { return bodyEdit.positionToRectangle(position) },
bodyEdit.leftPadding, bodyEdit.width - bodyEdit.rightPadding)
- var before = spellingSegments.count
- for (var i = 0; i < segments.length && spellingSegments.count < Spelling.MAX_UNDERLINE_RANGES; i++) {
+ var before = pass.segments.length
+ for (var i = 0; i < segments.length && pass.segments.length < Spelling.MAX_UNDERLINE_RANGES; i++) {
// Margin words warm the checker cache; only viewport geometry paints.
var segment = segments[i]
if (segment.y >= bodyFlick.contentY && segment.y < bodyFlick.contentY + bodyFlick.height)
- spellingSegments.append({ segmentX: segment.x, segmentY: segment.y, segmentWidth: segment.width })
+ pass.segments.push({ segmentX: segment.x, segmentY: segment.y,
+ segmentWidth: segment.width, wordEnd: range.end })
}
- return spellingSegments.count > before
+ return pass.segments.length > before
})
if (pass.revision !== bodyRevision || pass.generation !== spellingGeneration) {
cancelSpellingPass()
return
}
+ if (!pass.done) { spellingSlice.restart(); return }
+ // Publish a complete view without an empty intermediate frame or model.
+ for (var i = 0; i < pass.segments.length; i++) spellingSegments.set(i, pass.segments[i])
+ if (spellingSegments.count > pass.segments.length)
+ spellingSegments.remove(pass.segments.length, spellingSegments.count - pass.segments.length)
spellingRanges = pass.ranges.slice()
- if (!pass.done) spellingSlice.restart()
}
onBodyRevisionChanged: cancelSpellingPass()
@@ -2066,6 +2092,7 @@ DropArea {
// Sonnet can emit textChanged while rehighlighting an unchanged
// document. Only a plain-text change edits the draft or its revision.
if (text === lastPlainText) return
+ root.retainSpellingBeforeEdit(text, lastPlainText)
lastPlainText = text
root.noteDraftChanged()
if (!root.settingBodyText && activeFocus) {
diff --git a/ui/tests/qml/tst_spellcheck_composer.qml b/ui/tests/qml/tst_spellcheck_composer.qml
index 9e587d6..944d79a 100644
--- a/ui/tests/qml/tst_spellcheck_composer.qml
+++ b/ui/tests/qml/tst_spellcheck_composer.qml
@@ -5,11 +5,18 @@ import "../../compose/Spelling.js" as Spelling
// 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.
+// disabled. These tests also exercise the visible, bounded underline passes.
Item {
width: 900
height: 600
+ property bool watchUnderlines: false
+ property int minimumUnderlines: 0
+ Connections {
+ target: compose
+ function onSpellingDelegateCountChanged() {
+ if (watchUnderlines) minimumUnderlines = Math.min(minimumUnderlines, compose.spellingDelegateCount)
+ }
+ }
QtObject {
id: mailService
@@ -78,6 +85,7 @@ Item {
}
function init() {
+ watchUnderlines = false
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.
@@ -120,6 +128,56 @@ Item {
verify(compose.spellingRanges[0].start > 90000)
}
+ function test_typing_keeps_underlines_before_the_caret_until_replaced() {
+ if (!readyAdapter()) return
+ var body = named(compose, "compose-body-editor")
+ body.text = "mispelled here wrod here "
+ compose.refreshSpellingRanges()
+ tryVerify(function() { return compose.spellingPass && compose.spellingPass.done })
+ compare(compose.spellingRanges.length, 2)
+ minimumUnderlines = compose.spellingDelegateCount
+ watchUnderlines = true
+ body.cursorPosition = body.text.indexOf("wrod") + 2
+ body.forceActiveFocus()
+ keyClick(Qt.Key_X, Qt.NoModifier, 0)
+ compare(compose.spellingRanges.length, 1, "only the unchanged prefix is retained")
+ compare(compose.spellingRanges[0].start, 0)
+ tryVerify(function() { return compose.spellingPass && compose.spellingPass.done })
+ verify(minimumUnderlines > 0, "underlines never disappear during typing or publication")
+ compare(compose.spellingRanges[0].start, 0)
+ }
+
+ function test_scrolling_keeps_underlines_until_the_next_pass() {
+ if (!readyAdapter()) return
+ var body = named(compose, "compose-body-editor")
+ var flick = named(compose, "compose-body")
+ body.text = "mispelled here wrod here \n".repeat(100)
+ compose.refreshSpellingRanges()
+ tryVerify(function() { return compose.spellingPass && compose.spellingPass.done })
+ var underline = named(compose, "spelling-underline")
+ var contentY = underline.y
+ minimumUnderlines = compose.spellingDelegateCount
+ watchUnderlines = true
+ flick.contentY += 20
+ compare(underline.y, contentY, "segments stay in content coordinates")
+ verify(compose.spellingDelegateCount > 0, "the scroll step keeps the existing model")
+ tryVerify(function() { return compose.spellingPass && compose.spellingPass.done })
+ verify(minimumUnderlines > 0, "scrolling and publication never empty the model")
+ }
+
+ function test_removing_a_word_drops_its_underline() {
+ if (!readyAdapter()) return
+ var body = named(compose, "compose-body-editor")
+ body.text = "mispelled here wrod here "
+ compose.refreshSpellingRanges()
+ tryVerify(function() { return compose.spellingPass && compose.spellingPass.done })
+ compare(compose.spellingRanges.length, 2)
+ body.remove(15, 20)
+ tryVerify(function() { return compose.spellingPass && compose.spellingPass.done })
+ compare(compose.spellingRanges, [{ start: 0, end: 9 }])
+ compare(compose.spellingDelegateCount, 1)
+ }
+
function test_revision_change_abandons_an_incomplete_pass_before_it_can_paint() {
var adapter = readyAdapter()
if (!adapter) return
From a7a28db8433439d4617a08182a956539dc0dd881 Mon Sep 17 00:00:00 2001
From: Chris Gray <216301595+latentoperator@users.noreply.github.com>
Date: Sun, 11 Oct 2026 22:37:16 -0500
Subject: [PATCH 28/88] Fix disabled spelling loading and host-specific setup
guidance
---
ui/components/SettingsPage.qml | 18 +++++---
ui/compose/SpellingState.qml | 6 +--
ui/tests/qml/tst_service_settings.qml | 60 +++++++++++++++++++++++++++
3 files changed, 76 insertions(+), 8 deletions(-)
diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml
index 9372503..8dd0c6e 100644
--- a/ui/components/SettingsPage.qml
+++ b/ui/components/SettingsPage.qml
@@ -33,6 +33,8 @@ Column {
signal openCalendarRequested()
signal calendarSignInRequested(int index)
+ readonly property string spellingLanguage: Spelling.resolveLanguage(
+ service ? service.spellingLanguage : "", Qt.locale().name)
readonly property var accounts: service ? service.accountSummaries : []
// A separate list on purpose: accountSummaries carries live mailbox state and
// is replaced on a poll, which would rebuild the field being typed in.
@@ -873,8 +875,10 @@ Column {
Text {
objectName: "spellingLanguagePolicy"
width: parent.width
- text: "Checking spelling in "
- + (Spelling.resolveLanguage(root.service ? root.service.spellingLanguage : "", Qt.locale().name) || Qt.locale().name)
+ id: spellingLanguagePolicy
+ text: root.spellingLanguage === ""
+ ? "No system language is set; choose one with the spellingLanguage setting."
+ : "Checking spelling in " + root.spellingLanguage
+ (root.service && Spelling.decodeSettings(root.service.settings).language !== ""
? " (set in settings)." : " (system language).")
color: root.dimColor
@@ -891,10 +895,14 @@ Column {
Text {
objectName: "spellingNeedsSetup"
width: parent.width
- visible: !!root.service && !root.service.spellingAvailable
- text: root.service && root.service.spellingStatus === "no-module"
+ visible: !!root.service && root.service.spellingEnabled !== false
+ && !root.service.spellingAvailable && root.service.spellingStatus !== "loading"
+ text: root.service && root.service.standalone === true
+ ? "Spell-checking is not available in this build."
+ : root.service && root.service.spellingStatus === "no-module"
? "Spell-checking is unavailable: install the Sonnet QML module, then restart Omamail."
- : "The " + (Spelling.resolveLanguage(root.service ? root.service.spellingLanguage : "", Qt.locale().name) || Qt.locale().name)
+ : root.spellingLanguage === "" ? spellingLanguagePolicy.text
+ : "The " + root.spellingLanguage
+ " dictionary is not installed. Install the matching Hunspell "
+ "dictionary package (hunspell-, for example hunspell-de), then restart Omamail."
color: root.accentColor
diff --git a/ui/compose/SpellingState.qml b/ui/compose/SpellingState.qml
index 80040ce..a478811 100644
--- a/ui/compose/SpellingState.qml
+++ b/ui/compose/SpellingState.qml
@@ -13,11 +13,11 @@ Item {
readonly property string language: Spelling.resolveLanguage(languageOverride, Qt.locale().name)
readonly property bool available: probe.status === Loader.Ready
&& probe.item !== null && probe.item.available
- readonly property string status: probe.status === Loader.Error
- ? "no-module" : (probe.item ? probe.item.status : "loading")
+ readonly property string status: !enabledRequest ? "disabled" : (probe.status === Loader.Error
+ ? "no-module" : (probe.item ? probe.item.status : "loading"))
// Sonnet enumerates dictionaries once per process. Installing one requires
// restarting Omamail; a new adapter alone cannot discover it.
- Loader { id: probe; source: "SpellcheckAdapter.qml" }
+ Loader { id: probe; active: root.enabledRequest; source: "SpellcheckAdapter.qml" }
Binding {
target: probe.item
property: "language"
diff --git a/ui/tests/qml/tst_service_settings.qml b/ui/tests/qml/tst_service_settings.qml
index 5c6a366..d4b3f6a 100644
--- a/ui/tests/qml/tst_service_settings.qml
+++ b/ui/tests/qml/tst_service_settings.qml
@@ -1,6 +1,7 @@
import QtQuick 2.15
import QtTest 1.3
import "../.." as Omamail
+import "../../components" as Components
import "../../account/Unified.js" as Unified
import "../../compose/Spelling.js" as Spelling
@@ -32,6 +33,18 @@ Item {
manifest: ({ id: "omamail" })
}
+ Components.SettingsPage {
+ id: page
+ width: parent.width
+ service: mailService
+ calendarController: null
+ textColor: Qt.rgba(1, 1, 1, 1)
+ dimColor: Qt.rgba(0.6, 0.6, 0.6, 1)
+ accentColor: Qt.rgba(1, 0.5, 0, 1)
+ urgentColor: Qt.rgba(1, 0.5, 0, 1)
+ panelFontFamily: "sans"
+ }
+
TestCase {
name: "ServiceSettings"
@@ -191,9 +204,56 @@ Item {
compare(mailService.spellingLanguage, Spelling.resolveLanguage("", Qt.locale().name))
}
+ function test_spelling_setup_guidance_data() {
+ return [
+ { tag: "plugin-module", standalone: false, status: "no-module", enabled: true, message: "install the Sonnet QML module" },
+ { tag: "plugin-dictionary", standalone: false, status: "no-dictionary", enabled: true, message: "The en_US dictionary is not installed" },
+ { tag: "standalone-module", standalone: true, status: "no-module", enabled: true, message: "Spell-checking is not available in this build." },
+ { tag: "standalone-dictionary", standalone: true, status: "no-dictionary", enabled: true, message: "Spell-checking is not available in this build." },
+ { tag: "off", standalone: false, status: "disabled", enabled: false, message: "" },
+ { tag: "loading", standalone: false, status: "loading", enabled: true, message: "" }
+ ]
+ }
+ function test_spelling_setup_guidance(data) {
+ try {
+ page.service = { standalone: data.standalone, spellingEnabled: data.enabled,
+ spellingStatus: data.status, spellingAvailable: false, spellingLanguage: "en_US",
+ settings: { spellingLanguage: "en_US" }, accountSummaries: [] }
+ var notice = findChild(page, "spellingNeedsSetup")
+ compare(notice.visible, data.message !== "")
+ if (data.message !== "") verify(notice.text.indexOf(data.message) >= 0)
+ } finally { page.service = mailService }
+ }
+ function test_unset_system_language_guidance() {
+ if (Spelling.validLanguage(Qt.locale().name)) { skip("requires C/POSIX system locale"); return }
+ mailService.applySettings({ spellingLanguage: "" })
+ compare(mailService.spellingLanguage, "")
+ compare(findChild(page, "spellingLanguagePolicy").text,
+ "No system language is set; choose one with the spellingLanguage setting.")
+ compare(findChild(page, "spellingNeedsSetup").text.indexOf("The C dictionary"), -1)
+ }
+
+ function test_spelling_off_unloads_the_probe_and_hides_setup_warning() {
+ mailService.applySettings({ spellingEnabled: false })
+ compare(mailService.spellingStatus, "disabled")
+ compare(mailService.spellingAvailable, false)
+ var state = null
+ for (var i = 0; i < mailService.children.length; i++) {
+ if (mailService.children[i].enabledRequest !== undefined) state = mailService.children[i]
+ }
+ verify(state)
+ var probe = state.children[0]
+ compare(probe.active, false)
+ compare(probe.item, null)
+ compare(probe.status, Loader.Null)
+ compare(findChild(page, "spellingNeedsSetup").visible, false)
+ mailService.applySettings({})
+ }
+
// 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() {
+ mailService.applySettings({})
tryVerify(function() {
var status = mailService.spellingStatus
return status === "ready" || status === "no-dictionary" || status === "no-module"
From afe3e8f033e1887182a043adf35fb3f170071b5b Mon Sep 17 00:00:00 2001
From: Chris Gray <216301595+latentoperator@users.noreply.github.com>
Date: Sun, 11 Oct 2026 22:37:16 -0500
Subject: [PATCH 29/88] Clarify Sonnet missing-dictionary language restoration
---
ui/compose/SpellcheckAdapter.qml | 10 +++-------
1 file changed, 3 insertions(+), 7 deletions(-)
diff --git a/ui/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml
index 7223783..4eed3e1 100644
--- a/ui/compose/SpellcheckAdapter.qml
+++ b/ui/compose/SpellcheckAdapter.qml
@@ -33,13 +33,9 @@ Item {
// 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.
+ // On a missing dictionary Sonnet sets spellCheckerFound false, restores the
+ // previous language and returns without emitting currentLanguageChanged.
+ // Read both properties imperatively after the call, not through a binding.
property bool requestedLanguageAvailable: false
readonly property bool available: requestedLanguageAvailable
// "ready", "disabled", or "no-dictionary". A missing module is reported by
From 8699f1c592c892be6b669f21bffcc9f7dbfa7e8e Mon Sep 17 00:00:00 2001
From: Chris Gray <216301595+latentoperator@users.noreply.github.com>
Date: Sun, 11 Oct 2026 22:38:39 -0500
Subject: [PATCH 30/88] Remove redundant spelling probes and unused APIs
---
ui/Service.qml | 1 -
ui/compose/SpellcheckAdapter.qml | 9 --
ui/compose/Spelling.js | 10 +-
ui/tests/qml/SpellcheckProbe.qml | 41 --------
ui/tests/qml/tst_service_settings.qml | 10 +-
ui/tests/qml/tst_spellcheck_adapter.qml | 31 +-----
ui/tests/qml/tst_spellcheck_composer.qml | 4 +-
ui/tests/qml/tst_spellcheck_probe.qml | 115 -----------------------
ui/tests/test_spelling.js | 47 +++++----
9 files changed, 40 insertions(+), 228 deletions(-)
delete mode 100644 ui/tests/qml/SpellcheckProbe.qml
delete mode 100644 ui/tests/qml/tst_spellcheck_probe.qml
diff --git a/ui/Service.qml b/ui/Service.qml
index 6d3b871..01a9699 100644
--- a/ui/Service.qml
+++ b/ui/Service.qml
@@ -697,7 +697,6 @@ Item {
readonly property alias spellingAvailable: spelling.available
readonly property alias spellingStatus: spelling.status
function setSpellingEnabled(value) { persistSetting("spellingEnabled", value !== false) }
- function setSpellingLanguage(value) { persistSetting("spellingLanguage", String(value || "")) }
// ---------------------------------------------------------- the accounts
diff --git a/ui/compose/SpellcheckAdapter.qml b/ui/compose/SpellcheckAdapter.qml
index 4eed3e1..0ce49c7 100644
--- a/ui/compose/SpellcheckAdapter.qml
+++ b/ui/compose/SpellcheckAdapter.qml
@@ -93,15 +93,6 @@ Item {
Session.changed()
}
- // Only completed words receive underlines; Sonnet supplies the decision,
- // while the shared rule keeps positions and completeness testable without Qt.
- function misspelledRanges(text) {
- if (!available || !enabled) return []
- return Spelling.misspelledRanges(text, function(word) {
- return adapter.isMisspelled(word)
- })
- }
-
function applySettings() {
resetCache()
// The request is attempted even when the previous one reverted: a later
diff --git a/ui/compose/Spelling.js b/ui/compose/Spelling.js
index 460343d..0880175 100644
--- a/ui/compose/Spelling.js
+++ b/ui/compose/Spelling.js
@@ -63,7 +63,7 @@ function nonProseAt(text, position) {
to += 1
}
var chunk = text.substring(from, to)
- if (/^(?:[A-Za-z][A-Za-z0-9+.-]*:\/\/|mailto:|www\.)/i.test(chunk)) return true
+ if (chunk.indexOf("://") >= 0 || /^(?:mailto:|www\.)/i.test(chunk)) return true
var email = chunk.indexOf("@")
while (email >= 0) {
if (isWordChar(chunk.charAt(email - 1)) && isWordChar(chunk.charAt(email + 1))) return true
@@ -145,14 +145,6 @@ function cachedVerdict(cache, word, check) {
return verdict
}
-// Small-text helper for non-visual callers; production uses incremental passes.
-function misspelledRanges(text, isMisspelled) {
- var window = wordWindow(text, 0, text.length)
- var pass = createPass(text, window, window.start, window.end, 0)
- while (!pass.done) advancePass(pass, isMisspelled, function() { return 0 }, null)
- return pass.ranges
-}
-
function isWordChar(character) {
// Letters/digits in common scripts and apostrophes within words. Surrogate
// halves (such as emoji) delimit words without changing UTF-16 positions.
diff --git a/ui/tests/qml/SpellcheckProbe.qml b/ui/tests/qml/SpellcheckProbe.qml
deleted file mode 100644
index b2172ba..0000000
--- a/ui/tests/qml/SpellcheckProbe.qml
+++ /dev/null
@@ -1,41 +0,0 @@
-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.
-//
-// This isolates the Sonnet runtime behavior used by the production adapter.
-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) }
-
- onEditorChanged: if (editor !== null) highlighter.document = editor.textDocument
-
- Sonnet.SpellcheckHighlighter {
- id: highlighter
- 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 d4b3f6a..6e9ebc4 100644
--- a/ui/tests/qml/tst_service_settings.qml
+++ b/ui/tests/qml/tst_service_settings.qml
@@ -188,7 +188,7 @@ Item {
mailService.applySettings({ spellingEnabled: "no" })
compare(mailService.spellingEnabled, true)
- mailService.setSpellingLanguage("en_GB")
+ mailService.persistSetting("spellingLanguage", "en_GB")
compare(mailService.spellingLanguage, "en_GB")
compare(shellStore.updatedEntry.spellingLanguage, "en_GB")
}
@@ -199,7 +199,7 @@ Item {
mailService.applySettings({ spellingLanguage: values[i] })
compare(mailService.spellingLanguage, Spelling.resolveLanguage("", Qt.locale().name))
}
- mailService.setSpellingLanguage("")
+ mailService.persistSetting("spellingLanguage", "")
compare(shellStore.updatedEntry.spellingLanguage, "")
compare(mailService.spellingLanguage, Spelling.resolveLanguage("", Qt.locale().name))
}
@@ -269,15 +269,15 @@ Item {
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")
+ mailService.persistSetting("spellingLanguage", "en_US")
tryVerify(function() {
return mailService.spellingStatus === "ready" || mailService.spellingStatus === "no-dictionary"
}, 3000)
if (!mailService.spellingAvailable) { skip("en_US dictionary is not installed"); return }
- mailService.setSpellingLanguage("zz_ZZ")
+ mailService.persistSetting("spellingLanguage", "zz_ZZ")
tryVerify(function() { return mailService.spellingStatus === "no-dictionary" }, 3000)
compare(mailService.spellingAvailable, false)
- mailService.setSpellingLanguage("en_US")
+ mailService.persistSetting("spellingLanguage", "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
index d6158f1..bb7b157 100644
--- a/ui/tests/qml/tst_spellcheck_adapter.qml
+++ b/ui/tests/qml/tst_spellcheck_adapter.qml
@@ -88,7 +88,8 @@ Item {
var a = adapter()
if (!a) return
var chunks = ["sam@example.com", "first.last+tag@sub.example.co.uk",
- "https://x.y/recieve?teh=wrod#shedule", "www.x.y/wrod", "mailto:sam", "wrod-".repeat(10000)]
+ "https://x.y/recieve?teh=wrod#shedule", "Re:http://x.y/recieve", "see:https://x.y/wrod",
+ "www.x.y/wrod", "mailto:sam", "wrod-".repeat(10000)]
for (var i = 0; i < chunks.length; i++) {
edit.text = "<" + chunks[i] + "> mispelled "
var at = edit.text.indexOf("@")
@@ -116,6 +117,9 @@ Item {
// A correct word is not reported as misspelled.
var ok = a.inspect(edit.text.indexOf("sentence"))
compare(ok.misspelled, false)
+ compare(ok.suggestions.length, 0)
+ compare(a.isMisspelled("don't"), false)
+ verify(a.inspect(edit.text.indexOf("mispelled")).suggestions.length > 0)
}
function test_correction_is_undo_safe_and_does_not_touch_other_words() {
@@ -139,31 +143,6 @@ 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_session_ignore_treats_a_word_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 944d79a..8af6315 100644
--- a/ui/tests/qml/tst_spellcheck_composer.qml
+++ b/ui/tests/qml/tst_spellcheck_composer.qml
@@ -553,9 +553,7 @@ Item {
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")
+ compare(compose.spellingRanges.length, 0, "en_GB accepts all the British spellings")
verify(compose.spellingRanges.length < usRanges, "en_GB accepts the British spellings")
}
}
diff --git a/ui/tests/qml/tst_spellcheck_probe.qml b/ui/tests/qml/tst_spellcheck_probe.qml
deleted file mode 100644
index 8f5fa1f..0000000
--- a/ui/tests/qml/tst_spellcheck_probe.qml
+++ /dev/null
@@ -1,115 +0,0 @@
-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/test_spelling.js b/ui/tests/test_spelling.js
index 7132205..cee554e 100644
--- a/ui/tests/test_spelling.js
+++ b/ui/tests/test_spelling.js
@@ -4,29 +4,35 @@ const { load, deepEqual } = require("./load")
// Load inside each test so the baseline demonstrates all four missing rules.
function spelling() { return load("compose/Spelling.js") }
+function collectRanges(rules, text, checker) {
+ const window = rules.wordWindow(text, 0, text.length)
+ const pass = rules.createPass(text, window, window.start, window.end, 0)
+ while (!pass.done) rules.advancePass(pass, checker, () => 0)
+ return pass.ranges
+}
test("Only completed body words are checked", () => {
const rules = spelling()
const seen = []
const checker = word => { seen.push(word); return true }
- deepEqual(rules.misspelledRanges("mispelled", checker), [])
+ deepEqual(collectRanges(rules, "mispelled", checker), [])
assert.equal(seen.length, 0, "the unfinished word never reaches the checker")
for (const delimiter of [" ", ".", ",", "\n", "\t"]) {
- deepEqual(rules.misspelledRanges("mispelled" + delimiter, checker), [{ start: 0, end: 9 }])
+ deepEqual(collectRanges(rules, "mispelled" + delimiter, checker), [{ start: 0, end: 9 }])
}
- deepEqual(rules.misspelledRanges("mispelled wrod", checker), [{ start: 0, end: 9 }])
- deepEqual(rules.misspelledRanges("", checker), [])
+ deepEqual(collectRanges(rules, "mispelled wrod", checker), [{ start: 0, end: 9 }])
+ deepEqual(collectRanges(rules, "", checker), [])
})
test("Ranges keep UTF-16 offsets, apostrophes, combining marks and repeated words", () => {
const rules = spelling()
const wrong = word => word !== "correct"
const text = "📨 'wrod', correct wrod.\n"
- deepEqual(rules.misspelledRanges(text, wrong), [{ start: 4, end: 8 }, { start: 19, end: 23 }])
- deepEqual(rules.misspelledRanges("‘can’t’ cafe\u0301 Ελληνικά русский ", wrong), [
+ deepEqual(collectRanges(rules, text, wrong), [{ start: 4, end: 8 }, { start: 19, end: 23 }])
+ deepEqual(collectRanges(rules, "‘can’t’ cafe\u0301 Ελληνικά русский ", wrong), [
{ start: 1, end: 6 }, { start: 8, end: 13 }, { start: 14, end: 22 }, { start: 23, end: 30 }
])
- deepEqual(rules.misspelledRanges("'' ’ 😀 ", wrong), [])
+ deepEqual(collectRanges(rules, "'' ’ 😀 ", wrong), [])
})
test("Email chunks skip every token without dictionary calls", () => {
@@ -35,7 +41,7 @@ test("Email chunks skip every token without dictionary calls", () => {
for (const wrap of [["", ""], ["<", ">"], ["(", ")"], ["[", "]"], ['"', '"'], ["'", "'"], [",", ";"]]) {
const text = "shedule " + wrap[0] + address + wrap[1] + " recieve "
const seen = []
- const ranges = r.misspelledRanges(text, word => { seen.push(word); return true })
+ const ranges = collectRanges(r, text, word => { seen.push(word); return true })
assert.deepEqual(seen, ["shedule", "recieve"])
deepEqual(ranges, [{ start: 0, end: 7 }, { start: text.indexOf("recieve"), end: text.indexOf("recieve") + 7 }])
assert.equal(r.nonProseAt(text, text.indexOf(address)), true)
@@ -47,28 +53,28 @@ test("Link chunks skip schemes, mailto, www and misspelled paths/query/fragment"
const r = spelling()
for (const link of ["http://x.y/recieve", "https://x.y/recieve?teh=wrod#shedule",
"ftp://x.y/wrod", "file:///recieve", "a+b.c-d://wrod", "HTTPS://x.y/wrod",
- "www.x.y/recieve", "mailto:sam", "mailto:sam@example.com"]) {
+ "www.x.y/recieve", "mailto:sam", "mailto:sam@example.com", "Re:http://x.y/recieve", "see:https://x.y/wrod", "1http://wrod"]) {
for (const suffix of [" ", ". ", ", ", "; "]) {
const text = "shedule (" + link + ")" + suffix + "recieve "
const seen = []
- r.misspelledRanges(text, word => { seen.push(word); return true })
+ collectRanges(r, text, word => { seen.push(word); return true })
assert.deepEqual(seen, ["shedule", "recieve"], text)
assert.equal(r.nonProseAt(text, text.indexOf(link)), true)
}
}
- deepEqual(r.misspelledRanges("see https://x.y/recieve. ", w => w !== "see"), [])
+ deepEqual(collectRanges(r, "see https://x.y/recieve. ", w => w !== "see"), [])
})
test("Incomplete @ and non-link prefixes do not suppress prose", () => {
const r = spelling()
- for (const text of ["@ noon ", "me@ ", "@me ", "me@.noon ", "1http://wrod ", "http:wrod "]) {
+ for (const text of ["@ noon ", "me@ ", "@me ", "me@.noon ", "http:wrod "]) {
assert.equal(r.nonProseAt(text, text.indexOf(" ") - 1), false, text)
const seen = []
- r.misspelledRanges(text, word => { seen.push(word); return true })
+ collectRanges(r, text, word => { seen.push(word); return true })
assert.ok(seen.length > 0, text)
}
const seen = []
- r.misspelledRanges("Thanks shedule, sam@example.com ", word => { seen.push(word); return true })
+ collectRanges(r, "Thanks shedule, sam@example.com ", word => { seen.push(word); return true })
assert.deepEqual(seen, ["Thanks", "shedule"])
})
@@ -133,7 +139,10 @@ test("Language uses the system locale unless a short dictionary code overrides i
deepEqual(rules.decodeSettings({ spellingLanguage: hostile }), { enabled: true, language: "" })
}
assert.equal(rules.resolveLanguage("", "zz_ZZ"), "zz_ZZ", "no silent English fallback")
- assert.equal(rules.resolveLanguage("", "C"), "", "an unsupported system locale never reaches Sonnet")
+ for (const locale of ["C", "POSIX", ""]) {
+ assert.equal(rules.resolveLanguage("", locale), "", "an unset system locale never reaches Sonnet")
+ assert.equal(rules.resolveLanguage("de_DE", locale), "de_DE")
+ }
})
test("Windows expand whole words, preserve offsets and cap hostile tokens", () => {
@@ -145,18 +154,18 @@ test("Windows expand whole words, preserve offsets and cap hostile tokens", () =
assert.equal(text[window.end - 1], " ")
const hostile = "a".repeat(100000) + " wrod "
const seen = []
- r.misspelledRanges(hostile, w => { seen.push(w); return true })
+ collectRanges(r, hostile, w => { seen.push(w); return true })
assert.equal(seen.length, 0, "a huge token never reaches the native checker")
- r.misspelledRanges("a".repeat(129) + " wrod ", w => { seen.push(w); return true })
+ collectRanges(r, "a".repeat(129) + " wrod ", w => { seen.push(w); return true })
assert.deepEqual(seen, ["wrod"], "an over-budget token is skipped, not split")
- deepEqual(r.misspelledRanges("a".repeat(129) + "\nwrod ", () => true), [{ start: 130, end: 134 }])
+ deepEqual(collectRanges(r, "a".repeat(129) + "\nwrod ", () => true), [{ start: 130, end: 134 }])
})
test("Quoted lines skip lookup including an initial window in the middle of a quote", () => {
const r = spelling()
const text = "wrod \n > mispelled wrod \n\t> more wrod \nunquoted "
const seen = []
- const ranges = r.misspelledRanges(text, w => { seen.push(w); return true })
+ const ranges = collectRanges(r, text, w => { seen.push(w); return true })
assert.deepEqual(seen, ["wrod", "unquoted"])
assert.equal(ranges.length, 2)
assert.equal(r.quotedAt(text, text.indexOf("mispelled")), true)
From 6710e39d871319742aa3650078fdaffb8364e29e Mon Sep 17 00:00:00 2001
From: Jason Lee
Date: Mon, 19 Oct 2026 00:02:12 +0800
Subject: [PATCH 31/88] docs: Clarify contribution priorities and review
evidence (#379)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Omamail’s core product is substantially complete, so contribution
guidance should favor well-tested fixes to existing functionality and
explain the product cost of new features and providers. This updates
CONTRIBUTING.md to require labeled, detailed before-and-after
screenshots for every UI change and a detailed end-to-end recording for
complex features or workflows, so the maintainer can assess the result
without installing the app.
The review guidance skips drafts, distinguishes low-risk objective fixes
from product choices, and reserves context-menu changes, feature
placement, subjective design tradeoffs, large features, and
architectural direction for Jason’s confirmation. An objective
correction to an established convention still needs evidence and
regression checks. Approval never authorizes automated merging.
## Verification
Documentation-only change; no runtime code, tests, release
configuration, or deployment changes.
- Read current CONTRIBUTING.md, AGENTS.md, and the Makefile.
- Patch applicability against main
5db17740f99feb1252ba136db20d9fb67899cd91 passed with git apply --check.
- Checked added text for trailing whitespace, preserved Markdown fences,
and the repository’s 128 KiB file limit.
- A fresh independent reviewer found two wording gaps: approval needed
an explicit low-risk limit, and the objective exception needed to be
limited to established conventions. Both were corrected.
- make validate was not run: no working QML test runner or omarchy
executable was available for this task. The qmltestrunner command is a
qtchooser shim pointing to a missing runner. CI will be checked for the
published commit; this PR remains a draft.
- Security: PASS for this documentation-only diff; no runtime trust
boundary is changed.
Prepared with ChatGPT.
---
CONTRIBUTING.md | 22 ++++++++++++++++++----
1 file changed, 18 insertions(+), 4 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 41617fa..2ef4d01 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -39,6 +39,12 @@ it, described in terms of what it protects rather than what it opens.
[docs/KEYS.md](docs/KEYS.md) the key design — read that one before touching a
binding.
+## Contribution priorities
+
+Omamail's core product is substantially complete. Prefer fixes and refinements to existing functionality: reproducible bugs, small focused fixes, wording corrections, and performance improvements that preserve the intended design and workflow. New features and email providers are considered cautiously; explain the unmet need, why existing workflows are insufficient, and the ongoing interface and maintenance cost before expanding scope.
+
+Discuss large features, new providers, and substantial architectural changes with Jason before implementation. Passing tests does not establish that a capability belongs in the product.
+
## Project boundary
Omamail has two hosts over one shared mail and calendar implementation: a [Quickshell plugin hosted by `omarchy-shell`][omarchy-shell], and the Qt host under `app/`. A shared behavior belongs under `ui/` or in the Rust backend; `ui/Service.qml`, `ui/BarWidget.qml`, and `ui/App.qml` remain the Omarchy entry points, while `app/qml/Main.qml` supplies the standalone composition and adapters.
@@ -110,8 +116,9 @@ code once and watch it fail, and say so in the pull request.
*Popups* sections are the same rules where they are specific to this
codebase, and `tests/test_source.sh` enforces the part of them that grep can.
- **Test it on a screen, by hand. This is required and nothing substitutes for it.** For the plugin, register your development checkout with the Omarchy shell and follow [the development runtime instructions](docs/BACKEND-RUNTIME.md); click the envelope in the bar and drive the change with the mouse and keyboard in a light theme and a dark one, at both window sizes. For the standalone host, run `make app-run` on each affected platform and repeat the applicable mail, calendar, notification, and window checks. The offscreen QML tests prove focus and routing; they cannot see that a control hangs four pixels out of its row.
-- Put a screenshot in the pull request, and say which themes and sizes you
- drove it in.
+- **Every UI change requires clear, detailed visual evidence.** Attach labeled before-and-after screenshots of every changed view and relevant state, captured at matching window dimensions, theme, and scale. Explain what changed and identify the platforms, themes, and sizes tested. Screenshots must be legible enough to evaluate the actual layout, labels, and states; update them whenever the UI changes.
+- **Complex features and workflows also require a detailed screen recording.** Show the complete path from entry to result, including the relevant keyboard and mouse interactions and loading, empty, error, cancellation, or recovery states. Explain the steps and expected behavior so Jason can understand and assess the change without installing or running the app. Screenshots alone are not sufficient for these changes.
+- Use synthetic or redacted data in screenshots and recordings. Upload the evidence as PR attachments rather than committing it to the repository. Visual evidence complements the required hands-on testing and regression tests; it does not replace them.
## The pull request
@@ -158,8 +165,7 @@ missing:
- `make validate`, and that it was green on the commit you are sending.
- The new test, and that you saw it fail against the unfixed code.
-- What you drove by hand — for an interface change, the themes and sizes, with
- a screenshot.
+- What you drove by hand — for an interface change, the platforms, themes, and sizes, with the required before-and-after screenshots and, for complex features or workflows, a detailed recording.
- That a fresh agent reviewed the diff, and what it found. "Nothing" is an
answer; not having asked is not.
@@ -172,6 +178,14 @@ document, an internal rename.
## Review
+Draft pull requests are not reviewed or approved. The failing-test-only draft described above is a way to preserve a reproducible report; mark a completed change ready for review when it has the required implementation and evidence.
+
+Review existing-functionality bug fixes, small fixes, wording corrections, and performance improvements first. A reviewer may approve a reasonable, focused, low-risk change that preserves product intent once the current diff and discussion have been checked, the relevant tests and required checks pass on the latest revision, and the affected security boundaries satisfy [AGENTS.md](AGENTS.md). Missing verification must be reported, not inferred from an earlier green commit.
+
+UI, shortcuts, layout, and interaction changes need a separate product and design judgment. An objectively demonstrable correction to an established product convention, such as restoring the product's established Vim navigation conventions, may be approved after verifying the convention, checking for conflicts and regressions, and reviewing the required tests and visual evidence. Explain the evidence and recommendation. This exception does not cover new product choices: context-menu details or new menu actions, feature placement, subjective taste, and changes with multiple reasonable design tradeoffs require Jason's explicit confirmation before approval. Large features, product-direction changes, and substantial architectural changes also require deep review and product confirmation. When the distinction is unclear, ask rather than treating passing tests as a product decision.
+
+An approval is not permission to merge: Jason makes the final merge decision, and automated reviewers must never merge.
+
Answer a review comment by changing the code or by saying why the change would
be wrong, and re-run `make validate` after every round — a fix made under
review is a change like any other. Both answers are useful; silence and a
From 3dd8e2f93d27d434e926bbc78130c312bccab0f7 Mon Sep 17 00:00:00 2001
From: Sergey Armodin
Date: Sun, 18 Oct 2026 23:35:11 +0700
Subject: [PATCH 32/88] Fix BackendSync not re-registering a mail watch the
backend no longer holds (#374)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Stacked on #373 and #372; please review only the last commit. I will
rebase as they merge so the squash carries only this change. #372 named
this as a follow-up.
`BackendSync.check()` discarded the `mail.check` reply. When the backend
answered `mail_watch_unknown`, the UI still believed it was registered,
and since `reconcile()` returns early for a matching key nothing ever
sent `mail.watch` again: automatic checks and the unread badge stopped
for that account until its settings changed, it was disabled, or the
backend restarted.
The backend removes a watch only on unwatch, replacement or shutdown,
and a restart always passes through `ready` going false, so the trigger
has to be an unwatch the delegate did not send. There is one.
`Service.qml`'s `Instantiator` binds delegates to `accounts[index]`, so
removing an account that is not last moves ids between delegates: with
[A, B, C] → [B, C], delegate 0 moves A→B and delegate 1 moves B→C. If
delegate 1 still had a watch for B in flight — ordinary at startup,
during a retry, or after an interval change — #373 defers its unwatch
for B until that watch answers, and that unwatch can then land after
delegate 0 has registered B. Before #373 the immediate unwatch usually
won that race but could orphan the watch instead. #373's guard is per
`BackendSync`, so it cannot coordinate two delegates; the real fix
belongs in Rust (list accounts under the operations lock, or a client
generation on watch/unwatch), as noted there.
Until then this self-heals: on `mail_watch_unknown` for the current
epoch `BackendSync` clears its registration and reconciles, which sends
a single `mail.watch` with no unwatch because the account is unchanged.
A reply that arrives after the registration moved on is ignored, and
other errors are still ignored. Recovery happens on the next `refresh()`
(wake, ready, sign-in or a mail action), since that is what calls
`check()`. It uses an error code that has existed since the first API
revision, so no API revision or fixtures are involved.
## Verification
`make validate` green on this commit.
`ui/tests/qml/tst_backend_sync.qml` lets the mock answer `mail.check`
with an error or hold its reply back, and adds three tests: a lost watch
registers again, other check errors keep the registration, and a
lost-watch reply for a watch that has since been replaced is ignored.
Against #373's `BackendSync.qml` the first fails (the registration is
kept); with the change 20/20 pass. Mutations removing the epoch guard,
the error filter, the registration reset or the scheduled reconcile are
each caught.
Nothing visible changes in the interface beyond the badge recovering, so
there are no screenshots, and I did not drive the account-removal race
by hand on screen.
Three fresh reviews of the diff (protocol correctness, test quality with
mutation runs, and a maintainer/security pass against AGENTS.md)
approved; the correctness and maintainer reviews traced the
delegate-shift trigger above, and the test review's findings — a stray
reconcile timer masking a mutant and the untested epoch guard — are
applied. Security: PASS; it only re-registers the delegate's own
account.
## Release Notes
- Automatic mail checks and the unread count resume for an account whose
background check was lost, for example after removing another account.
---
ui/account/BackendSync.qml | 60 ++++++--
ui/tests/qml/tst_backend_sync.qml | 219 +++++++++++++++++++++++++++++-
2 files changed, 267 insertions(+), 12 deletions(-)
diff --git a/ui/account/BackendSync.qml b/ui/account/BackendSync.qml
index 4bbdc3b..5c24654 100644
--- a/ui/account/BackendSync.qml
+++ b/ui/account/BackendSync.qml
@@ -13,7 +13,14 @@ Item {
property var registeredBackend: null
property string registeredAccount: ""
property string registrationKey: ""
+ // A check sent before mail.watch answers may fail with mail_watch_unknown and
+ // is not needed, as a new watch checks at once.
+ property bool registered: false
property bool unregistering: false
+ // One registration request at a time: Rust lists accounts before it takes
+ // its operation lock, so a later watch or unwatch can overtake this one. An
+ // unwatch requested meanwhile is stored here and sent from the watch's reply.
+ property var watchRequest: null
property int epoch: 0
property real sequence: 0
signal updated(var snapshot)
@@ -30,23 +37,31 @@ Item {
registeredBackend = null
registeredAccount = ""
registrationKey = ""
+ registered = false
sequence = 0
epoch++
if (oldBackend && oldBackend.ready && oldAccount) {
unregistering = true
- oldBackend.call("mail.unwatch", { accountId: oldAccount }, function() {
- if (!root) return
- root.unregistering = false
- root.scheduleReconcile()
- })
+ // The pending watch sends it on reply, even after this item is destroyed.
+ if (watchRequest && watchRequest.backend === oldBackend) watchRequest.unwatch = oldAccount
+ else oldBackend.call("mail.unwatch", { accountId: oldAccount }, unwatched)
}
}
+ function unwatched() {
+ if (!root) return
+ root.unregistering = false
+ root.scheduleReconcile()
+ }
+
+ function wantedKey() { return JSON.stringify([accountId, query, intervalSec, pageSize]) }
+
function reconcile() {
if (unregistering) return
if (!enabled || !backend || !backend.ready || !accountId) { stop(); return }
- var key = JSON.stringify([accountId, query, intervalSec, pageSize])
+ var key = wantedKey()
if (registeredBackend === backend && registrationKey === key) return
+ if (watchRequest && watchRequest.backend === backend) return
retryTimer.stop()
// Updating an existing watch is atomic in Rust; an unwatch racing a new
// watch would otherwise remove the replacement.
@@ -55,15 +70,31 @@ Item {
registeredBackend = backend
registeredAccount = accountId
registrationKey = key
+ registered = false
var mine = ++epoch
+ var request = { backend: backend, unwatch: "" }
+ // Captured so a deferred unwatch can still finish after destruction.
+ var onUnwatched = root.unwatched
+ watchRequest = request
backend.call("mail.watch", { accountId: accountId, query: query, intervalSec: intervalSec, pageSize: pageSize }, function(result, error) {
- if (mine !== root.epoch) return
+ if (root && root.watchRequest === request) root.watchRequest = null
+ if (request.unwatch) {
+ request.backend.call("mail.unwatch", { accountId: request.unwatch }, onUnwatched)
+ return
+ }
+ if (!root) return
+ if (mine !== root.epoch) { root.scheduleReconcile(); return }
+ // Settings changed while this watch was pending: register those instead.
+ var current = root.wantedKey() === key
if (error) {
root.registrationKey = ""
- if (root.enabled && root.backend && root.backend.ready) retryTimer.restart()
+ if (!current) root.scheduleReconcile()
+ else if (root.enabled && root.backend && root.backend.ready) retryTimer.restart()
return
}
- root.accept(result)
+ root.registered = true
+ if (current) root.accept(result)
+ else root.scheduleReconcile()
})
}
@@ -76,8 +107,15 @@ Item {
function check() {
reconcile()
- if (!registeredBackend || !registeredBackend.ready || !registrationKey) return
- registeredBackend.call("mail.check", { accountId: registeredAccount }, function() {})
+ if (!registeredBackend || !registeredBackend.ready || !registered) return
+ var mine = epoch
+ registeredBackend.call("mail.check", { accountId: registeredAccount }, function(result, error) {
+ if (!root || mine !== root.epoch || !error || error.message !== "mail_watch_unknown") return
+ // The backend no longer holds this watch, so polling stopped: register again.
+ root.registrationKey = ""
+ root.registered = false
+ root.scheduleReconcile()
+ })
}
onEnabledChanged: scheduleReconcile()
diff --git a/ui/tests/qml/tst_backend_sync.qml b/ui/tests/qml/tst_backend_sync.qml
index d4309dd..a608853 100644
--- a/ui/tests/qml/tst_backend_sync.qml
+++ b/ui/tests/qml/tst_backend_sync.qml
@@ -9,10 +9,19 @@ Item {
property var calls: []
property var pendingStop: null
property bool failWatch: false
+ property bool deferWatch: false
+ property string checkError: ""
+ property bool deferCheck: false
+ property var pendingChecks: []
+ property var pendingWatches: []
signal notification(string method, var params)
function call(method, params, callback) {
- calls = calls.concat([{method:method, params:params}])
+ calls = calls.concat([ready ? {method:method, params:params} : {method:method, params:params, refused:true}])
+ if (!ready) { callback(null, {message:"Backend unavailable"}); return }
if (method === "mail.unwatch") pendingStop = callback
+ else if (method === "mail.watch" && deferWatch) pendingWatches = pendingWatches.concat([callback])
+ else if (method === "mail.check" && deferCheck) pendingChecks = pendingChecks.concat([callback])
+ else if (method === "mail.check" && checkError) callback(null, {message:checkError})
else callback(null, method === "mail.watch" && failWatch ? {message:"temporary"} : null)
}
}
@@ -22,6 +31,10 @@ Item {
accountId: "a@example.org"
query: "is:unread"
}
+ Component {
+ id: syncComponent
+ Accounts.BackendSync { accountId: "b@example.org"; query: "is:unread" }
+ }
SignalSpy { id: updates; target: sync; signalName: "updated" }
TestCase {
name: "BackendSync"
@@ -29,10 +42,21 @@ Item {
function init() {
sync.enabled = false
sync.reconcile()
+ var waiting = backend.pendingWatches
+ backend.pendingWatches = []
+ // A test that failed early leaves its watch unanswered; settle it here
+ // without charging a throw to the next test.
+ for (var i = 0; i < waiting.length; i++) {
+ try { if (waiting[i]) waiting[i](null, {message:"reset"}) } catch (failure) {}
+ }
if (backend.pendingStop) { var done = backend.pendingStop; backend.pendingStop = null; done() }
backend.ready = true
backend.calls = []
backend.failWatch = false
+ backend.deferWatch = false
+ backend.checkError = ""
+ backend.deferCheck = false
+ backend.pendingChecks = []
sync.accountId = "a@example.org"
sync.intervalSec = 120
sync.pageSize = 25
@@ -96,5 +120,198 @@ Item {
compare(backend.calls[backend.calls.length - 1].method, "mail.check")
verify(sync.registrationKey !== "")
}
+ function answerWatch(index, error) {
+ var answer = backend.pendingWatches[index]
+ backend.pendingWatches[index] = null
+ answer(error ? null : {accountId:"a@example.org",sequence:index + 1,estimate:0,messages:[],error:""}, error || null)
+ }
+ function test_check_waits_for_the_watch_to_answer() {
+ backend.deferWatch = true
+ sync.enabled = true
+ sync.check()
+ compare(backend.calls.length, 1)
+ compare(backend.calls[0].method, "mail.watch")
+ compare(backend.pendingWatches.length, 1)
+ answerWatch(0)
+ sync.check()
+ compare(backend.calls.length, 2)
+ compare(backend.calls[1].method, "mail.check")
+ }
+ function test_check_waits_for_a_reconnected_backend_to_register() {
+ sync.enabled = true
+ sync.reconcile()
+ backend.deferWatch = true
+ backend.ready = false
+ backend.ready = true
+ var count = backend.calls.length
+ compare(backend.calls[count - 1].method, "mail.watch")
+ sync.check()
+ compare(backend.calls.length, count)
+ answerWatch(0)
+ sync.check()
+ compare(backend.calls.length, count + 1)
+ compare(backend.calls[count].method, "mail.check")
+ }
+ function test_settings_changed_during_a_watch_wait_for_its_answer() {
+ backend.deferWatch = true
+ sync.enabled = true
+ sync.reconcile()
+ sync.pageSize = 50
+ sync.reconcile()
+ sync.pageSize = 25
+ sync.reconcile()
+ sync.pageSize = 50
+ sync.reconcile()
+ compare(backend.calls.length, 1)
+ answerWatch(0)
+ var count = backend.calls.length
+ sync.check()
+ compare(backend.calls.length, count + 1)
+ compare(backend.calls[count].method, "mail.watch")
+ compare(backend.calls[count].params.pageSize, 50)
+ answerWatch(1)
+ sync.check()
+ compare(backend.calls.length, count + 2)
+ compare(backend.calls[count + 1].method, "mail.check")
+ }
+ function test_settings_changed_during_a_watch_apply_after_it() {
+ backend.deferWatch = true
+ sync.enabled = true
+ sync.reconcile()
+ sync.pageSize = 50
+ wait(0)
+ compare(backend.calls.length, 1)
+ answerWatch(0)
+ compare(updates.count, 0)
+ tryVerify(function() { return backend.pendingWatches.length === 2 })
+ compare(backend.calls[1].params.pageSize, 50)
+ }
+ function test_failed_watch_for_changed_settings_registers_them_at_once() {
+ backend.deferWatch = true
+ sync.enabled = true
+ sync.reconcile()
+ sync.pageSize = 50
+ wait(0)
+ answerWatch(0, {message:"temporary"})
+ tryVerify(function() { return backend.pendingWatches.length === 2 }, 1000)
+ compare(backend.calls[1].params.pageSize, 50)
+ }
+ function test_reconnect_during_a_watch_ignores_its_answer() {
+ backend.deferWatch = true
+ sync.enabled = true
+ sync.reconcile()
+ backend.ready = false
+ backend.ready = true
+ wait(0)
+ compare(backend.calls.length, 1)
+ answerWatch(0)
+ compare(updates.count, 0)
+ tryVerify(function() { return backend.pendingWatches.length === 2 })
+ sync.check()
+ compare(backend.calls[backend.calls.length - 1].method, "mail.watch")
+ }
+ function test_backend_failure_releases_a_deferred_unwatch() {
+ backend.deferWatch = true
+ sync.enabled = true
+ sync.reconcile()
+ sync.enabled = false
+ sync.reconcile()
+ verify(sync.unregistering)
+ backend.ready = false
+ answerWatch(0, {message:"Backend unavailable"})
+ verify(!sync.unregistering)
+ compare(backend.calls.length, 2)
+ compare(backend.calls[1].method, "mail.unwatch")
+ verify(backend.calls[1].refused)
+ backend.ready = true
+ sync.enabled = true
+ tryVerify(function() { return backend.pendingWatches.length === 2 })
+ }
+ function test_disabling_during_a_watch_unwatches_after_its_answer() {
+ backend.deferWatch = true
+ sync.enabled = true
+ sync.reconcile()
+ sync.enabled = false
+ sync.reconcile()
+ compare(backend.calls.length, 1)
+ answerWatch(0)
+ compare(backend.calls.length, 2)
+ compare(backend.calls[1].method, "mail.unwatch")
+ compare(backend.calls[1].params.accountId, "a@example.org")
+ sync.enabled = true
+ sync.reconcile()
+ compare(backend.calls.length, 2)
+ var done = backend.pendingStop
+ backend.pendingStop = null
+ done()
+ tryVerify(function() { return backend.pendingWatches.length === 2 })
+ }
+ function test_destroyed_during_a_watch_still_unwatches() {
+ backend.deferWatch = true
+ var item = syncComponent.createObject(null, {backend: backend, enabled: true})
+ item.reconcile()
+ compare(backend.calls.length, 1)
+ item.destroy()
+ wait(0)
+ compare(backend.calls.length, 1)
+ answerWatch(0)
+ compare(backend.calls.length, 2)
+ compare(backend.calls[1].method, "mail.unwatch")
+ compare(backend.calls[1].params.accountId, "b@example.org")
+ var done = backend.pendingStop
+ backend.pendingStop = null
+ done()
+ }
+ function test_failed_pending_watch_registers_again_instead_of_checking() {
+ backend.deferWatch = true
+ sync.enabled = true
+ sync.reconcile()
+ answerWatch(0, {message:"temporary"})
+ var count = backend.calls.length
+ sync.check()
+ compare(backend.calls.length, count + 1)
+ compare(backend.calls[count].method, "mail.watch")
+ }
+ function test_check_for_a_lost_watch_registers_again() {
+ sync.enabled = true
+ sync.reconcile()
+ wait(10)
+ backend.checkError = "mail_watch_unknown"
+ sync.check()
+ var count = backend.calls.length
+ compare(backend.calls[count - 1].method, "mail.check")
+ verify(!sync.registered)
+ tryVerify(function() { return backend.calls.length === count + 1 }, 1000)
+ compare(backend.calls[count].method, "mail.watch")
+ verify(sync.registered)
+ }
+ function test_other_check_errors_keep_the_watch() {
+ sync.enabled = true
+ sync.reconcile()
+ wait(10)
+ backend.checkError = "mail_network_failed"
+ sync.check()
+ var count = backend.calls.length
+ wait(10)
+ compare(backend.calls.length, count)
+ verify(sync.registered)
+ }
+ function test_lost_watch_reply_for_a_replaced_watch_is_ignored() {
+ sync.enabled = true
+ sync.reconcile()
+ wait(10)
+ backend.deferCheck = true
+ sync.check()
+ compare(backend.pendingChecks.length, 1)
+ sync.intervalSec = 60
+ sync.reconcile()
+ var count = backend.calls.length
+ compare(backend.calls[count - 1].method, "mail.watch")
+ verify(sync.registered)
+ backend.pendingChecks[0](null, {message:"mail_watch_unknown"})
+ wait(10)
+ compare(backend.calls.length, count)
+ verify(sync.registered)
+ }
}
}
From bb2ed8414c193659582f86715504917ebc16fece Mon Sep 17 00:00:00 2001
From: Lesani <5182104+Lesani@users.noreply.github.com>
Date: Sun, 18 Oct 2026 18:35:25 +0200
Subject: [PATCH 33/88] Hide the calendar entry while no calendar is connected
(#375)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## What changes and who it helps
A mailbox with no calendar behind it, such as plain IMAP without CalDAV
and with nothing added under Settings → Calendars, still shows
**Calendar** in the sidebar, in the window menu and under Alt+C /
Ctrl+Shift+C. It opens an empty month that cannot hold an event, because
every event write needs a source. People who keep their calendar
elsewhere get a permanent dead entry and no way to turn it off.
The window now offers the calendar only while at least one source exists
across all accounts: a Google or Microsoft mailbox's own calendar, a
discovered iCloud calendar, or a CalDAV calendar added in Settings.
Nothing is removed for anyone who has one.
- **Sidebar, window menu, both shortcuts:** hidden or inert while there
is no source. A calendar opened from a bar notification is gated the
same way.
- **Adding one is unchanged:** the Settings form still adds a CalDAV
calendar, and the entry appears as soon as one exists.
- **Losing the last source:** a calendar that is open when its last
source goes away returns to the mail list.
- **Disabled calendars still count,** because the calendar is where they
are turned back on.
- **No flicker on start:** a source list that has not been read yet
counts as having a source, so the entry never disappears and comes back
while the file loads.
No setting was added. The rule is one pure function,
`Sources.hasNone(loaded, list)`, exposed as `noCalendars` on the
calendar controller and the service, and read by `App.qml`'s new
`calendarAvailable`.
### Reproduction
1. Configure only an IMAP mailbox with no CalDAV calendar (All-Inkl, for
example).
2. Open Omamail. **Calendar** sits at the foot of the sidebar, and
opening it shows an empty month with nothing to create an event in.
## Screenshots
The sidebar is rendered offscreen with synthetic labels at matching
size, scale and colours. The left image uses unmodified `main`.
| Before (`main`) | After, calendar connected | After, none connected |
| --- | --- | --- |
|

| 
| 
|
There's no screenshot of the window menu: its Calendar row hides the
same way the existing Quit and web-inbox rows do, and
`tst_app_navigation` asserts that.
## Verification
- `ui/tests/test_calendar_sources.js`: `hasNone` covers an empty list,
an unread list, `null`, a disabled source and a signed-in Gmail account.
- `tst_app_navigation`: an open calendar that loses its last source
returns to the list. Neither shortcut opens it, `showCalendar()`
refuses, the menu row is hidden, and connecting a source brings it back.
- `tst_sidebar_fold`: the sidebar entry follows `calendarAvailable`.
- All three new tests fail on `main` and pass here.
- `tst_standalone_composition`'s calendar close-chord test now connects
a source before it opens the calendar.
- `make validate` passes locally (Qt 6.11.2, Arch, Omarchy 4.0.4),
including `omarchy plugin validate .`. The one exception is
`tests/test_clipboard.py`, which needs a live Wayland clipboard and
fails the same way on unmodified `main` here.
**Security: PASS.** This only changes which entry points are shown. No
network request, credential, subprocess or persisted setting is touched.
## Release Notes
- The Calendar entry, menu row and shortcuts are hidden while no
calendar is connected. Add one in Settings to bring them back.
🤖 Greetings from [Claude](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5
---
app/tests/qml/tst_standalone_composition.qml | 6 +++-
ui/App.qml | 28 +++++++++----------
ui/Service.qml | 1 +
ui/calendar/CalendarController.qml | 3 ++
ui/calendar/Sources.js | 10 +++++++
ui/components/AppMenu.qml | 3 ++
ui/components/MailboxSidebar.qml | 2 ++
ui/tests/qml/tst_app_navigation.qml | 29 ++++++++++++++++++++
ui/tests/qml/tst_sidebar_fold.qml | 8 ++++++
ui/tests/test_calendar_sources.js | 19 +++++++++++++
10 files changed, 94 insertions(+), 15 deletions(-)
diff --git a/app/tests/qml/tst_standalone_composition.qml b/app/tests/qml/tst_standalone_composition.qml
index a8d4ce2..5551765 100644
--- a/app/tests/qml/tst_standalone_composition.qml
+++ b/app/tests/qml/tst_standalone_composition.qml
@@ -501,7 +501,11 @@ TestCase {
var scope = focusScopeOf(composition)
verify(scope)
scope.enabled = true
- composition.app.showCalendar()
+ // The window offers a calendar only once one is connected.
+ composition.app.service.calendarController.sourceList = ({ version: 1, sources: [{
+ id: "caldav:calendar-example", kind: "caldav", name: "Example",
+ url: "https://calendar.example/", username: "me", enabled: true }] })
+ verify(composition.app.showCalendar())
var router = keyRouter(composition)
verify(router)
router.context = "calendar"
diff --git a/ui/App.qml b/ui/App.qml
index dadb1fa..0daa95c 100644
--- a/ui/App.qml
+++ b/ui/App.qml
@@ -310,6 +310,10 @@ Item {
readonly property string currentView: page === "reader" ? "reader"
: ((page === "calendar" || page === "calendarDetail") ? "calendar" : "list")
readonly property bool calendarVisible: currentView === "calendar"
+ // With no calendar connected anywhere the view cannot hold an event, so the
+ // window stops offering it; Settings still adds one.
+ readonly property bool calendarAvailable: !(service && service.noCalendars === true)
+ onCalendarAvailableChanged: if (!calendarAvailable && calendarVisible) backToList()
readonly property bool showSettings: page === "settings"
readonly property bool showPicker: page === "picker"
readonly property bool showSetup: page === "setup"
@@ -491,8 +495,7 @@ Item {
if (payload.messageId) Qt.callLater(function() {
root.openMessage(String(payload.messageId))
})
- if (payload.view === "calendar") {
- showCalendar()
+ if (payload.view === "calendar" && showCalendar()) {
Qt.callLater(function() {
calendarView.showEvent(String(payload.eventId || ""), Number(payload.eventStart || 0))
})
@@ -611,8 +614,10 @@ Item {
}
function showCalendar() {
+ if (!calendarAvailable) return false
navUntouched = false
nav = Nav.replaceRoot(nav, "calendar")
+ return true
}
// Moving the cursor has to bring the row with it. The list is a Column in a
@@ -1066,16 +1071,12 @@ Item {
if (id === "switchAccount") return accountSwitcher.openCentered()
if (id === "calendar") {
if (calendarVisible) backToList()
- else {
- showCalendar()
- calendarView.refresh()
- }
+ else if (showCalendar()) calendarView.refresh()
return
}
if (id === "mailView") return backToList()
if (id === "calendarView") {
- showCalendar()
- calendarView.refresh()
+ if (showCalendar()) calendarView.refresh()
return
}
if (id === "toggleSidebar") return toggleSidebar()
@@ -1811,6 +1812,7 @@ Item {
visible: !root.compact && !root.showPage && !root.composing
collapsed: root.sidebarCollapsed
calendarSelected: root.calendarVisible
+ calendarAvailable: root.calendarAvailable
menuLabelPath: labelMenu.opened && !!root.service
&& labelMenu.accountId === root.service.activeAccountId ? labelMenu.labelPath : ""
service: root.service
@@ -1822,8 +1824,7 @@ Item {
numbersVisible: focusScope.ctrlHeld
onMailboxSelected: function(key) { root.goMailbox(key) }
onCalendarRequested: {
- root.showCalendar()
- calendarView.refresh()
+ if (root.showCalendar()) calendarView.refresh()
}
// Not a search: the provider decides what selecting a label means,
// and on IMAP it is a folder rather than a term to look for.
@@ -2364,8 +2365,7 @@ Item {
Qt.callLater(function() { if (root.service) root.service.signIn() })
}
onOpenCalendarRequested: {
- root.showCalendar()
- calendarView.refresh()
+ if (root.showCalendar()) calendarView.refresh()
}
// Which kind first, then the form for it.
onAddRequested: root.addMailbox()
@@ -2669,6 +2669,7 @@ Item {
id: appMenu
objectName: "app-menu"
anchors.fill: parent
+ calendarAvailable: root.calendarAvailable
textColor: root.foreground
popupBackgroundColor: root.popupBackground
popupBorderColor: root.popupBorder
@@ -2685,8 +2686,7 @@ Item {
if (root.service) root.service.selectMailbox("inbox")
}
onCalendarRequested: {
- root.showCalendar()
- calendarView.refresh()
+ if (root.showCalendar()) calendarView.refresh()
}
onSetupRequested: root.openSettings()
onSwitchAccountRequested: accountSwitcher.openCentered()
diff --git a/ui/Service.qml b/ui/Service.qml
index c3ded4f..0e446f0 100644
--- a/ui/Service.qml
+++ b/ui/Service.qml
@@ -1670,6 +1670,7 @@ Item {
}
readonly property alias calendarController: sharedCalendar
+ readonly property bool noCalendars: sharedCalendar.noCalendars
readonly property var barEvents: Preview.upcomingEvents(
barCalendar.events, Date.now(), 2)
diff --git a/ui/calendar/CalendarController.qml b/ui/calendar/CalendarController.qml
index 8c69ca8..68ecd47 100644
--- a/ui/calendar/CalendarController.qml
+++ b/ui/calendar/CalendarController.qml
@@ -74,6 +74,9 @@ Item {
property bool eventWriting: false
readonly property var availableSources: Sources.withMicrosoftAccounts(Sources.withGoogleAccounts(
sourceList, service ? service.accountSummaries : []), service ? service.accountSummaries : [])
+ // Every account's calendars, not just this mailbox's: the entry hides only
+ // when no account has one and nothing was added in Settings.
+ readonly property bool noCalendars: Sources.hasNone(sourcesLoaded, availableSources)
readonly property bool unifiedCalendarView: !!service
&& service.unifiedCalendarView === true
readonly property var contextSources: unifiedCalendarView
diff --git a/ui/calendar/Sources.js b/ui/calendar/Sources.js
index 2039cd1..7c5f2ef 100644
--- a/ui/calendar/Sources.js
+++ b/ui/calendar/Sources.js
@@ -364,6 +364,16 @@ function forAccount(list, accountId) {
return next
}
+// Whether the window should offer a calendar at all. Nothing connected means
+// the view is an empty grid that cannot hold an event, since every write needs
+// a source. A list that has not been read yet still counts as having one: the
+// entry must not vanish and reappear while the file loads. A disabled source
+// still counts, because the calendar is where it is turned back on.
+function hasNone(loaded, list) {
+ return loaded === true
+ && !(list && Array.isArray(list.sources) && list.sources.length > 0)
+}
+
function providerLabel(kind) {
var value = trimmed(kind).toLowerCase()
if (value === "google" || value === "gmail") return "Google"
diff --git a/ui/components/AppMenu.qml b/ui/components/AppMenu.qml
index ad00bc8..7244cb9 100644
--- a/ui/components/AppMenu.qml
+++ b/ui/components/AppMenu.qml
@@ -26,6 +26,7 @@ Item {
// Only the standalone host owns the application process. A plugin menu
// must never offer to terminate the shell that loaded it.
property bool canQuit: false
+ property bool calendarAvailable: true
readonly property bool opened: menu.opened
// Positioned against the window rather than a button, and flipped when it
@@ -146,7 +147,9 @@ Item {
}
MenuRow {
id: calendarRow
+ objectName: "app-menu-calendar"
text: "Calendar"
+ visible: root.calendarAvailable
onActivated: { menu.close(); root.calendarRequested() }
}
MenuSeparatorLine {
diff --git a/ui/components/MailboxSidebar.qml b/ui/components/MailboxSidebar.qml
index 608ca17..a362603 100644
--- a/ui/components/MailboxSidebar.qml
+++ b/ui/components/MailboxSidebar.qml
@@ -21,6 +21,7 @@ Item {
required property string panelFontFamily
property bool collapsed: false
property bool calendarSelected: false
+ property bool calendarAvailable: true
property string menuLabelPath: ""
signal mailboxSelected(string key)
@@ -166,6 +167,7 @@ Item {
x: Style.space(6)
label: "Calendar"
icon: "calendar"
+ visible: root.calendarAvailable
selected: root.calendarSelected
onActivated: root.calendarRequested()
}
diff --git a/ui/tests/qml/tst_app_navigation.qml b/ui/tests/qml/tst_app_navigation.qml
index be10306..2d81038 100644
--- a/ui/tests/qml/tst_app_navigation.qml
+++ b/ui/tests/qml/tst_app_navigation.qml
@@ -107,6 +107,7 @@ Item {
property var sendAsAliases: []
property var sendIdentities: []
property var calendarController: null
+ property bool noCalendars: false
property var selectedBody: ({ text: "Original body", source: "plain" })
property var selectedMessage: null
property var unavailableActions: []
@@ -268,6 +269,7 @@ Item {
mailService.selectedId = ""
mailService.selectedMessage = null
mailService.unavailableActions = []
+ mailService.noCalendars = false
mailService.selectedBody = ({ text: "Original body", source: "plain" })
fakeAuth.credentialsPresent = false
fakeShell.hidden = []
@@ -481,6 +483,33 @@ Item {
compare(kinds(), "list,reader", "the key toggles")
}
+ function test_no_connected_calendar_takes_the_calendar_out_of_the_window() {
+ app.runShortcut("calendarView", "")
+ compare(kinds(), "calendar")
+ mailService.noCalendars = true
+ compare(app.calendarAvailable, false)
+ compare(kinds(), "list", "a calendar that loses its last source closes")
+
+ app.runShortcut("calendarView", "")
+ app.runShortcut("calendar", "")
+ compare(kinds(), "list", "neither shortcut opens an empty calendar")
+ compare(app.showCalendar(), false)
+
+ var menu = named(app, "app-menu")
+ menu.openAt(40, 40)
+ wait(20)
+ var row = null
+ for (var i = 0; i < menu.menuRows.length; i++)
+ if (menu.menuRows[i].objectName === "app-menu-calendar") row = menu.menuRows[i]
+ verify(row, "the menu has a calendar row")
+ compare(row.visible, false, "and does not offer it")
+ menu.close()
+
+ mailService.noCalendars = false
+ app.runShortcut("calendarView", "")
+ compare(kinds(), "calendar", "connecting one brings it back")
+ }
+
function test_the_calendar_is_the_other_root_and_back_on_a_root_closes() {
app.runShortcut("calendarView", "")
compare(kinds(), "calendar")
diff --git a/ui/tests/qml/tst_sidebar_fold.qml b/ui/tests/qml/tst_sidebar_fold.qml
index 3312f90..15c4bb1 100644
--- a/ui/tests/qml/tst_sidebar_fold.qml
+++ b/ui/tests/qml/tst_sidebar_fold.qml
@@ -64,6 +64,14 @@ Item {
sidebar.collapsed = false
}
+ function test_the_calendar_entry_follows_whether_one_is_connected() {
+ verify(textItem(sidebar, "Calendar").visible, "shown by default")
+ sidebar.calendarAvailable = false
+ var hidden = textItem(sidebar, "Calendar")
+ verify(hidden === null || !hidden.visible, "hidden with nothing connected")
+ sidebar.calendarAvailable = true
+ }
+
function test_the_chevron_folds_without_opening() {
var folds = named(sidebar, "fold", [])
compare(folds.length, 1, "only the parent carries a chevron")
diff --git a/ui/tests/test_calendar_sources.js b/ui/tests/test_calendar_sources.js
index 88860d3..17c9a2a 100644
--- a/ui/tests/test_calendar_sources.js
+++ b/ui/tests/test_calendar_sources.js
@@ -359,3 +359,22 @@ assert.strictEqual(namedMicrosoft.sources[0].name, "Work appointments",
assert.strictEqual(sources.errorLabel({ id: "caldav:team", kind: "caldav" }, accounts), "caldav:team")
assert.strictEqual(sources.errorLabel(null, accounts), "Calendar")
}
+
+// The window hides its calendar only once the list is known to be empty.
+{
+ assert.strictEqual(sources.hasNone(true, sources.emptyList()), true,
+ "nothing connected anywhere hides the calendar")
+ assert.strictEqual(sources.hasNone(false, sources.emptyList()), false,
+ "an unread list keeps the entry rather than flashing it away")
+ assert.strictEqual(sources.hasNone(true, null), true)
+ const disabled = sources.add(sources.emptyList(), {
+ id: "caldav:off", kind: "caldav", name: "Off",
+ url: "https://calendar.example/off/", username: "me", enabled: false
+ })
+ assert.strictEqual(sources.hasNone(true, disabled), false,
+ "a disabled calendar is still turned back on from the calendar")
+ const google = sources.withGoogleAccounts(sources.emptyList(),
+ [{ id: "one@gmail.com", email: "one@gmail.com", provider: "gmail", signedIn: true }])
+ assert.strictEqual(sources.hasNone(true, google), false,
+ "a Google mailbox brings its own calendar")
+}
From 027efb6bafd4281d4c5a4bd710b17f37aa177244 Mon Sep 17 00:00:00 2001
From: Oliver Lukschander
Date: Mon, 19 Oct 2026 03:58:22 +0200
Subject: [PATCH 34/88] Add Restore in Trash (menu, buttons, d) and Move to
Inbox in Archive (buttons, e) (#359)
---
docs/KEYS.md | 6 +-
ui/App.qml | 18 +-
ui/account/Model.js | 98 +++
ui/components/MessageList.qml | 64 +-
ui/components/MessageMenu.qml | 72 ++-
ui/components/MessageReader.qml | 24 +-
ui/components/MessageRow.qml | 20 +-
ui/components/ReaderBlankSlate.qml | 30 +-
ui/keys/Keymap.js | 22 +-
ui/tests/qml/tst_message_menu_inbox.qml | 124 ++++
ui/tests/qml/tst_trash_restore.qml | 786 ++++++++++++++++++++++++
ui/tests/test_keymap.js | 14 +
ui/tests/test_model.js | 100 +++
13 files changed, 1316 insertions(+), 62 deletions(-)
create mode 100644 ui/tests/qml/tst_trash_restore.qml
diff --git a/docs/KEYS.md b/docs/KEYS.md
index f771a10..16da26d 100644
--- a/docs/KEYS.md
+++ b/docs/KEYS.md
@@ -118,8 +118,8 @@ used to exist, and they had.
| `backToList` | `u`, `Left` | reader | Back to the list |
| `nextMember` | `n` | reader | Next message in the conversation |
| `previousMember` | `p` | reader | Previous message in the conversation |
-| `archive` | `e` | mail | Archive |
-| `trash` | `d` | mail | Move to trash |
+| `archive` | `e` | mail | Archive (in Archive: move to Inbox) |
+| `trash` | `d` | mail | Move to trash (in the trash: restore) |
| `star` | `s` | mail | Star or unstar |
| `moveToLabel` | `v` | mail | Move to |
| `markRead` | `Shift+I` | mail | Mark read |
@@ -177,6 +177,8 @@ In Drafts, `Enter`, `o` and `c` open the selected draft in the composer, with wh
`Space` or `x` toggles the cursor row's selection in the list or reader context. Shift+click applies the clicked row's next checked state to the inclusive range from the cursor: an unchecked endpoint selects the range, and a checked endpoint clears it. Selections outside the range remain unchanged; the cursor then moves to the clicked row.
+`e` and `d` are the archive and trash buttons, and where a button's action is already done for every row it will reach, the button is its inverse, and so is the key: in the trash they restore, and in Archive they move an archived message to the Inbox. The rows are the ones the control acts on: the ticked rows when it is about one of them (a key, a ticked row's menu or middle-click, the reader on a ticked message), else the cursor's row (before there is one, the listing's rows, which is what the hint row and the empty reader's key list describe), the row itself, or the row the open message belongs to. A mixed selection gets the key's own verb, the way `s` stars a mixed one. Restore is the provider's untrash, which every client has, so it is also the way out of the trash on HEY, which has no archive and no move. It is not called Move to Inbox because where it lands is the provider's: Gmail takes the TRASH label off and leaves the rest, the others move the message to the Inbox. `e` turns back only in Archive: on IMAP every folder but the Inbox reads as archived, and `e` in one of them still files the message in Archive. `Model.keyActionFor` is the rule. `MessageList` applies it over each control's rows, with App's own `selectionActive` deciding whether the ticked rows are reached, and App sends the keys and the hint row through its `keyActions`. A button's tooltip, on a row or in the reader, names `e` or `d` only when the key reaches the same rows and asks the same of them. Hovering does not move the cursor, so a row names its keys only when it is the cursor's row, or ticked while the selection is active. A message that is not one of the listing's rows, such as one a notification opened over the Trash, is judged by its own labels.
+
`n` and `p` walk the conversation rail beside the message on a provider whose listing collapses to conversations, opening the next and previous member in the same reader and stopping at the ends. The rail runs newest at the top, so `n` opens the stop below the open message, which is the older one, and `p` the stop above it, the newer — the keys follow the rail as it is drawn, the way `j` and `k` follow the list. They move the reader and nothing else. `j` and `k` move the list cursor and immediately open the representative of that row, leaving the conversation member selected with `n` or `p`. A message whose conversation has one member draws no rail, and both keys then do nothing. A right-click on a stop opens the same menu a row has — reply, archive, trash, spam, read, star — for that one message: the action reaches the member alone, where the same verb on the row reaches every counted member, and if the open message is the one taken out of the view the reader moves to the stop beside it, the newer one above or else the older below.
The delayed-send toast does not create a keyboard context. The current screen keeps its normal keys while the toast is visible. A new draft, reply, or forward can open during the delay. The send button waits for the queued message, but every draft field remains editable. The toast button restores the queued message. `Alt+Z` does the same from every context. `Ctrl+Z` remains text undo while composing or searching. If another compose is open, Omamail saves it to the provider's Drafts storage before dropping its in-memory fallback. A failed save keeps that fallback.
diff --git a/ui/App.qml b/ui/App.qml
index 0daa95c..28f4cb9 100644
--- a/ui/App.qml
+++ b/ui/App.qml
@@ -1006,8 +1006,7 @@ Item {
if (id === "backToList") return backToList()
if (id === "nextMember") return stepMember(1)
if (id === "previousMember") return stepMember(-1)
- if (id === "archive") return actOnCursor("archive")
- if (id === "trash") return actOnCursor("trash")
+ if (id === "archive" || id === "trash") return actOnCursor(list.keyActions[id])
// Through the same guard actOnCursor applies rather than around it:
// starring with nothing selected used to call through with an empty id.
//
@@ -1947,6 +1946,7 @@ Item {
panelFontFamily: root.fontFamily
cursorId: root.cursorId
checkedIds: root.checkedIds
+ selectionActive: root.selectionActive
ctrlHeld: focusScope.ctrlHeld
urgentColor: root.urgent
onMessageActivated: function(id) { root.openMessage(id) }
@@ -1954,9 +1954,9 @@ Item {
onRowActionRequested: function(id, action) { root.actFromRow(id, action) }
onCheckToggled: function(id) { root.toggleCheck(id) }
onCheckRangeRequested: function(id) { root.checkRange(id) }
- onMenuRequested: function(id, sceneX, sceneY) {
+ onMenuRequested: function(id, sceneX, sceneY, ids) {
root.cursorId = id
- rowMenu.openAt(id, sceneX, sceneY)
+ rowMenu.openAt(id, sceneX, sceneY, ids)
}
}
}
@@ -2034,6 +2034,8 @@ Item {
bodyMode: root.bodyMode
alwaysRenderHeavyMessages: !!root.service && root.service.alwaysRenderHeavyMessages
contentDirection: root.service ? root.service.contentDirection : ""
+ actions: list.readerActions
+ keyActions: list.keyActions
onBodyModeRequested: function(mode) {
if (root.service) root.service.setBodyMode(mode)
}
@@ -2081,9 +2083,7 @@ Item {
root.service.toggleStar(root.service.selectedId)
return
}
- if (((root.service.conversationProjection || ({})).memberIds || []).indexOf(root.service.selectedId) < 0
- || root.cursorId === "")
- root.cursorId = root.service.selectedId
+ root.cursorId = Model.readerTarget(root.service.conversationProjection, root.service.selectedId, root.cursorId)
if (action === "moveToLabel") return root.openLabelPicker(outside)
root.actOnCursor(action, outside)
}
@@ -2660,7 +2660,7 @@ Item {
panelFontFamily: root.fontFamily
hints: Keymap.hintsFor(focusScope.keyContext,
root.service ? root.service.unavailableActions : [],
- root.cursorId !== "")
+ root.cursorId !== "", list.keyActions)
}
}
@@ -2981,8 +2981,6 @@ Item {
var outside = root.checkedIds.indexOf(id) < 0
root.cursorId = id
if (action === "moveToLabel") return root.openLabelPicker(outside)
- if ((action === "star" || action === "unstar") && root.selectionActive && !outside)
- return root.actOnChecked(Model.starActionFor(Model.summariesById(root.service.messages, root.checkedIds)))
root.actOnCursor(action, outside)
}
// From a stop on the rail. A member is not a row, so the cursor stays
diff --git a/ui/account/Model.js b/ui/account/Model.js
index 335c28e..11854ac 100644
--- a/ui/account/Model.js
+++ b/ui/account/Model.js
@@ -538,6 +538,104 @@ function unavailableActions(capabilities) {
return out
}
+// The mailbox the list is showing, or "" while it shows something else: a
+// search reaches the whole account and a label view is somewhere else,
+// whatever `mailboxKey` still says. `view` is anything with the service's
+// `mailboxKey`, `searchQuery` and `rawQuery`.
+function plainMailbox(view) {
+ var on = view || {}
+ if (String(on.searchQuery || "") !== "" || String(on.rawQuery || "") !== "") return ""
+ return String(on.mailboxKey || "")
+}
+
+// Whether a message is in the trash. Its own TRASH label says so wherever the
+// provider's resource carries one. A HEY posting carries no label for the box
+// it was listed from, so the plain Trash listing is the other witness.
+function inTrash(summary, view) {
+ if (!summary) return false
+ return summary.inTrash === true || plainMailbox(view) === "trash"
+}
+
+// Whether a message is archived: out of the inbox and not somewhere that has
+// its own verb. Spam counts as "its own verb" only where a spam verb exists —
+// an IMAP Junk folder has no report-spam inverse to offer instead, so a Junk
+// message there is the one spam case "Move to Inbox" still means. The verb is
+// the owning mailbox's (`view.hostForId`), because a merged list holds both
+// kinds, and an owner that cannot be found is not taken to lack one.
+function isArchived(summary, view, id) {
+ if (!summary || summary.inInbox !== false || inTrash(summary, view)) return false
+ if (summary.isSent === true || summary.isDraft === true) return false
+ if (summary.inSpam !== true) return true
+ var host = !view ? null : typeof view.hostForId === "function" ? view.hostForId(id) : view
+ return !!host && host.canReportSpam === false
+}
+
+// Whether every one of these rows is in the trash, or archived: the menu and
+// `keyActionFor` ask over the rows an action will reach, never one of them.
+function allInTrash(rows, view) {
+ var list = Array.isArray(rows) ? rows : []
+ for (var i = 0; i < list.length; i++) if (!inTrash(list[i], view)) return false
+ return list.length > 0
+}
+
+function allArchived(rows, view) {
+ var list = Array.isArray(rows) ? rows : []
+ for (var i = 0; i < list.length; i++)
+ if (!isArchived(list[i], view, list[i] ? list[i].id : "")) return false
+ return list.length > 0
+}
+
+// What the archive or trash slot asks for on the rows its action will reach.
+// Where the slot's action is already done for all of them the slot is the way
+// back: `d` restores messages in the trash, `e` moves archived messages in the
+// Archive mailbox to the Inbox. Archived alone is not enough for `e`: on IMAP
+// every folder but the Inbox reads as archived, and `e` in one of them files
+// the message in Archive, which is worth keeping. Anything else is the slot's
+// own action, so a mixed selection lands in one place rather than swapping
+// every row — the rule `starActionFor` keeps for `s`.
+function keyActionFor(action, rows, view) {
+ var verb = String(action || "")
+ if (verb === "trash") return allInTrash(rows, view) ? "untrash" : verb
+ if (verb === "archive" && plainMailbox(view) === "archive" && allArchived(rows, view)) return "unarchive"
+ return verb
+}
+
+// The view a message that is not one of the listing's rows is judged in: the
+// same mailboxes and their spam verbs, and no listing. The listing witnesses
+// where its own rows are (`inTrash`, the Archive rule of `keyActionFor`), not
+// where a message opened from elsewhere is, such as one a new-mail
+// notification opened over the Trash.
+function unlistedView(view) {
+ var on = view || {}
+ return { mailboxKey: "", searchQuery: "", rawQuery: "", canReportSpam: on.canReportSpam,
+ hostForId: function(id) { return typeof on.hostForId === "function" ? on.hostForId(id) : on } }
+}
+
+// The row the reader's own buttons act on when the selection does not
+// reach the open message: the cursor's row while the open message is a
+// member of that row's conversation, else the open message itself. App moves
+// the cursor there before acting, and the list draws the buttons from it.
+function readerTarget(projection, selectedId, cursorId) {
+ var members = projection && Array.isArray(projection.memberIds) ? projection.memberIds : []
+ var cursor = String(cursorId || "")
+ return members.indexOf(selectedId) >= 0 && cursor !== "" ? cursor : String(selectedId || "")
+}
+
+// The words for the four verbs, for the menu, the row and the reader, so a
+// verb reads the same wherever it is offered. Which verb each control offers
+// is its own: the menu offers Move to Inbox for an archived message anywhere,
+// the buttons and `e` only in Archive. Untrash is "Restore", not "Move to Inbox":
+// Gmail's takes the TRASH label off and leaves the rest, so a sent message
+// goes back to Sent, while the other clients move it to the Inbox.
+function actionName(action, labelView) {
+ var verb = String(action || "")
+ if (verb === "archive") return "Archive"
+ if (verb === "trash") return "Move to trash"
+ if (verb === "untrash") return "Restore"
+ if (verb === "unarchive") return labelView === true ? "Move to Inbox and remove label" : "Move to Inbox"
+ return ""
+}
+
// A row carrying a block, with its own flags read the way `Message.summarize`
// reads them: unread and starred are "this message, *or* any counted member".
// A representative that has been read while a reply has not is still an unread
diff --git a/ui/components/MessageList.qml b/ui/components/MessageList.qml
index d729038..ac22f34 100644
--- a/ui/components/MessageList.qml
+++ b/ui/components/MessageList.qml
@@ -37,7 +37,55 @@ Column {
// A row's own star, archive and trash buttons. Routed up rather than
// straight to the service so a ticked row's button means the selection.
signal rowActionRequested(string id, string action)
- signal menuRequested(string id, real sceneX, real sceneY)
+
+ // `ids` are the rows a menu opened here will act on (`reachedIds`).
+ signal menuRequested(string id, real sceneX, real sceneY, var ids)
+
+ // App's own answer to whether an action reaches the ticked rows
+ // (`App.selectionActive`: rows are ticked and the list is on screen). The
+ // list draws what App will do and does not decide it again.
+ property bool selectionActive: false
+
+ // What the archive and trash slots ask for, by binding id, decided over the
+ // rows the action will reach and nothing else (`Model.keyActionFor`), so a
+ // control says what will happen to them. The rows are the ones App's
+ // handler for that control sends the action to: the ticked rows when the
+ // selection is active and the control is about one of them (or is `e`/`d`),
+ // else the cursor's row for the keys, the row itself for a row's own
+ // controls, and for the reader the row it was opened from.
+ readonly property var selectionActions: actionsFor(Model.summariesById(
+ root.service ? root.service.messages : [], root.checkedIds))
+ // With no cursor yet, the next `j` lands on one of this listing's rows, so
+ // the keys are described by all of them: in the Trash `d` restores before a
+ // row is chosen (the hint row and the empty reader say so).
+ readonly property var keyActions: root.selectionActive ? selectionActions
+ : actionsFor(root.cursorId !== "" ? rowsOf(root.cursorId) : (root.service ? root.service.messages : []))
+ // `keys` says whether `e` and `d` reach the same rows as the reader's
+ // buttons and ask the same of them, so its tooltips name a key only then.
+ // An open message that is not a listed row (one a notification opened) is
+ // judged by its own labels: the listing says nothing about where it is.
+ readonly property var readerActions: {
+ var open = root.service ? String(root.service.selectedId || "") : ""
+ if (reaches(open)) return ({ archive: selectionActions.archive, trash: selectionActions.trash, keys: true })
+ var target = Model.readerTarget(root.service ? root.service.conversationProjection : null, open, root.cursorId)
+ var rows = rowsOf(target)
+ var actions = rows.length > 0 ? actionsFor(rows)
+ : actionsFor(root.service && root.service.selectedMessage ? [root.service.selectedMessage] : [],
+ Model.unlistedView(root.service))
+ return ({ archive: actions.archive, trash: actions.trash,
+ keys: !root.selectionActive && target === root.cursorId
+ && actions.archive === keyActions.archive && actions.trash === keyActions.trash })
+ }
+
+ // Whether an action on `id` means the selection: App's `outside` test.
+ function reaches(id) { return root.selectionActive && root.checkedIds.indexOf(id) >= 0 }
+ function reachedIds(id) { return reaches(id) ? root.checkedIds.slice() : [id] }
+ function rowsOf(id) { return Model.summariesById(root.service ? root.service.messages : [], [id]) }
+ function actionsFor(rows, view) {
+ var on = view || root.service
+ return ({ archive: Model.keyActionFor("archive", rows, on),
+ trash: Model.keyActionFor("trash", rows, on) })
+ }
width: parent ? parent.width : 0
spacing: Style.space(2)
@@ -86,6 +134,14 @@ Column {
selectionActive: root.checkedIds.length > 0
ctrlHeld: root.ctrlHeld
canArchive: root.service.canArchive
+ // A ticked row's buttons and middle-click mean the selection.
+ readonly property var slotActions: root.reaches(modelData.id)
+ ? root.selectionActions : root.actionsFor([modelData])
+ archiveAction: slotActions.archive
+ trashAction: slotActions.trash
+ // Hovering does not move the cursor, so `e` and `d` reach this row only
+ // when it is the cursor's, or ticked while the selection is active.
+ namesKeys: root.selectionActive ? root.reaches(modelData.id) : root.cursorId === modelData.id
conversations: Unified.rowIsConversation(modelData)
contentDirection: root.service.contentDirection
onActivated: root.messageActivated(modelData.id)
@@ -93,10 +149,10 @@ Column {
onCheckRangeRequested: root.checkRangeRequested(modelData.id)
onAgentRequested: function(sceneX, sceneY) { root.agentRequested(modelData.id, sceneX, sceneY) }
onStarToggled: root.rowActionRequested(modelData.id, "star")
- onArchiveRequested: root.rowActionRequested(modelData.id, "archive")
- onTrashRequested: root.rowActionRequested(modelData.id, "trash")
+ onArchiveRequested: root.rowActionRequested(modelData.id, archiveAction)
+ onTrashRequested: root.rowActionRequested(modelData.id, trashAction)
onMenuRequested: function(sceneX, sceneY) {
- root.menuRequested(modelData.id, sceneX, sceneY)
+ root.menuRequested(modelData.id, sceneX, sceneY, root.reachedIds(modelData.id))
}
}
}
diff --git a/ui/components/MessageMenu.qml b/ui/components/MessageMenu.qml
index 7fdadaa..c7a768f 100644
--- a/ui/components/MessageMenu.qml
+++ b/ui/components/MessageMenu.qml
@@ -29,24 +29,27 @@ Item {
property real anchorY: 0
property int cursorIndex: -1
readonly property var menuRows: [continueRow, replyRow, replyAllRow, forwardRow, archiveRow,
- unarchiveRow, moveRow,
+ unarchiveRow, untrashRow, moveRow,
trashRow, spamRow, readRow, starRow, browserRow, aiRow]
- // Whether this message is archived — out of the inbox and not somewhere
- // that has its own verb. Read off the summary the menu was opened on rather
- // than asked of the service, because the menu is about one message. IMAP
- // synthesises all four of these from the folder, so one rule serves both
- // kinds of provider. Spam counts as "its own verb" only where a spam verb
- // exists: an IMAP Junk folder has no report-spam inverse to offer instead,
- // so a Junk message there is the one spam case "Move to Inbox" still means.
- readonly property var messageHost: !root.service ? null
- : typeof root.service.hostForId === "function"
- ? root.service.hostForId(root.messageId) : root.service
- readonly property bool archived: !!root.summary
- && root.summary.inInbox === false
- && root.summary.inTrash !== true
- && (root.summary.inSpam !== true || (root.messageHost && root.messageHost.canReportSpam === false))
- && root.summary.isSent !== true
- && root.summary.isDraft !== true
+ // The rows a choice here will act on, as App's handler sends it: every
+ // ticked row when the menu was opened on one of them (the list says which,
+ // `MessageList.reachedIds`), else the one message. Restore, Move to Inbox
+ // and Star or Unstar are decided over all of them: Restore only when every
+ // one is in the trash, Unstar only when every one is starred. Mark read or
+ // unread follows the row the menu was opened on and reaches them all. Move
+ // to Inbox is offered for an archived message anywhere (`Model.isArchived`),
+ // where the row's button offers it only in Archive. IMAP synthesises the
+ // flags from the folder, so one rule serves both kinds of provider.
+ property var reachedIds: []
+ readonly property var reached: {
+ if (!root.summary) return []
+ if (root.memberOnly || root.reachedIds.length < 2) return [root.summary]
+ var rows = Model.summariesById(root.service ? root.service.messages : [], root.reachedIds)
+ return rows.length > 0 ? rows : [root.summary]
+ }
+ readonly property bool archived: Model.allArchived(root.reached, root.service)
+ readonly property bool trashed: Model.allInTrash(root.reached, root.service)
+ readonly property string starAction: Model.starActionFor(root.reached)
// Whether the list it was opened from is a label's, and whether that label
// is one a message can be taken out of — which is the same question
@@ -81,13 +84,19 @@ Item {
anchors.fill: parent
z: 50
- function openAt(id, sceneX, sceneY) {
+ function openAt(id, sceneX, sceneY, ids) {
root.memberOnly = false
+ // Copied by index: through a signal the list arrives as a sequence, not
+ // a JavaScript array.
+ var reached = []
+ for (var i = 0; ids && i < ids.length; i++) reached.push(String(ids[i]))
+ root.reachedIds = reached
openMenu(id, sceneX, sceneY)
}
function openForMember(id, sceneX, sceneY) {
root.memberOnly = true
+ root.reachedIds = []
openMenu(id, sceneX, sceneY)
}
@@ -210,9 +219,21 @@ Item {
MenuRow {
id: unarchiveRow
visible: (!root.service || root.service.canArchive) && root.archived
- text: root.inLabelView ? "Move to Inbox and remove label" : "Move to Inbox"
+ text: Model.actionName("unarchive", root.inLabelView)
onActivated: root.run("unarchive")
}
+ // Out of the trash, by the verb every client has for it — which is why
+ // it needs no capability, and why it is offered on a provider with no
+ // archive and no move, where it is the only way back. Undoing a trash
+ // is not adding INBOX: `labelChangesFor` would leave TRASH on the
+ // message, which is why the row above is not offered here. "Restore"
+ // because where it lands is the provider's (`Model.actionName`).
+ MenuRow {
+ id: untrashRow
+ visible: root.trashed
+ text: Model.actionName("untrash")
+ onActivated: root.run("untrash")
+ }
MenuRow {
id: moveRow
// A member of a conversation is not a row the picker can move on
@@ -221,7 +242,14 @@ Item {
text: "Move to..."
onActivated: root.run("moveToLabel")
}
- MenuRow { id: trashRow; text: "Move to trash"; tone: root.urgentColor; onActivated: root.run("trash") }
+ // Not for a message already there: trashing it again moves nothing.
+ MenuRow {
+ id: trashRow
+ visible: !root.trashed
+ text: Model.actionName("trash")
+ tone: root.urgentColor
+ onActivated: root.run("trash")
+ }
MenuRow {
id: spamRow
visible: !root.service || root.service.canReportSpam
@@ -243,8 +271,8 @@ Item {
MenuRow {
id: starRow
visible: !root.service || root.service.canStar
- text: root.summary && root.summary.starred ? "Unstar" : "Star"
- onActivated: root.run(root.summary && root.summary.starred ? "unstar" : "star")
+ text: root.starAction === "unstar" ? "Unstar" : "Star"
+ onActivated: root.run(root.starAction)
}
MenuSeparatorLine {
diff --git a/ui/components/MessageReader.qml b/ui/components/MessageReader.qml
index 2bfd57a..244ea71 100644
--- a/ui/components/MessageReader.qml
+++ b/ui/components/MessageReader.qml
@@ -6,6 +6,7 @@ import "../message/Direction.js" as Direction
import "../message/Html.js" as Html
import "../message/Message.js" as Mail
import "../message/Mailto.js" as Mailto
+import "../account/Model.js" as Model
// The right column. The body goes through Qt's own rich text engine — a real
// HTML renderer, not a browser — after Html.sanitize has removed what Qt would
@@ -125,6 +126,18 @@ Item {
readonly property var summary: service ? service.selectedMessage : null
readonly property bool isDraft: !!summary && summary.isDraft === true
+ // What the archive and trash buttons ask for, by binding id. The window
+ // decides it over the rows the buttons' action will reach, which are not
+ // always the open message (`MessageList.readerActions`): the selection when
+ // the message is ticked, the conversation's row when a member is open.
+ // `keys` false means `e` and `d` reach other rows, so the tooltips leave
+ // them out rather than name a key that does something else.
+ property var actions: null
+ // What `e` and `d` ask for, for the empty reader's key list.
+ property var keyActions: null
+ readonly property string archiveAction: actions ? actions.archive : "archive"
+ readonly property string trashAction: actions ? actions.trash : "trash"
+ function keyHint(key) { return actions && actions.keys === false ? "" : " · " + key }
// The id the service answers to, which is not always the one on the summary.
// A list made of several mailboxes addresses a row by mailbox and id, and the
@@ -277,6 +290,7 @@ Item {
dimColor: root.dimColor
dimmerColor: root.dimmerColor
panelFontFamily: root.panelFontFamily
+ keyActions: root.keyActions
}
// Nothing known at all, which after the reader learned to open on the list's
@@ -973,9 +987,10 @@ Item {
x: actionGap.x + actionGap.width + messageActions.gap
y: Math.round((parent.height - height) / 2)
visible: !root.service || root.service.canArchive
- iconName: "archive"; tooltipText: "Archive · e"
+ iconName: root.archiveAction === "unarchive" ? "inbox" : "archive"
+ tooltipText: Model.actionName(root.archiveAction) + root.keyHint("e")
foreground: root.dimColor; hoverColor: root.textColor; fontFamily: root.panelFontFamily
- onClicked: root.actionRequested("archive")
+ onClicked: root.actionRequested(root.archiveAction)
}
// Archive under a label, or move to a folder: the same picker `v`
// opens, one press away in the reader too.
@@ -999,9 +1014,10 @@ Item {
? archiveButton.x + archiveButton.width
: actionGap.x + actionGap.width)) + messageActions.gap
y: Math.round((parent.height - height) / 2)
- iconName: "trash"; tooltipText: "Move to trash · d"
+ iconName: root.trashAction === "untrash" ? "undo" : "trash"
+ tooltipText: Model.actionName(root.trashAction) + root.keyHint("d")
foreground: root.dimColor; hoverColor: root.textColor; fontFamily: root.panelFontFamily
- onClicked: root.actionRequested("trash")
+ onClicked: root.actionRequested(root.trashAction)
}
}
diff --git a/ui/components/MessageRow.qml b/ui/components/MessageRow.qml
index 41dd05a..91998c6 100644
--- a/ui/components/MessageRow.qml
+++ b/ui/components/MessageRow.qml
@@ -24,6 +24,14 @@ Rectangle {
? String(root.summary.sourceLabel) : ""
property bool canArchive: true
+ // What the archive and trash buttons ask for. The list asks
+ // `Model.keyActionFor`, the rule `e` and `d` follow, so in the trash the
+ // trash button restores, in Archive the archive button moves the message to
+ // the Inbox, and the key its tooltip names does the same.
+ property string archiveAction: "archive"
+ property string trashAction: "trash"
+ // Whether `e` and `d` act on this row, so its tooltips name them only then.
+ property bool namesKeys: true
// Whether this row stands for a conversation rather than for one message.
// Grouping is a panel rule gated on the provider's `conversations`
// capability; a row is told, and asks nobody.
@@ -114,8 +122,8 @@ Rectangle {
var scene = mapToGlobal(event.x, event.y)
root.menuRequested(scene.x, scene.y)
} else if (event.button === Qt.MiddleButton) {
- // Middle-click archives: the one triage action worth having without
- // moving the pointer to a button.
+ // Middle-click is the archive button, without moving the pointer to
+ // it: Archive, or in Archive, Move to Inbox (`archiveAction`).
root.archiveRequested()
} else if (event.modifiers & Qt.ShiftModifier) {
// Shift selects or clears the range from the cursor to here;
@@ -298,8 +306,8 @@ Rectangle {
// that is a move to a folder, and a server without one would have this
// quietly do nothing.
visible: root.hot && root.canArchive && !root.selectionMode
- iconName: "archive"
- tooltipText: "Archive · e"
+ iconName: root.archiveAction === "unarchive" ? "inbox" : "archive"
+ tooltipText: Model.actionName(root.archiveAction) + (root.namesKeys ? " · e" : "")
foreground: root.dimColor
hoverColor: root.textColor
iconSize: Style.font.iconSmall
@@ -311,8 +319,8 @@ Rectangle {
IconButton {
visible: root.hot && !root.selectionMode
objectName: "message-trash"
- iconName: "trash"
- tooltipText: "Move to trash · d"
+ iconName: root.trashAction === "untrash" ? "undo" : "trash"
+ tooltipText: Model.actionName(root.trashAction) + (root.namesKeys ? " · d" : "")
foreground: root.dimColor
hoverColor: root.textColor
iconSize: Style.font.iconSmall
diff --git a/ui/components/ReaderBlankSlate.qml b/ui/components/ReaderBlankSlate.qml
index f125aa7..c1614ea 100644
--- a/ui/components/ReaderBlankSlate.qml
+++ b/ui/components/ReaderBlankSlate.qml
@@ -42,15 +42,27 @@ Item {
&& (height - centeredColumn.height) / 2
>= versionLabel.implicitHeight + Style.space(12) + Style.space(12)
- readonly property var keys: [
- { key: "j / k", action: "Move through the list" },
- { key: "Enter or o", action: "Open the selected message" },
- { key: "e", action: "Archive" },
- { key: "d", action: "Move to trash" },
- { key: Keymap.hintKeyFor(Keymap.byId("toggleCheck")), action: "Select or deselect a message" },
- { key: "r", action: "Reply" },
- { key: "c", action: "Compose" }
- ]
+ // What `e` and `d` will ask for here, the decision the hint row reads
+ // (`MessageList.keyActions`): Restore in the trash, Move to Inbox in
+ // Archive. `e` is left out where the mailbox has no archive, as the hint
+ // row leaves it out (`unavailableActions`).
+ property var keyActions: null
+ readonly property var keys: {
+ var acts = root.keyActions || ({ archive: "archive", trash: "trash" })
+ var missing = root.service && Array.isArray(root.service.unavailableActions)
+ ? root.service.unavailableActions : []
+ var out = [
+ { key: "j / k", action: "Move through the list" },
+ { key: "Enter or o", action: "Open the selected message" }
+ ]
+ if (missing.indexOf("archive") < 0) out.push({ key: "e", action: Model.actionName(acts.archive) })
+ out.push({ key: "d", action: Model.actionName(acts.trash) })
+ return out.concat([
+ { key: Keymap.hintKeyFor(Keymap.byId("toggleCheck")), action: "Select or deselect a message" },
+ { key: "r", action: "Reply" },
+ { key: "c", action: "Compose" }
+ ])
+ }
Column {
id: centeredColumn
diff --git a/ui/keys/Keymap.js b/ui/keys/Keymap.js
index b178ba8..cc3c091 100644
--- a/ui/keys/Keymap.js
+++ b/ui/keys/Keymap.js
@@ -69,12 +69,19 @@ var BINDINGS = [
{ id: "previousMember", keys: ["p"], contexts: ["reader"],
group: "Moving", label: "Previous message in the conversation" },
+ // Each is the button in its slot, and where that action is already done the
+ // button is its inverse: `d` restores a message in the trash and `e` moves
+ // one in Archive to the Inbox (`Model.keyActionFor`). Re-trashing moves
+ // nothing, so `d` was a key that did nothing there. `inverse` names that
+ // action and its hint, so the hint row says what the key will do.
{ id: "archive", keys: ["e"], contexts: MAIL,
- group: "Acting", label: "Archive",
- hint: { list: "archive", reader: "archive" } },
+ group: "Acting", label: "Archive (in Archive: move to Inbox)",
+ hint: { list: "archive", reader: "archive" },
+ inverse: { action: "unarchive", hint: "move to inbox" } },
{ id: "trash", keys: ["d"], contexts: MAIL,
- group: "Acting", label: "Move to trash",
- hint: { list: "trash", reader: "trash" } },
+ group: "Acting", label: "Move to trash (in the trash: restore)",
+ hint: { list: "trash", reader: "trash" },
+ inverse: { action: "untrash", hint: "restore" } },
{ id: "star", keys: ["s"], contexts: MAIL,
group: "Acting", label: "Star or unstar" },
// `v` because that is the key Gmail moves a message with, and issue #58 asks
@@ -407,15 +414,20 @@ function helpGroups(hidden) {
// what a key means is a property of the application, and only whether it is on
// offer depends on which mailbox is open. `hasSelection` makes the few hints
// that act on a particular row contextual without changing their bindings.
-function hintsFor(context, unavailable, hasSelection) {
+// `actions` says what a binding with an `inverse` will ask for, by binding
+// id; where that is the inverse, the hint names it rather than the key's own
+// verb.
+function hintsFor(context, unavailable, hasSelection, actions) {
var out = []
var rows = bindingsFor(context)
var missing = Array.isArray(unavailable) ? unavailable : []
+ var asked = actions && typeof actions === "object" ? actions : {}
for (var i = 0; i < rows.length; i++) {
if (rows[i].hintNeedsSelection && hasSelection !== true) continue
var unavailableId = rows[i].hintUnavailableId || rows[i].id
if (missing.indexOf(unavailableId) >= 0) continue
var text = hintTextFor(rows[i], context)
+ if (text !== "" && rows[i].inverse && asked[rows[i].id] === rows[i].inverse.action) text = rows[i].inverse.hint
if (text !== "") out.push(({ key: hintKeyFor(rows[i]), label: text }))
}
return out
diff --git a/ui/tests/qml/tst_message_menu_inbox.qml b/ui/tests/qml/tst_message_menu_inbox.qml
index e3f9a38..d2259bb 100644
--- a/ui/tests/qml/tst_message_menu_inbox.qml
+++ b/ui/tests/qml/tst_message_menu_inbox.qml
@@ -23,6 +23,9 @@ Item {
property bool canOpenOnWeb: false
property bool hasLabels: true
property string rawLabelId: ""
+ property string mailboxKey: "inbox"
+ property string searchQuery: ""
+ property string rawQuery: ""
property var messages: []
property var hosts: null
function hostForId(id) { return hosts ? hosts[id] || null : fakeService }
@@ -74,6 +77,17 @@ Item {
menu.close()
fakeService.hosts = null
fakeService.canReportSpam = true
+ fakeService.canArchive = true
+ fakeService.mailboxKey = "inbox"
+ fakeService.searchQuery = ""
+ }
+
+ // A row by what it says, among those drawn: the rows added for the trash
+ // must not be found by a position that moves when a row is added.
+ function shown(text) {
+ for (var i = 0; i < menu.menuRows.length; i++)
+ if (menu.menuRows[i].visible && menu.menuRows[i].text === text) return menu.menuRows[i]
+ return null
}
function archivedMessage() {
@@ -195,6 +209,116 @@ Item {
compare(unarchiveRow().visible, false)
}
+ // ------------------------------------------------- out of the trash
+ //
+ // Untrash is the verb every client has, so Restore needs no capability: it
+ // is offered where there is no archive and no move, and "Move to trash" is
+ // never offered for a message already there.
+
+ function trashedMessage() {
+ var summary = archivedMessage()
+ summary.inTrash = true
+ summary.labelIds = ["TRASH"]
+ return summary
+ }
+
+ function test_a_message_in_the_trash_offers_restore_and_not_trash() {
+ show(trashedMessage())
+ verify(shown("Move to trash") === null, "a message in the trash is not moved to it again")
+ verify(shown("Move to Inbox") === null, "adding INBOX would leave TRASH on it")
+ var restore = shown("Restore")
+ verify(restore !== null)
+ restore.activated()
+ compare(actionSpy.count, 1)
+ compare(actionSpy.signalArguments[0][0], "untrash")
+ compare(actionSpy.signalArguments[0][1], "m1")
+ }
+
+ // HEY: no archive, no move, and a posting that carries no TRASH label.
+ // The plain Trash listing is where it is, and nothing else here gets it out.
+ function test_without_archive_or_a_trash_label_the_trash_listing_offers_it() {
+ fakeService.canArchive = false
+ fakeService.mailboxKey = "trash"
+ var summary = archivedMessage()
+ summary.labelIds = []
+ show(summary)
+ verify(shown("Move to trash") === null)
+ verify(shown("Archive") === null)
+ var restore = shown("Restore")
+ verify(restore !== null)
+ restore.activated()
+ compare(actionSpy.signalArguments[0][0], "untrash")
+ }
+
+ // A search reaches the whole account, whatever mailbox the rail still has.
+ function test_a_search_from_the_trash_is_not_the_trash() {
+ fakeService.mailboxKey = "trash"
+ fakeService.searchQuery = "invoice"
+ var summary = archivedMessage()
+ summary.inInbox = true
+ summary.labelIds = ["INBOX"]
+ show(summary)
+ verify(shown("Restore") === null)
+ verify(shown("Move to trash") !== null)
+ }
+
+ function test_elsewhere_it_is_move_to_trash() {
+ var summary = archivedMessage()
+ summary.inInbox = true
+ show(summary)
+ verify(shown("Restore") === null)
+ var trash = shown("Move to trash")
+ verify(trash !== null)
+ trash.activated()
+ compare(actionSpy.signalArguments[0][0], "trash")
+ }
+
+ function test_the_keyboard_can_reach_restore_in_the_trash() {
+ show(trashedMessage())
+ var steps = 0
+ while (steps < menu.menuRows.length
+ && (menu.cursorIndex < 0 || menu.menuRows[menu.cursorIndex].text !== "Restore")) {
+ menu.moveCursor(1)
+ steps++
+ }
+ compare(menu.menuRows[menu.cursorIndex].text, "Restore", "j steps onto the row rather than over it")
+ menu.runCursor()
+ compare(actionSpy.signalArguments[0][0], "untrash")
+ }
+
+ // Opened on a ticked row, a choice reaches every ticked row, so each verb
+ // is decided over all of them: Restore only when every one is in the
+ // trash, Unstar only when every one is starred.
+ function test_a_ticked_row_decides_over_the_selection() {
+ var inbox = archivedMessage()
+ inbox.id = "m2"
+ inbox.inInbox = true
+ inbox.labelIds = ["INBOX"]
+ var trashed = trashedMessage()
+ trashed.starred = true
+ fakeService.messages = [trashed, inbox]
+ actionSpy.clear()
+ menu.openAt("m1", 100, 100, ["m1", "m2"])
+ wait(20)
+ verify(shown("Restore") === null, "one of them is not in the trash")
+ verify(shown("Unstar") === null, "one of them is not starred")
+ verify(shown("Star") !== null)
+ var trash = shown("Move to trash")
+ verify(trash !== null)
+ trash.activated()
+ compare(actionSpy.signalArguments[0][0], "trash")
+
+ var other = trashedMessage()
+ other.id = "m3"
+ other.starred = true
+ fakeService.messages = [trashed, other]
+ menu.openAt("m1", 100, 100, ["m1", "m3"])
+ wait(20)
+ verify(shown("Restore") !== null, "every one is in the trash")
+ verify(shown("Unstar") !== null, "every one is starred")
+ menu.close()
+ }
+
// ------------------------------------------------------- what it says
function test_from_a_label_it_says_the_label_goes_too() {
diff --git a/ui/tests/qml/tst_trash_restore.qml b/ui/tests/qml/tst_trash_restore.qml
new file mode 100644
index 0000000..e78612d
--- /dev/null
+++ b/ui/tests/qml/tst_trash_restore.qml
@@ -0,0 +1,786 @@
+import QtQuick 2.15
+import QtTest 1.3
+import "../.." as Omamail
+import "BackendFixture.js" as BackendFixture
+import "ModelFixture.js" as NativeModel
+import "NativeIntentFixture.js" as NativeIntentFixture
+import "../../account/Accounts.js" as Accounts
+import "../../account/Unified.js" as Unified
+
+// Restore in the trash and Move to Inbox in Archive, through the real Service,
+// App and MailAccount, with the native intent engine deciding the optimistic
+// change and a client the test controls recording what reaches the provider.
+//
+// HEY declares neither archive nor move, so a message in its Trash had no way
+// out: the menu offered "Move to trash" again, `d` trashed it again, and the
+// untrash every client implements was reachable from nothing. HEY's posting
+// carries no TRASH label either, so the Trash listing itself says where it is.
+//
+// Move to Inbox in Archive comes from the same rule. Every control decides its
+// verb over the rows its action will reach: a ticked row's menu or
+// middle-click, `e` and `d` with rows ticked, and the reader on a ticked
+// message all mean the selection, and the reader on a conversation member
+// means the conversation's row.
+Item {
+ width: 900
+ height: 600
+
+ QtObject {
+ id: shellStore
+ function updateEntryInline(_id, _entry) {}
+ function hide(_id) {}
+ }
+
+ QtObject {
+ id: record
+ property var trashed: []
+ property var untrashed: []
+ property var modified: []
+ function reset() { trashed = []; untrashed = []; modified = [] }
+ }
+
+ Component {
+ id: controlledClient
+ QtObject {
+ property var auth: null
+ property string email: ""
+ function handle() { return ({ aborted: false }) }
+ function later(fn) { Qt.callLater(fn); return handle() }
+ function trashMessage(id, callback) {
+ record.trashed = record.trashed.concat([String(id)])
+ return later(function() { callback(null, "") })
+ }
+ function untrashMessage(id, callback) {
+ record.untrashed = record.untrashed.concat([String(id)])
+ return later(function() { callback(null, "") })
+ }
+ function batchModify(ids, add, remove, callback) {
+ record.modified = record.modified.concat([{ ids: ids.slice().sort().join(","),
+ add: add.join(","), remove: remove.join(",") }])
+ return later(function() { callback(null, "") })
+ }
+ function modifyMessage(id, add, remove, callback) { return batchModify([id], add, remove, callback) }
+ function listMessages() { return handle() }
+ function getMessages() { return handle() }
+ function getMessage() { return handle() }
+ function getSummaries() { return handle() }
+ function getLabels(callback) { return later(function() { callback([], "") }) }
+ function getLabelCounts(id, callback) { return later(function() { callback({ id: id, unread: 0, total: 0, threadsUnread: 0 }, "") }) }
+ function getProfile(callback) { return later(function() { callback({ email: email }, "") }) }
+ function getSendAs(callback) { return later(function() { callback([], "") }) }
+ function getAttachment() { return handle() }
+ function saveDraft() { return handle() }
+ function deleteDraft() { return handle() }
+ function sendMessage() { return handle() }
+ function createLabel() { return handle() }
+ function renameLabel() { return handle() }
+ function deleteLabel() { return handle() }
+ function abortRequest(h) { if (h) h.aborted = true }
+ }
+ }
+
+ Omamail.Service {
+ id: mailService
+ shell: shellStore
+ manifest: ({ id: "omamail", __sourceDir: "/tmp/omamail-test" })
+ }
+
+ Omamail.App { id: app; service: mailService }
+
+ TestCase {
+ name: "TrashRestore"
+ when: windowShown
+
+ function initTestCase() {
+ // Every mailbox made here asks for its cached list. Unanswered, those
+ // requests fill the backend's 64 slots and the actions under test wait
+ // behind them.
+ BackendFixture.install(mailService).answers = {"cache.queryRestore": null}
+ NativeModel.install(mailService)
+ NativeIntentFixture.install(mailService)
+ }
+
+ function entry(provider, email) {
+ var value = { email: email, provider: provider, clientSecret: "", label: "", signature: "",
+ clientId: provider === "outlook" ? "87654321-4321-4abc-9def-1234567890ab" : "" }
+ if (provider === "imap") value.imap = { imapHost: "imap.example.com", imapPort: 993,
+ smtpHost: "smtp.example.com", smtpPort: 465, username: email, aliases: [], insecure: false }
+ if (provider === "jmap") value.jmap = { sessionUrl: "https://api.example.org/jmap/session",
+ username: email, authScheme: "basic", accountId: "u1" }
+ return value
+ }
+
+ // Ready an account the way each sign-in leaves it, with the recording client.
+ function ready(account, provider) {
+ account.clientOverride = controlledClient
+ account.auth.toolsChecked = true
+ account.auth.missingTools = []
+ if (provider === "imap") {
+ account.auth.passwordChecked = true
+ account.auth.password = "test-password"
+ } else if (provider === "jmap") {
+ account.auth.secret = "app-password"
+ account.auth.secretChecked = true
+ } else if (provider === "gmail") {
+ account.auth.credentials = ({ clientId: "123-test.apps.googleusercontent.com",
+ clientSecret: "test", projectId: "test" })
+ account.auth.refreshBusy = true
+ account.auth.loggedIn = true
+ } else {
+ account.auth.loggedIn = true
+ }
+ tryCompare(account, "ready", true)
+ }
+
+ // Accounts on `mailboxKey`, holding `rows` each. A new address each time:
+ // the native ledger is one process for the whole file, and an action a
+ // replaced account left unsettled must not hold up the next one.
+ property int seeded: 0
+ function seedMany(providers, mailboxKey, rowsEach) {
+ var list = Accounts.emptyList()
+ var emails = []
+ for (var i = 0; i < providers.length; i++) {
+ seeded++
+ emails.push("me" + seeded + "@example.com")
+ list = Accounts.add(list, entry(providers[i], emails[i]))
+ }
+ mailService.setUnifiedMailboxes(false)
+ mailService.activeIndex = -1
+ mailService.accountList = list
+ mailService.accountsLoaded = true
+ wait(0)
+ mailService.refreshCurrent()
+ var accounts = []
+ for (var h = 0; h < providers.length; h++) {
+ var account = mailService.accountAt(h)
+ verify(account !== null)
+ ready(account, providers[h])
+ // A host can outlive the account it held, so nothing a previous test
+ // left on it is allowed to stand.
+ account.searchQuery = ""
+ account.rawQuery = ""
+ account.rawLabelId = ""
+ account.mailboxKey = mailboxKey
+ account.messages = rowsEach[h]
+ account.listLoaded = true
+ accounts.push(account)
+ }
+ return accounts
+ }
+
+ function seed(provider, mailboxKey, rows) { return seedMany([provider], mailboxKey, [rows])[0] }
+
+ // The same, merged: turning the merged view on moves every mailbox to the
+ // merged view's mailbox, so the rows are put back after it has.
+ function unified(providers, mailboxKey, rowsEach) {
+ var accounts = seedMany(providers, mailboxKey, rowsEach)
+ mailService.setUnifiedMailboxes(true)
+ mailService.selectMailbox(mailboxKey)
+ wait(0)
+ for (var i = 0; i < accounts.length; i++) {
+ accounts[i].mailboxKey = mailboxKey
+ accounts[i].messages = rowsEach[i]
+ accounts[i].listLoading = false
+ accounts[i].listLoaded = true
+ }
+ tryVerify(function() { return mailService.messages.length === accounts.length })
+ compare(mailService.mailboxKey, mailboxKey)
+ return accounts
+ }
+
+ // A message with these labels, and the flags the summary derives from them.
+ // A HEY posting in Trash has none: nothing in it says where it is.
+ function message(id, labels) {
+ var list = labels || []
+ return ({ id: id, threadId: "", from: { email: "x@example.com", display: "X" }, subject: id,
+ snippet: "", time: "", date: "", unread: false, starred: list.indexOf("STARRED") >= 0,
+ inInbox: list.indexOf("INBOX") >= 0, inTrash: list.indexOf("TRASH") >= 0,
+ inSpam: false, isSent: false, isDraft: false, labelIds: list })
+ }
+
+ 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 having(item, accept) {
+ if (!item) return null
+ if (accept(item)) return item
+ var values = item.children || []
+ for (var i = 0; i < values.length; i++) {
+ var found = having(values[i], accept)
+ if (found) return found
+ }
+ return null
+ }
+
+ // The archive or trash button under `item`, by the key its tooltip names
+ // (`e`, `d`) rather than by a name the change gave it, so the same lookup
+ // finds the button before the change and after.
+ function slot(item, key) {
+ return having(item, function(candidate) {
+ return candidate.iconName !== undefined && candidate.visible
+ && String(candidate.tooltipText || "").slice(-4) === " · " + key
+ })
+ }
+
+ function reader() {
+ var found = having(app, function(item) { return item.forceRichAnyway !== undefined })
+ verify(found !== null)
+ return found
+ }
+
+ // The row drawing `id`, found by the summary it was handed.
+ function rowFor(id) {
+ return having(app, function(item) {
+ return item.summary !== undefined && item.trashRequested !== undefined
+ && !!item.summary && item.summary.id === id
+ })
+ }
+
+ // A popup's rows live under the overlay, not under the menu item, so they
+ // are found in the list the menu's own cursor walks, by what they say.
+ function menuRow(text) {
+ var menu = named(app, "rowMenu")
+ for (var i = 0; i < menu.menuRows.length; i++)
+ if (menu.menuRows[i].visible && menu.menuRows[i].text === text) return menu.menuRows[i]
+ return null
+ }
+
+ function ids(account) {
+ return account.messages.map(function(message) { return message.id }).join(",")
+ }
+
+ function hintLabels() {
+ var hints = named(app, "status-key-hints")
+ verify(hints !== null)
+ return hints.hints.map(function(hint) { return hint.key + " " + hint.label })
+ }
+
+ function tick(ids) {
+ app.checkedAccountId = mailService.activeAccountId
+ app.checkedIds = ids
+ verify(app.selectionActive)
+ }
+
+ // The reader on `id`, in a window wide enough to keep the list beside it.
+ function openReader(account, id, summary) {
+ account.selectedId = id
+ account.selectedMessage = summary
+ app.pushEntry("reader", { id: id })
+ wait(0)
+ verify(!app.compact)
+ verify(app.listOnScreen)
+ }
+
+ function init() {
+ record.reset()
+ app.checkedIds = []
+ app.checkedAccountId = ""
+ app.cursorId = ""
+ app.resetNavigation()
+ mailService.conversationProjection = ({ showsRail: false, stops: [], caption: "", navigation: {}, memberIds: [] })
+ app.open()
+ }
+
+ function cleanup() {
+ var menu = named(app, "rowMenu")
+ if (menu) menu.close()
+ app.close()
+ }
+
+ // ------------------------------------------------- Restore in the trash
+
+ function test_hey_trash_row_button_restores() {
+ var account = seed("hey", "trash", [message("1:2"), message("3:4")])
+ compare(mailService.canArchive, false, "HEY has no archive")
+ compare(mailService.canMoveToLabel, false, "and no move")
+ var row = rowFor("1:2")
+ verify(row !== null)
+ app.cursorId = "1:2"
+ tryCompare(row, "hot", true)
+ var trash = slot(row, "d")
+ verify(trash !== null && trash.visible)
+ compare(trash.tooltipText, "Restore · d")
+ compare(trash.iconName, "undo")
+ trash.clicked()
+ tryCompare(record, "untrashed", ["1:2"])
+ compare(record.trashed, [], "a message in the trash is not trashed again")
+ tryCompare(account, "actionPreparations", 0)
+ compare(ids(account), "3:4", "the row leaves the Trash")
+ tryCompare(mailService, "actionStatus", "Restored")
+ }
+
+ function test_hey_trash_key_restores() {
+ var account = seed("hey", "trash", [message("1:2"), message("3:4")])
+ app.cursorId = "1:2"
+ app.runShortcut("trash", "d")
+ tryCompare(record, "untrashed", ["1:2"])
+ compare(record.trashed, [])
+ tryCompare(account, "actionPreparations", 0)
+ compare(ids(account), "3:4")
+ compare(app.cursorId, "3:4", "the cursor takes the place of the row that left")
+ verify(hintLabels().indexOf("d restore") >= 0, "the hint says what d does here: " + hintLabels())
+ }
+
+ function test_hey_selection_in_trash_restores_every_row() {
+ var account = seed("hey", "trash", [message("1:2"), message("3:4"), message("5:6")])
+ app.cursorId = "1:2"
+ tick(["1:2", "5:6"])
+ app.runShortcut("trash", "d")
+ tryVerify(function() { return record.untrashed.length === 2 })
+ compare(record.untrashed.slice().sort(), ["1:2", "5:6"])
+ compare(record.trashed, [])
+ tryCompare(account, "actionPreparations", 0)
+ compare(ids(account), "3:4")
+ }
+
+ function test_hey_trash_menu_offers_restore_and_not_trash() {
+ seed("hey", "trash", [message("1:2")])
+ rowFor("1:2").menuRequested(100, 100)
+ tryCompare(named(app, "rowMenu"), "opened", true)
+ verify(menuRow("Move to trash") === null, "never Move to trash for a message in the trash")
+ var restore = menuRow("Restore")
+ verify(restore !== null)
+ restore.activated()
+ tryCompare(record, "untrashed", ["1:2"])
+ compare(record.trashed, [])
+ }
+
+ function test_hey_reader_trash_button_restores() {
+ var account = seed("hey", "trash", [message("1:2"), message("3:4")])
+ app.cursorId = "1:2"
+ openReader(account, "1:2", account.messages[0])
+ var button = slot(reader(), "d")
+ verify(button !== null)
+ button.clicked()
+ tryCompare(record, "untrashed", ["1:2"])
+ compare(record.trashed, [])
+ compare(button.tooltipText, "Restore · d")
+ }
+
+ // Untrash reaches each provider's client the same way.
+ function test_trash_key_restores_on_every_provider_data() {
+ return [
+ { tag: "gmail", provider: "gmail", id: "g1" },
+ { tag: "imap", provider: "imap", id: "1:Trash" },
+ { tag: "outlook", provider: "outlook", id: "1:Deleted Items" },
+ { tag: "jmap", provider: "jmap", id: "j1" }
+ ]
+ }
+
+ function test_trash_key_restores_on_every_provider(data) {
+ var account = seed(data.provider, "trash", [message(data.id, ["TRASH"]), message("other", ["TRASH"])])
+ app.cursorId = data.id
+ app.runShortcut("trash", "d")
+ tryCompare(record, "untrashed", [data.id])
+ compare(record.trashed, [])
+ tryCompare(account, "actionPreparations", 0)
+ compare(ids(account), "other")
+ }
+
+ // A merged Trash: each row goes to the mailbox that owns it, HEY's
+ // unlabelled posting included.
+ function test_unified_trash_restores_through_the_owning_mailbox() {
+ var accounts = unified(["hey", "imap"], "trash", [[message("1:2")], [message("7:Trash", ["TRASH"])]])
+ app.cursorId = Unified.unifiedId(accounts[0].accountId, "1:2")
+ app.runShortcut("trash", "d")
+ tryCompare(record, "untrashed", ["1:2"])
+ compare(record.trashed, [])
+ tryVerify(function() { return accounts[0].messages.length === 0 })
+ compare(accounts[1].messages.length, 1, "the other mailbox's row stays")
+ mailService.setUnifiedMailboxes(false)
+ }
+
+ // ----------------------------------------- where nothing should change
+
+ // Outside the Trash `d` trashes, and a search started from the Trash
+ // reaches the whole HEY account, so it is not the Trash.
+ function test_hey_elsewhere_d_trashes() {
+ var account = seed("hey", "inbox", [message("1:2", ["INBOX"])])
+ app.cursorId = "1:2"
+ app.runShortcut("trash", "d")
+ tryCompare(record, "trashed", ["1:2"])
+ compare(record.untrashed, [])
+ verify(hintLabels().indexOf("d trash") >= 0)
+ tryCompare(account, "actionPreparations", 0)
+
+ record.reset()
+ account.mailboxKey = "trash"
+ account.searchQuery = "invoice"
+ account.messages = [message("7:8", ["INBOX"])]
+ app.cursorId = "7:8"
+ app.runShortcut("trash", "d")
+ tryCompare(record, "trashed", ["7:8"])
+ compare(record.untrashed, [], "a search is not the Trash listing")
+ account.searchQuery = ""
+ }
+
+ // `e` in the Inbox and in a folder of one's own still archives: on IMAP
+ // every folder but the Inbox reads as archived, and that is worth keeping.
+ function test_imap_e_archives_from_the_inbox_and_a_folder() {
+ var account = seed("imap", "inbox", [message("1:INBOX", ["INBOX"])])
+ app.cursorId = "1:INBOX"
+ app.runShortcut("archive", "e")
+ tryVerify(function() { return record.modified.length === 1 })
+ compare(record.modified[0].remove, "INBOX")
+ compare(record.modified[0].add, "")
+ tryCompare(account, "actionPreparations", 0)
+
+ record.reset()
+ account.rawQuery = "folder:Receipts"
+ account.messages = [message("3:Receipts")]
+ app.cursorId = "3:Receipts"
+ app.runShortcut("archive", "e")
+ tryVerify(function() { return record.modified.length === 1 })
+ compare(record.modified[0].ids, "3:Receipts")
+ compare(record.modified[0].add, "", "a folder is not Archive: e archives")
+ account.rawQuery = ""
+ }
+
+ // ------------------------------------------- Move to Inbox in Archive
+
+ function test_imap_archive_row_button_moves_to_inbox() {
+ var account = seed("imap", "archive", [message("1:Archive"), message("2:Archive")])
+ var row = rowFor("1:Archive")
+ verify(row !== null)
+ app.cursorId = "1:Archive"
+ tryCompare(row, "hot", true)
+ var archive = slot(row, "e")
+ verify(archive !== null && archive.visible)
+ compare(archive.iconName, "inbox")
+ compare(archive.tooltipText, "Move to Inbox · e")
+ compare(slot(row, "d").tooltipText, "Move to trash · d", "the trash button is unchanged in Archive")
+ archive.clicked()
+ tryVerify(function() { return record.modified.length === 1 })
+ compare(record.modified[0].ids, "1:Archive")
+ compare(record.modified[0].add, "INBOX", "the existing unarchive: INBOX added")
+ tryCompare(account, "actionPreparations", 0)
+ compare(ids(account), "2:Archive", "on a folder provider the row leaves Archive")
+ }
+
+ function test_imap_archive_key_moves_to_inbox() {
+ seed("imap", "archive", [message("1:Archive"), message("2:Archive")])
+ app.cursorId = "1:Archive"
+ app.runShortcut("archive", "e")
+ tryVerify(function() { return record.modified.length === 1 })
+ compare(record.modified[0].add, "INBOX")
+ compare(record.modified[0].remove, "")
+ verify(hintLabels().indexOf("e move to inbox") >= 0, "the hint says what e does here: " + hintLabels())
+ }
+
+ function test_imap_archive_reader_button_moves_to_inbox() {
+ var account = seed("imap", "archive", [message("1:Archive"), message("2:Archive")])
+ app.cursorId = "1:Archive"
+ openReader(account, "1:Archive", account.messages[0])
+ var archive = slot(reader(), "e")
+ verify(archive !== null && archive.visible)
+ archive.clicked()
+ tryVerify(function() { return record.modified.length === 1 })
+ compare(record.modified[0].ids, "1:Archive")
+ compare(record.modified[0].add, "INBOX")
+ compare(archive.tooltipText, "Move to Inbox · e")
+ }
+
+ function test_unified_archive_moves_to_inbox_through_the_owning_mailbox() {
+ var accounts = unified(["imap", "imap"], "archive", [[message("1:Archive")], [message("1:Archive")]])
+ app.cursorId = Unified.unifiedId(accounts[1].accountId, "1:Archive")
+ app.runShortcut("archive", "e")
+ tryVerify(function() { return record.modified.length === 1 })
+ compare(record.modified[0].ids, "1:Archive")
+ compare(record.modified[0].add, "INBOX")
+ tryVerify(function() { return accounts[1].messages.length === 0 })
+ compare(accounts[0].messages.length, 1, "the other mailbox's row stays")
+ mailService.setUnifiedMailboxes(false)
+ }
+
+ // --------------------------------------- the rows the action reaches
+
+ // Gmail's `in:anywhere` lists a message in the trash beside one in the
+ // Inbox. With both ticked, every control that reaches the selection
+ // trashes both, and says so: Restore would take a message that is not in
+ // the trash "out" of it.
+ function mixedGmailSelection() {
+ var account = seed("gmail", "inbox", [message("t1", ["TRASH"]), message("i1", ["INBOX"])])
+ account.searchQuery = "in:anywhere invoice"
+ app.cursorId = "t1"
+ tick(["t1", "i1"])
+ return account
+ }
+
+ function test_reader_on_a_ticked_message_trashes_a_mixed_selection() {
+ var account = mixedGmailSelection()
+ openReader(account, "t1", account.messages[0])
+ var button = slot(reader(), "d")
+ verify(button !== null)
+ button.clicked()
+ tryVerify(function() { return record.trashed.length === 2 })
+ compare(record.untrashed, [])
+ compare(button.tooltipText, "Move to trash · d", "the reader's verb is the selection's")
+ account.searchQuery = ""
+ }
+
+ function test_reader_on_a_ticked_message_restores_a_trashed_selection() {
+ var account = seed("gmail", "trash", [message("t1", ["TRASH"]), message("t2", ["TRASH"]), message("t3", ["TRASH"])])
+ app.cursorId = "t1"
+ tick(["t1", "t2"])
+ openReader(account, "t1", account.messages[0])
+ var button = slot(reader(), "d")
+ compare(button.tooltipText, "Restore · d")
+ button.clicked()
+ tryVerify(function() { return record.untrashed.length === 2 })
+ compare(record.untrashed.slice().sort(), ["t1", "t2"])
+ compare(record.trashed, [])
+ }
+
+ function test_menu_on_a_ticked_row_trashes_a_mixed_selection() {
+ var account = mixedGmailSelection()
+ rowFor("t1").menuRequested(100, 100)
+ tryCompare(named(app, "rowMenu"), "opened", true)
+ verify(menuRow("Restore") === null, "not every row it reaches is in the trash")
+ var trash = menuRow("Move to trash")
+ verify(trash !== null)
+ trash.activated()
+ tryVerify(function() { return record.trashed.length === 2 })
+ compare(record.untrashed, [])
+ account.searchQuery = ""
+ }
+
+ function test_d_trashes_a_mixed_selection() {
+ var account = mixedGmailSelection()
+ verify(hintLabels().indexOf("d trash") >= 0, "the hint names trash: " + hintLabels())
+ app.runShortcut("trash", "d")
+ tryVerify(function() { return record.trashed.length === 2 })
+ compare(record.untrashed, [])
+ account.searchQuery = ""
+ }
+
+ // A menu on a ticked row stars or unstars the whole selection, and says
+ // which: Unstar only when every ticked row is starred.
+ function test_menu_on_a_ticked_row_names_the_selections_star() {
+ seed("gmail", "inbox", [message("s1", ["INBOX", "STARRED"]), message("s2", ["INBOX"])])
+ app.cursorId = "s1"
+ tick(["s1", "s2"])
+ rowFor("s1").menuRequested(100, 100)
+ tryCompare(named(app, "rowMenu"), "opened", true)
+ verify(menuRow("Unstar") === null, "one of them is not starred")
+ var star = menuRow("Star")
+ verify(star !== null)
+ star.activated()
+ tryVerify(function() { return record.modified.length === 1 })
+ compare(record.modified[0].ids, "s1,s2")
+ compare(record.modified[0].add, "STARRED")
+ }
+
+ // JMAP lets a message be in the Inbox and Archive at once. Middle-click is
+ // the archive button, and on a ticked row it means the selection.
+ function test_middle_click_on_a_ticked_row_archives_a_mixed_selection() {
+ seed("jmap", "archive", [message("a1"), message("a2", ["INBOX"])])
+ app.cursorId = "a1"
+ tick(["a1", "a2"])
+ rowFor("a1").archiveRequested()
+ tryVerify(function() { return record.modified.length === 1 })
+ compare(record.modified[0].ids, "a1,a2")
+ compare(record.modified[0].remove, "INBOX", "archived, not moved to the Inbox")
+ compare(record.modified[0].add, "")
+ }
+
+ // A conversation listed in Archive, with `n` on a member that is in the
+ // Inbox: `e` and the reader's button both act on the conversation's row,
+ // so both move it to the Inbox, and the button says so.
+ function test_reader_on_a_conversation_member_follows_the_row() {
+ var row = message("m1")
+ row.thread = { id: "c", count: 2, unread: false, flagged: false, memberIds: ["m1", "m2"] }
+ var account = seed("jmap", "archive", [row])
+ app.cursorId = "m1"
+ openReader(account, "m2", message("m2", ["INBOX"]))
+ // The rail as the backend projects it, once the projection asked for on
+ // opening has landed.
+ wait(100)
+ mailService.conversationProjection = ({ showsRail: true, stops: [], caption: "",
+ navigation: {}, memberIds: ["m1", "m2"] })
+ wait(50)
+ compare(mailService.conversationProjection.memberIds, ["m1", "m2"])
+ var button = slot(reader(), "e")
+ verify(button !== null && button.visible)
+ compare(button.tooltipText, "Move to Inbox · e", "the button says what e does")
+ button.clicked()
+ tryVerify(function() { return record.modified.length === 1 })
+ compare(record.modified[0].ids, "m1,m2", "the row's action reaches every member")
+ compare(record.modified[0].add, "INBOX")
+ }
+
+ // With rows ticked, `d` reaches them, while the reader's buttons reach the
+ // open message when it is not one of them. The button then names no key:
+ // here `d` restores the ticked rows and the button trashes the open one.
+ function test_reader_names_no_key_that_reaches_other_rows() {
+ var account = seed("gmail", "inbox", [message("t1", ["TRASH"]), message("t2", ["TRASH"]), message("i1", ["INBOX"])])
+ account.searchQuery = "in:anywhere invoice"
+ app.cursorId = "i1"
+ tick(["t1", "t2"])
+ openReader(account, "i1", account.messages[2])
+ var button = having(reader(), function(item) {
+ return item.iconName !== undefined && item.visible && item.tooltipText === "Move to trash"
+ })
+ verify(button !== null, "the reader's trash button names no key")
+ app.runShortcut("trash", "d")
+ tryVerify(function() { return record.untrashed.length === 2 })
+ compare(record.untrashed.slice().sort(), ["t1", "t2"], "d restores the ticked rows")
+ compare(record.trashed, [])
+ tryCompare(account, "actionPreparations", 0)
+ record.reset()
+ account.selectedId = "i1"
+ account.selectedMessage = message("i1", ["INBOX"])
+ button.clicked()
+ tryCompare(record, "trashed", ["i1"])
+ compare(record.untrashed, [])
+ account.searchQuery = ""
+ }
+
+ // In a narrow window the reader replaces the list and the ticks are not
+ // on screen, so App acts on the open message alone. The list must decide
+ // with App's answer, not its own reading of the ticks: `d` and the
+ // reader's button here act on the open message whatever is ticked.
+ function compactReader(account, id, summary) {
+ var window = having(app, function(item) { return item.title === "Omamail" })
+ verify(window !== null)
+ window.width = 600
+ app.pushEntry("reader", { id: id })
+ account.selectedId = id
+ account.selectedMessage = summary
+ wait(0)
+ verify(app.compact)
+ verify(!app.selectionActive, "the ticks are not on screen")
+ return window
+ }
+
+ function test_compact_reader_d_acts_on_the_open_message() {
+ var account = seed("gmail", "inbox", [message("t1", ["TRASH"]), message("t2", ["TRASH"]), message("i1", ["INBOX"])])
+ account.searchQuery = "in:anywhere invoice"
+ app.cursorId = "i1"
+ app.checkedAccountId = mailService.activeAccountId
+ app.checkedIds = ["t1", "t2"]
+ var window = compactReader(account, "i1", account.messages[2])
+ app.runShortcut("trash", "d")
+ tryCompare(record, "trashed", ["i1"])
+ compare(record.untrashed, [], "the ticked rows are not what d reaches here")
+ window.width = 980
+ account.searchQuery = ""
+ }
+
+ function test_compact_reader_button_acts_on_the_open_message() {
+ var account = seed("gmail", "inbox", [message("t1", ["TRASH"]), message("i1", ["INBOX"])])
+ account.searchQuery = "in:anywhere invoice"
+ app.cursorId = "t1"
+ app.checkedAccountId = mailService.activeAccountId
+ app.checkedIds = ["t1", "i1"]
+ var window = compactReader(account, "t1", account.messages[0])
+ var button = slot(reader(), "d")
+ verify(button !== null)
+ compare(button.tooltipText, "Restore · d", "the open message alone is in the trash")
+ button.clicked()
+ tryCompare(record, "untrashed", ["t1"])
+ compare(record.trashed, [])
+ window.width = 980
+ account.searchQuery = ""
+ }
+
+ // A message a notification opened over the Trash is not one of its rows,
+ // so the listing says nothing about it: an Inbox message there is moved
+ // to the trash, and the reader's button and `d` both say and do that.
+ function test_a_message_opened_from_outside_the_trash_listing_is_trashed() {
+ var account = seed("gmail", "trash", [message("t1", ["TRASH"])])
+ var outside = message("n1", ["INBOX"])
+ account.previewMessages = [outside]
+ app.cursorId = "n1"
+ openReader(account, "n1", outside)
+ var button = slot(reader(), "d")
+ verify(button !== null, "the button names d, which reaches the same message")
+ compare(button.tooltipText, "Move to trash · d")
+ app.runShortcut("trash", "d")
+ tryCompare(record, "trashed", ["n1"])
+ compare(record.untrashed, [])
+ tryCompare(account, "actionPreparations", 0)
+ record.reset()
+ account.previewMessages = [outside]
+ account.selectedId = "n1"
+ account.selectedMessage = outside
+ app.cursorId = "n1"
+ button.clicked()
+ tryCompare(record, "trashed", ["n1"])
+ compare(record.untrashed, [])
+ }
+
+ // Hovering does not move the cursor, so a row names `d` only when `d`
+ // reaches it: hovering a trashed row beside an Inbox cursor shows Restore
+ // without the key, while `d` trashes the cursor's row.
+ function test_a_row_names_d_only_when_d_reaches_it() {
+ var account = mixedGmailSelection()
+ app.checkedIds = []
+ app.cursorId = "i1"
+ var trashed = rowFor("t1")
+ var restore = having(trashed, function(item) { return item.iconName === "undo" })
+ verify(restore !== null)
+ compare(restore.tooltipText, "Restore", "d does not reach a row the pointer is only resting on")
+ compare(slot(rowFor("i1"), "d").tooltipText, "Move to trash · d")
+ app.runShortcut("trash", "d")
+ tryCompare(record, "trashed", ["i1"])
+ compare(record.untrashed, [])
+ account.searchQuery = ""
+ }
+
+ // A reload that takes the open message's row away moves the cursor to
+ // another row: `d` now reaches that row, so the reader's button, which
+ // still means the open message, names no key.
+ function test_reader_names_no_key_once_the_cursor_moved_off_its_row() {
+ var account = seed("gmail", "inbox", [message("r1", ["INBOX"]), message("r2", ["INBOX"])])
+ app.cursorId = "r1"
+ openReader(account, "r1", account.messages[0])
+ compare(slot(reader(), "d").tooltipText, "Move to trash · d")
+ account.messages = [message("r2", ["INBOX"])]
+ app.cursorId = "r2"
+ wait(0)
+ var button = having(reader(), function(item) {
+ return item.iconName === "trash" && item.visible
+ })
+ verify(button !== null)
+ compare(button.tooltipText, "Move to trash", "d reaches r2 now, the button r1")
+ app.runShortcut("trash", "d")
+ tryCompare(record, "trashed", ["r2"])
+ }
+
+ // The empty reader lists the keys that do something here, and `e` and `d`
+ // are listed as what they will do: Restore in the trash, Move to Inbox in
+ // Archive, no `e` at all where there is no archive.
+ function blankSlateLines() {
+ var slate = having(app, function(item) { return item.keys !== undefined && item.showLegend !== undefined })
+ verify(slate !== null)
+ return slate.keys.map(function(line) { return line.key + " " + line.action })
+ }
+
+ function test_empty_reader_lists_what_e_and_d_do_here() {
+ seed("hey", "trash", [message("1:2"), message("3:4")])
+ var lines = blankSlateLines()
+ verify(lines.indexOf("d Restore") >= 0, "in the trash: " + lines)
+ verify(lines.indexOf("d Move to trash") < 0)
+ verify(lines.indexOf("e Archive") < 0, "HEY has no archive: " + lines)
+ verify(hintLabels().indexOf("d restore") >= 0, "the hint row agrees: " + hintLabels())
+
+ seed("imap", "archive", [message("1:Archive"), message("2:Archive")])
+ lines = blankSlateLines()
+ verify(lines.indexOf("e Move to Inbox") >= 0, "in Archive: " + lines)
+ verify(lines.indexOf("d Move to trash") >= 0)
+
+ seed("imap", "inbox", [message("1:INBOX", ["INBOX"])])
+ lines = blankSlateLines()
+ verify(lines.indexOf("e Archive") >= 0, "in the Inbox: " + lines)
+ verify(lines.indexOf("d Move to trash") >= 0)
+ }
+ }
+}
diff --git a/ui/tests/test_keymap.js b/ui/tests/test_keymap.js
index 3348c09..be124c7 100644
--- a/ui/tests/test_keymap.js
+++ b/ui/tests/test_keymap.js
@@ -278,6 +278,20 @@ deepEqual(selectedListHints.map(function (h) { return h.key + " " + h.label }),
assert.ok(!keymap.hintsFor("list", ["move"], true).some(function (h) {
return h.key === "v"
}), "a provider without move does not offer the move hint")
+// Where `e` or `d` is the way back, its hint says so rather than naming a verb
+// the key will not perform (`Model.keyActionFor` decides which).
+deepEqual(keymap.hintsFor("list", [], true, { archive: "archive", trash: "untrash" }).map(function (h) { return h.key + " " + h.label }),
+ ["j / k move", "e archive", "d restore", "v move to", "Space select", "c compose"],
+ "in the trash, d restores")
+deepEqual(keymap.hintsFor("reader", [], true, { archive: "unarchive", trash: "trash" }).filter(function (h) {
+ return h.key === "e" || h.key === "d" }).map(function (h) { return h.key + " " + h.label }),
+ ["e move to inbox", "d trash"], "in Archive, e is the way back")
+deepEqual(keymap.hintsFor("list", ["archive", "star", "move"], true, { archive: "unarchive", trash: "untrash" }).map(function (h) { return h.key }),
+ ["j / k", "d", "Space", "c"], "a provider with no archive still drops e, whatever it would ask for")
+deepEqual(keymap.hintsFor("list", [], true, { archive: "archive", trash: "trash" }), selectedListHints,
+ "the keys' own verbs change nothing")
+deepEqual(keymap.hintsFor("list", [], true, { archive: "untrash", trash: "unarchive" }), selectedListHints,
+ "a key's hint changes only for its own way back")
const composeHints = keymap.hintsFor("compose")
deepEqual(composeHints.map(function (h) { return h.label }),
["send", "close"],
diff --git a/ui/tests/test_model.js b/ui/tests/test_model.js
index 0fa00ef..2a13f8b 100644
--- a/ui/tests/test_model.js
+++ b/ui/tests/test_model.js
@@ -1763,3 +1763,103 @@ assert.strictEqual(model.monitoredNote([]), "")
// A provider with no move verb is told so in the hints, the way archive is.
deepEqual(model.unavailableActions({ archive: true, star: true, move: true }), [])
deepEqual(model.unavailableActions({ archive: true, star: true }), ["move"])
+
+// ------------------------------------------------------- the way back
+//
+// `e` and `d` are their buttons, and where the button's action is already done
+// it is the way back. A message in the trash cannot be trashed again — that
+// moved nothing — and on HEY, which has no archive and no move, untrash is the
+// only way out of the trash at all.
+{
+ const plain = (key) => ({ mailboxKey: key, searchQuery: "", rawQuery: "" })
+ const labelled = { id: "g1", inInbox: false, inTrash: true, labelIds: ["TRASH"] }
+ // A HEY posting says nothing about the box it was listed from.
+ const posting = { id: "1:2", inInbox: false, inTrash: false, labelIds: [] }
+ const inbox = { id: "i1", inInbox: true, inTrash: false, labelIds: ["INBOX"] }
+ const filed = { id: "a1", inInbox: false, inTrash: false, inSpam: false,
+ isSent: false, isDraft: false, labelIds: [] }
+
+ assert.strictEqual(model.inTrash(labelled, plain("inbox")), true, "its own TRASH label says so anywhere")
+ assert.strictEqual(model.inTrash(posting, plain("trash")), true, "the plain Trash listing says so for HEY")
+ assert.strictEqual(model.inTrash(posting, plain("papertrail")), false)
+ assert.strictEqual(model.inTrash(posting, { mailboxKey: "trash", searchQuery: "invoice", rawQuery: "" }), false,
+ "a search reaches the whole account, whatever mailbox the rail still has")
+ assert.strictEqual(model.inTrash(posting, { mailboxKey: "trash", searchQuery: "", rawQuery: "label:Bills" }), false,
+ "a label view is somewhere else")
+ assert.strictEqual(model.inTrash(null, plain("trash")), false)
+
+ assert.strictEqual(model.keyActionFor("trash", [labelled], plain("trash")), "untrash")
+ assert.strictEqual(model.keyActionFor("trash", [posting], plain("trash")), "untrash")
+ assert.strictEqual(model.keyActionFor("trash", [inbox], plain("inbox")), "trash")
+ assert.strictEqual(model.keyActionFor("trash", [labelled, inbox], plain("inbox")), "trash",
+ "a mixed selection lands in one place rather than swapping every row")
+ assert.strictEqual(model.keyActionFor("trash", [labelled, posting], plain("trash")), "untrash")
+ assert.strictEqual(model.keyActionFor("trash", [], plain("trash")), "trash", "no rows, no change")
+
+ // `e` turns back only in Archive: on IMAP every folder but the Inbox reads as
+ // archived, and `e` there files the message in Archive.
+ assert.strictEqual(model.keyActionFor("archive", [filed], plain("archive")), "unarchive")
+ assert.strictEqual(model.keyActionFor("archive", [filed], { mailboxKey: "archive", searchQuery: "x", rawQuery: "" }),
+ "archive", "a search from Archive is not Archive")
+ assert.strictEqual(model.keyActionFor("archive", [filed], { mailboxKey: "inbox", searchQuery: "", rawQuery: "folder:Receipts" }),
+ "archive", "a folder of one's own still archives")
+ assert.strictEqual(model.keyActionFor("archive", [filed], plain("all")), "archive")
+ assert.strictEqual(model.keyActionFor("archive", [{ ...filed, inInbox: true }], plain("archive")), "archive",
+ "a message that is in the inbox as well can still be archived")
+ assert.strictEqual(model.keyActionFor("archive", [labelled], plain("trash")), "archive",
+ "the archive key is not the way out of the trash")
+ assert.strictEqual(model.keyActionFor("star", [labelled], plain("trash")), "star", "other keys are their own")
+
+ // The menu's archived rule, now shared: spam is archived only where the
+ // owning mailbox has no spam verb, and an owner that cannot be found is not
+ // taken to lack one.
+ const junk = { ...filed, inSpam: true }
+ assert.strictEqual(model.isArchived(filed, plain("archive"), "a1"), true)
+ assert.strictEqual(model.isArchived(posting, plain("trash"), "1:2"), false, "in the trash is not archived")
+ assert.strictEqual(model.isArchived(junk, { canReportSpam: false }, "a1"), true)
+ assert.strictEqual(model.isArchived(junk, { canReportSpam: true }, "a1"), false)
+ assert.strictEqual(model.isArchived(junk, { hostForId: () => null }, "a1"), false)
+ assert.strictEqual(model.isArchived(junk, { hostForId: (id) => id === "a1" ? { canReportSpam: false } : null }, "a1"), true)
+ assert.strictEqual(model.isArchived({ ...filed, isSent: true }, plain("sent"), "a1"), false)
+
+ // Over every row an action reaches: one that is not there is enough to say no.
+ assert.strictEqual(model.allInTrash([labelled, posting], plain("trash")), true)
+ assert.strictEqual(model.allInTrash([labelled, inbox], plain("inbox")), false)
+ assert.strictEqual(model.allInTrash([], plain("trash")), false, "nothing reached is nothing to restore")
+ assert.strictEqual(model.allArchived([filed, { ...filed, id: "a2" }], plain("archive")), true)
+ assert.strictEqual(model.allArchived([filed, { ...filed, id: "a2", inInbox: true }], plain("archive")), false)
+ assert.strictEqual(model.allArchived([], plain("archive")), false)
+
+ // A message that is not a listed row is judged by its own labels: an Inbox
+ // message a notification opened over the Trash is trashed, not restored.
+ const opened = { id: "n1", inInbox: true, inTrash: false, labelIds: ["INBOX"] }
+ assert.strictEqual(model.keyActionFor("trash", [opened], plain("trash")), "untrash",
+ "as a row of the Trash listing it would count as in the trash")
+ assert.strictEqual(model.keyActionFor("trash", [opened], model.unlistedView(plain("trash"))), "trash")
+ assert.strictEqual(model.keyActionFor("trash", [labelled], model.unlistedView(plain("inbox"))), "untrash",
+ "its own TRASH label still says so")
+ assert.strictEqual(model.keyActionFor("archive", [filed], model.unlistedView(plain("archive"))), "archive")
+ const owner = { canReportSpam: false }
+ assert.strictEqual(model.isArchived({ ...filed, inSpam: true },
+ model.unlistedView({ hostForId: () => owner }), "a1"), true, "the owning mailbox still decides spam")
+
+ // The row the reader's buttons land on without a selection: the cursor's
+ // row for a conversation member, the open message otherwise — App moves the
+ // cursor there and the list draws from it.
+ const rail = { memberIds: ["m1", "m2"] }
+ assert.strictEqual(model.readerTarget(rail, "m2", "m1"), "m1")
+ assert.strictEqual(model.readerTarget(rail, "m2", ""), "m2", "no cursor: the open message")
+ assert.strictEqual(model.readerTarget(rail, "x9", "m1"), "x9", "not a member: the open message")
+ assert.strictEqual(model.readerTarget(null, "x9", "m1"), "x9")
+
+ // Restore, not Move to Inbox: Gmail's untrash takes TRASH off and leaves the
+ // rest, so a sent message goes back to Sent.
+ assert.strictEqual(model.actionName("untrash"), "Restore")
+ assert.strictEqual(model.actionName("unarchive"), "Move to Inbox")
+ assert.strictEqual(model.actionName("unarchive", true), "Move to Inbox and remove label")
+ assert.strictEqual(model.actionName("trash"), "Move to trash")
+ assert.strictEqual(model.actionName("archive"), "Archive")
+ // An immediate action: no ellipsis.
+ for (const verb of ["archive", "unarchive", "trash", "untrash"])
+ assert.ok(!/\.\.\.$/.test(model.actionName(verb)), verb + " opens nothing")
+}
From 4ea8864aefdfb3b6bd391f6835b0fd813f6ecde7 Mon Sep 17 00:00:00 2001
From: Oliver Lukschander
Date: Mon, 19 Oct 2026 03:58:42 +0200
Subject: [PATCH 35/88] Fix display-name quoting in composed address headers
and inserted contacts (#368)
---
src/backend/mail.rs | 4 +-
src/mail/send.rs | 10 +-
src/mail/send_tests.rs | 18 ++
src/message/compose.rs | 119 ++++++--
src/message/content.rs | 5 +
src/message/parity_tests.rs | 373 +++++++++++++++++++++++
ui/account/Accounts.js | 6 +-
ui/account/Rsvp.qml | 16 +-
ui/account/Unsubscribe.qml | 12 +-
ui/compose/Recipients.js | 10 +-
ui/message/Message.js | 139 +++++++--
ui/tests/qml/tst_calendar_attendance.qml | 11 +
ui/tests/qml/tst_unsubscribe_backend.qml | 29 ++
ui/tests/test_accounts.js | 2 +
ui/tests/test_calendar.js | 12 +
ui/tests/test_message.js | 101 ++++++
ui/tests/test_recipients.js | 30 ++
ui/tests/test_unsubscribe.js | 14 +
18 files changed, 831 insertions(+), 80 deletions(-)
diff --git a/src/backend/mail.rs b/src/backend/mail.rs
index 4317990..2031f05 100644
--- a/src/backend/mail.rs
+++ b/src/backend/mail.rs
@@ -26,7 +26,7 @@ fn configured_identities(settings: &Value) -> Result {
// hand-edited entry names agent sends exactly as it names composer sends
// instead of failing them.
fn sender_name(raw: &str) -> String {
- let line: String = raw.chars().map(|c| if c.is_ascii_control() { ' ' } else { c }).collect();
+ let line: String = raw.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
line.split(' ').filter(|word| !word.is_empty()).collect::>().join(" ").trim().to_string()
}
@@ -642,6 +642,8 @@ mod tests {
assert_eq!(unnamed, json!([{"email":"me@example.org","displayName":"","isPrimary":true,"isDefault":true}]));
let edited = configured_identities(&json!({"email":"me@example.org","senderName":"Jane\r\nBcc: x@example.org\u{7f}\tExample"})).unwrap();
assert_eq!(edited[0]["displayName"], "Jane Bcc: x@example.org Example", "one header line, as the UI stores it");
+ let c1 = configured_identities(&json!({"email":"me@example.org","senderName":"Jane\u{85}Example\u{9f}"})).unwrap();
+ assert_eq!(c1[0]["displayName"], "Jane Example", "a C1 control too, which the composer would refuse");
}
#[test]
diff --git a/src/mail/send.rs b/src/mail/send.rs
index 4787890..f9af812 100644
--- a/src/mail/send.rs
+++ b/src/mail/send.rs
@@ -70,12 +70,10 @@ fn display(email: &str, name: &str) -> String {
if name.is_empty() {
return email.into();
}
- let name = if name.chars().any(|c| "\"\\,;<>@():[]".contains(c)) {
- format!("\"{}\"", name.replace('\\', "\\\\").replace('"', "\\\""))
- } else {
- name.to_owned()
- };
- format!("{name} <{email}>")
+ format!(
+ "{} <{email}>",
+ crate::message::compose::quoted_phrase(name, false)
+ )
}
fn parsed(value: &str) -> Result> {
diff --git a/src/mail/send_tests.rs b/src/mail/send_tests.rs
index cb32be2..befd01a 100644
--- a/src/mail/send_tests.rs
+++ b/src/mail/send_tests.rs
@@ -91,6 +91,24 @@ fn encoded_header_words_cannot_change_the_previewed_envelope() {
assert!(send::prepare(&request, &identities()).is_err());
}
+#[test]
+fn preview_quotes_names_with_the_composers_rule() {
+ let mut request = request();
+ request.to = vec![
+ "\"Dr. Jane\" , \"Team: eve@example.net;\" , Ann Lee "
+ .into(),
+ ];
+ let preview = send::prepare(&request, &identities()).unwrap().preview();
+ assert_eq!(
+ preview["to"],
+ json!([
+ "\"Dr. Jane\" ",
+ "\"Team: eve@example.net;\" ",
+ "Ann Lee "
+ ])
+ );
+}
+
#[test]
fn actual_composed_sender_and_recipients_must_match_the_authorized_plan() {
let fields = json!({"from":"alias@example.org","to":"to@example.org","cc":"cc@example.org","bcc":"bcc@example.org"});
diff --git a/src/message/compose.rs b/src/message/compose.rs
index 11b8307..fbb669b 100644
--- a/src/message/compose.rs
+++ b/src/message/compose.rs
@@ -35,19 +35,27 @@ fn header(value: &str) -> Result {
}
Ok(out)
}
+// RFC 5322 specials: a display name holding one is one name only when quoted.
+const SPECIALS: &[char] = &[
+ '(', ')', '<', '>', '[', ']', ':', ';', '@', '\\', ',', '.', '"',
+];
+/// A display name as a quoted-string, `"` and `\` escaped: `always` in a header,
+/// and in address text a person reads only when the name holds a special.
+pub(crate) fn quoted_phrase(value: &str, always: bool) -> String {
+ if value.is_empty() || (!always && !value.contains(SPECIALS)) {
+ return value.into();
+ }
+ format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
+}
+/// A display name in a header: one encoded word when it is not ASCII or holds
+/// `=?`, which readers decode even inside quotes; otherwise quoted.
fn phrase(value: &str) -> Result {
let value = header(value)?;
let value = value.trim();
- if value.is_empty() {
- return Ok(String::new());
- }
- if !value.is_ascii() {
+ if !value.is_ascii() || value.contains("=?") {
return Ok(format!("=?UTF-8?B?{}?=", STANDARD.encode(value)));
}
- Ok(format!(
- "\"{}\"",
- value.replace('\\', "\\\\").replace('"', "\\\"")
- ))
+ Ok(quoted_phrase(value, true))
}
fn fold(name: &str, value: &str) -> Result {
let value = header(value)?;
@@ -57,38 +65,83 @@ fn fold(name: &str, value: &str) -> Result {
format!("{name}: =?UTF-8?B?{}?=", STANDARD.encode(value))
})
}
+// An address that is one without angle brackets: a dot-atom on both sides of
+// the `@`. Anything else keeps its brackets, so `` stays one.
+fn plain_address(value: &str) -> bool {
+ let atom = |part: &str| {
+ !part.is_empty()
+ && part
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-/=?^_`{|}~".contains(&b))
+ };
+ value
+ .split_once('@')
+ .is_some_and(|(local, domain)| local.split('.').all(atom) && domain.split('.').all(atom))
+}
+fn addresses(list: &mailparse::MailAddrList) -> Vec {
+ list.iter()
+ .flat_map(|address| match address {
+ mailparse::MailAddr::Single(single) => vec![single.addr.clone()],
+ mailparse::MailAddr::Group(group) => {
+ group.addrs.iter().map(|s| s.addr.clone()).collect()
+ }
+ })
+ .collect()
+}
fn address_line(name: &str, value: &str) -> Result {
+ // ASCII goes out as typed, comments and unquoted commas included. A list
+ // ASCII cannot carry, or with a name holding `=?`, is written again with
+ // each name through `phrase`, and that rewrite refuses what it could change
+ // the reading of: a group, an address that is not ASCII, or a line that
+ // names other addresses than the list did.
let value = header(value)?;
- if value.is_ascii() {
- return Ok(format!("{name}: {value}"));
- }
- fn single(value: &mailparse::SingleInfo) -> Result {
- let address = header(&value.addr)?;
- let name = phrase(value.display_name.as_deref().unwrap_or(""))?;
- Ok(if name.is_empty() {
- address
- } else {
- format!("{name} <{address}>")
+ let parsed = mailparse::addrparse(&value);
+ let word = |name: &str| name.contains("=?");
+ let words = parsed.as_ref().is_ok_and(|list| {
+ list.iter().any(|address| match address {
+ mailparse::MailAddr::Single(single) => {
+ word(single.display_name.as_deref().unwrap_or(""))
+ }
+ mailparse::MailAddr::Group(group) => {
+ word(&group.group_name)
+ || group
+ .addrs
+ .iter()
+ .any(|s| word(s.display_name.as_deref().unwrap_or("")))
+ }
})
+ });
+ if value.is_ascii() && !words {
+ return Ok(format!("{name}: {value}"));
}
- let parsed = mailparse::addrparse(&value).map_err(|_| "invalid_message_header")?;
- let mut addresses = Vec::new();
+ let parsed = parsed.map_err(|_| "invalid_message_header")?;
+ let mut written = Vec::new();
for address in parsed.iter() {
- addresses.push(match address {
- mailparse::MailAddr::Single(value) => single(value)?,
- mailparse::MailAddr::Group(group) => format!(
- "{}: {};",
- phrase(&group.group_name)?,
- group
- .addrs
- .iter()
- .map(single)
- .collect::>>()?
- .join(", ")
- ),
+ let mailparse::MailAddr::Single(single) = address else {
+ return Err("invalid_message_header");
+ };
+ if !single.addr.is_ascii() {
+ return Err("invalid_message_header");
+ }
+ let phrase = phrase(single.display_name.as_deref().unwrap_or(""))?;
+ written.push(match (phrase.is_empty(), plain_address(&single.addr)) {
+ (true, true) => single.addr.clone(),
+ (true, false) => format!("<{}>", single.addr),
+ (false, _) => format!("{phrase} <{}>", single.addr),
});
}
- Ok(format!("{name}: {}", addresses.join(", ")))
+ let line = format!("{name}: {}", written.join(", "));
+ let check = format!("{line}\r\n\r\n");
+ let (headers, _) =
+ mailparse::parse_headers(check.as_bytes()).map_err(|_| "invalid_message_header")?;
+ let read = headers
+ .first()
+ .and_then(|header| mailparse::addrparse_header(header).ok())
+ .ok_or("invalid_message_header")?;
+ if addresses(&read) != addresses(&parsed) {
+ return Err("invalid_message_header");
+ }
+ Ok(line)
}
fn reference(value: &str) -> Result {
Ok(header(value)?
diff --git a/src/message/content.rs b/src/message/content.rs
index e36bf0f..04aa05b 100644
--- a/src/message/content.rs
+++ b/src/message/content.rs
@@ -187,10 +187,15 @@ pub fn address(value: &str) -> Value {
pub fn addresses(value: &str) -> Vec {
let mut quotes = false;
let mut angled = false;
+ let mut escaped = false;
let mut start = 0;
let mut result = Vec::new();
for (i, c) in value.char_indices() {
+ // Inside quotes a backslash escapes the next character, so `"O\"Neil, Pat"`
+ // stays one name.
match c {
+ _ if escaped => escaped = false,
+ '\\' if quotes => escaped = true,
'"' => quotes = !quotes,
'<' => angled = true,
'>' => angled = false,
diff --git a/src/message/parity_tests.rs b/src/message/parity_tests.rs
index b267790..1455cbe 100644
--- a/src/message/parity_tests.rs
+++ b/src/message/parity_tests.rs
@@ -174,3 +174,376 @@ fn outgoing_address_words_never_hide_address_structure() {
}
}
}
+
+fn composed_headers(fields: &Value) -> (Vec, Value) {
+ let raw = URL_SAFE_NO_PAD
+ .decode(compose::build(fields).unwrap()["raw"].as_str().unwrap())
+ .unwrap();
+ let summary = content::prepare(&json!({"payload":parse(&raw).unwrap()}), 0).unwrap();
+ (raw, summary["summary"].clone())
+}
+
+#[test]
+fn display_names_with_specials_stay_one_name_in_every_address_header() {
+ use mailparse::MailHeaderMap;
+ let mut names: Vec<(String, String)> = "()<>[]:;@\\,.\""
+ .chars()
+ .map(|c| format!("Ada {c} Lovelace"))
+ .chain(
+ [
+ "Doe, Jane",
+ "Say \"hi\" \\ bye",
+ "ends with \\",
+ "\"",
+ "()<>[]:;@\\,.\"",
+ "Team: eve@example.net;",
+ "eve@example.net",
+ "Müller, Jörg",
+ "工, Lee ",
+ // Readers decode `=?` even inside quotes, so it leaves encoded.
+ "=?UTF-8?B?PGV2ZUBleGFtcGxlLm5ldD4=?=",
+ ]
+ .map(String::from),
+ )
+ .map(|name| (name.clone(), name))
+ .collect();
+ for (typed, read) in [
+ ("Ada\rBcc: eve@example.net", "Ada Bcc: eve@example.net"),
+ ("Ada\nLovelace", "Ada Lovelace"),
+ ("Ada\r\nLovelace", "Ada Lovelace"),
+ ] {
+ names.push((typed.into(), read.into()));
+ }
+ for (name, read) in &names {
+ // The To text as the composer's field holds it.
+ let typed = |email: &str| format!("{} <{email}>", compose::quoted_phrase(name, false));
+ let fields = json!({"from":"me@example.org","fromName":name,
+ "to":format!("{}, ada@example.org", typed("to@example.org")),
+ "cc":typed("cc@example.org"),"bcc":typed("bcc@example.org"),
+ "replyTo":typed("reply@example.org"),"body":"body"});
+ let (raw, summary) = composed_headers(&fields);
+ let (headers, _) = mailparse::parse_headers(&raw).unwrap();
+ assert!(
+ headers.iter().all(|h| h.get_value_raw().is_ascii()),
+ "{name:?}"
+ );
+ assert!(headers.get_all_headers("Bcc").len() == 1, "{name:?}");
+ for (key, expected) in [
+ ("From", vec!["me@example.org"]),
+ ("To", vec!["to@example.org", "ada@example.org"]),
+ ("Cc", vec!["cc@example.org"]),
+ ("Bcc", vec!["bcc@example.org"]),
+ ("Reply-To", vec!["reply@example.org"]),
+ ] {
+ let list = mailparse::addrparse_header(headers.get_first_header(key).unwrap()).unwrap();
+ let singles: Vec<_> = list
+ .iter()
+ .map(|a| match a {
+ mailparse::MailAddr::Single(s) => s.clone(),
+ _ => panic!("{name:?} made a group in {key}"),
+ })
+ .collect();
+ assert_eq!(
+ singles.iter().map(|s| s.addr.as_str()).collect::>(),
+ expected,
+ "{name:?} {key}"
+ );
+ assert_eq!(
+ singles[0].display_name.as_deref(),
+ Some(read.as_str()),
+ "{name:?} {key}"
+ );
+ }
+ // And the reader this app draws a message with agrees.
+ assert_eq!(summary["from"]["name"], read.as_str(), "{name:?}");
+ assert_eq!(summary["to"].as_array().unwrap().len(), 2, "{name:?}");
+ assert_eq!(summary["to"][0]["name"], read.as_str(), "{name:?}");
+ assert_eq!(summary["cc"][0]["name"], read.as_str(), "{name:?}");
+ }
+ assert_eq!(
+ compose::build(&json!({"from":"me@example.org","fromName":"Ada\0Lovelace"})).unwrap_err(),
+ "invalid_message_header"
+ );
+}
+
+fn to_line(to: &str) -> Result {
+ use mailparse::MailHeaderMap;
+ let raw = URL_SAFE_NO_PAD
+ .decode(
+ compose::build(&json!({"to":to,"body":"b"}))?["raw"]
+ .as_str()
+ .unwrap(),
+ )
+ .unwrap();
+ let (headers, _) = mailparse::parse_headers(&raw).unwrap();
+ Ok(String::from_utf8(
+ headers
+ .get_first_header("To")
+ .unwrap()
+ .get_value_raw()
+ .to_vec(),
+ )
+ .unwrap())
+}
+
+#[test]
+fn typed_ascii_lists_go_out_as_typed_and_rewrites_refuse_what_they_could_change() {
+ // A group in the middle, a nameless address with specials, a comment, an
+ // unquoted comma, a half-typed draft: all as typed.
+ for typed in [
+ "ada@example.org, Team: eve@example.net; ",
+ ", ",
+ "Smith (Sales) , ann@example.org (Ann)",
+ "Doe, Jane ",
+ "bo",
+ ] {
+ assert_eq!(to_line(typed).unwrap(), typed);
+ }
+ // A list ASCII cannot carry, or with a name holding `=?`, is written again:
+ // a nameless address keeps its brackets unless it is a plain addr-spec.
+ assert_eq!(
+ to_line("Jörg , , ").unwrap(),
+ "=?UTF-8?B?SsO2cmc=?= , , c@example.org"
+ );
+ assert_eq!(
+ to_line("=?utf-8?q?Team=3A_eve=40example=2Enet=3B?= ").unwrap(),
+ format!(
+ "=?UTF-8?B?{}?= ",
+ base64::engine::general_purpose::STANDARD
+ .encode("=?utf-8?q?Team=3A_eve=40example=2Enet=3B?=")
+ )
+ );
+ // And refuses a group, an address that is not ASCII or printable, and what
+ // it cannot read.
+ for typed in [
+ "Jörg , Team: eve@example.net; ",
+ "Équipe: a@example.org, b@example.org;",
+ "Jörg , undisclosed-recipients:;",
+ "=?x?=: a@example.org;",
+ "x ",
+ "jörg@example.org",
+ "x ",
+ "x ",
+ "Müller, Jörg ",
+ // Rewritten, these would lose their first recipient: mailparse reads the
+ // address's `=?utf-8?q?` as an encoded word that runs into the next
+ // name, and the address turns into display text.
+ "=?utf-8?q?a?=b@example.org, Jörg ",
+ " =?utf-8?q?a?=b@example.org=?x?= ,=?utf-8?q?a?=Jörg ",
+ ] {
+ assert_eq!(
+ to_line(typed).unwrap_err(),
+ "invalid_message_header",
+ "{typed:?}"
+ );
+ }
+}
+
+#[test]
+fn composed_lists_name_the_recipients_that_were_typed() {
+ // Random lists of specials, names that need rewriting and addresses:
+ // whenever a message is built, its To names exactly the addresses mailparse
+ // reads in the typed text, rewritten or not.
+ let pieces = [
+ "\"",
+ "<",
+ ">",
+ "(",
+ ")",
+ "[",
+ "]",
+ ":",
+ ";",
+ "@",
+ "\\",
+ ",",
+ ".",
+ " ",
+ "a",
+ "é",
+ "Jörg ",
+ "=?x?= ",
+ "\"Müller, Jörg\" ",
+ "",
+ "b@example.org",
+ "",
+ "Team: ",
+ "(Sales) ",
+ ];
+ let mut seed: u64 = 0x9e3779b97f4a7c15;
+ for _ in 0..200000 {
+ seed ^= seed << 13;
+ seed ^= seed >> 7;
+ seed ^= seed << 17;
+ let mut x = seed;
+ let typed: String = (0..(seed % 10) as usize + 1)
+ .map(|_| {
+ x = x
+ .wrapping_mul(6364136223846793005)
+ .wrapping_add(1442695040888963407);
+ pieces[((x >> 33) as usize) % pieces.len()]
+ })
+ .collect();
+ let Ok(payload) = compose::build(&json!({"to":typed,"body":"b"})) else {
+ continue;
+ };
+ let raw = URL_SAFE_NO_PAD
+ .decode(payload["raw"].as_str().unwrap())
+ .unwrap();
+ let (headers, _) = mailparse::parse_headers(&raw).unwrap();
+ let before = format!("To: {typed}\r\n\r\n");
+ let (typed_headers, _) = mailparse::parse_headers(before.as_bytes()).unwrap();
+ if let Ok(expected) = envelope::addresses(&typed_headers, "To") {
+ assert_eq!(
+ envelope::addresses(&headers, "To"),
+ Ok(expected),
+ "{typed:?}"
+ );
+ }
+ }
+}
+
+#[test]
+fn javascript_rewrites_name_the_typed_recipients() {
+ // `Message.buildRawMessage` has no RFC 5322 parser of its own, so its
+ // rewrites are judged by mailparse here: a line it writes is printable
+ // ASCII, and a rewritten one names exactly the typed recipients.
+ let pieces = [
+ "\"",
+ "<",
+ ">",
+ "(",
+ ")",
+ "[",
+ "]",
+ ":",
+ ";",
+ "@",
+ "\\",
+ ",",
+ ".",
+ " ",
+ "a",
+ "é",
+ "Jörg ",
+ "=?x?= ",
+ "=?utf-8?q?a?=",
+ "\"Müller, Jörg\" ",
+ "",
+ "b@example.org",
+ "",
+ "Team: ",
+ "(Sales) ",
+ "\u{85}",
+ "\0",
+ ];
+ let mut seed: u64 = 0x1234_5678_9abc_def1;
+ let inputs: Vec = (0..100000)
+ .map(|_| {
+ seed ^= seed << 13;
+ seed ^= seed >> 7;
+ seed ^= seed << 17;
+ let mut x = seed;
+ (0..(seed % 10) as usize + 1)
+ .map(|_| {
+ x = x
+ .wrapping_mul(6364136223846793005)
+ .wrapping_add(1442695040888963407);
+ pieces[((x >> 33) as usize) % pieces.len()]
+ })
+ .collect()
+ })
+ .collect();
+ let script = r#"const M=require('./ui/tests/load.js').load('message/Message.js');const xs=JSON.parse(require('fs').readFileSync(0,'utf8'));process.stdout.write(JSON.stringify(xs.map(t=>{const r=M.buildRawMessage({to:t,body:'x'});return r===null?null:r.split('\r\n').find(l=>l.startsWith('To:'))})))"#;
+ let mut child = std::process::Command::new("node")
+ .args(["-e", script])
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .spawn()
+ .unwrap();
+ child
+ .stdin
+ .take()
+ .unwrap()
+ .write_all(json!(inputs).to_string().as_bytes())
+ .unwrap();
+ let output = child.wait_with_output().unwrap();
+ assert!(output.status.success());
+ let lines: Vec