From 457eb7f1b8196742c6dba8f0f0c33aa226c60021 Mon Sep 17 00:00:00 2001 From: Chris Gray <216301595+latentoperator@users.noreply.github.com> Date: Wed, 7 Oct 2026 12:14:43 -0500 Subject: [PATCH] Add saved-file toast, reader save entry points, and folder choice for Save as .eml - EmlSavedToast: a card naming the saved file and folder, with Open folder and dismiss; auto-hides after 8s, held while hovered. Status line note kept. - Reader: download button in the view toolbar (saves to Downloads) and Save as .eml / Save as .eml to folder... rows in the body's right-click menu. - Message menu: Save as .eml to folder... row beside Save as .eml. - mail.exportEml takes an optional absolute, normalized directory. A picked folder must already exist and pass the same ownership checks; it is never created. Downloads behaviour is unchanged. - attachment.sh folder: one folder through omarchy-file-select --directory (portal), falling back to zenity, out of process like the file picker. - Tests: Rust parse/write cases, contract case, shell picker cases, JS routing/stale-owner cases, QML toast/reader/menu cases. --- 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 | 12 +- ui/account/MailAccount.qml | 12 +- ui/account/MessageActions.js | 35 ++++- ui/components/EmlSavedToast.qml | 179 +++++++++++++++++++++++ ui/components/MessageMenu.qml | 19 ++- ui/components/MessageReader.qml | 34 +++++ ui/components/TextMenu.qml | 30 +++- ui/keys/Keymap.js | 2 +- ui/tests/qml/tst_eml_saved_toast.qml | 101 +++++++++++++ ui/tests/qml/tst_message_menu_export.qml | 33 ++++- ui/tests/qml/tst_reader_text_menu.qml | 63 +++++++- ui/tests/test_eml_export.js | 48 ++++++ 20 files changed, 778 insertions(+), 21 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 0c4da26..5c26895 100644 --- a/Makefile +++ b/Makefile @@ -51,6 +51,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, &'static str> { + let Some(value) = value else { + return Ok(None); + }; + let text = value.as_str().ok_or("invalid_params")?; + let path = std::path::Path::new(text); + // `components()` quietly drops an inner `.`, a doubled or trailing + // separator, so the path must also be exactly its own normal form. + let normal: PathBuf = path.components().collect(); + if text.is_empty() + || text.len() > 4096 + || text.chars().any(char::is_control) + || !path.is_absolute() + || normal.as_os_str() != path.as_os_str() + || path + .components() + .any(|part| matches!(part, std::path::Component::ParentDir)) + { + return Err("invalid_params"); + } + Ok(Some(path.to_path_buf())) +} + /// Export needs an explicit account. An empty or unknown id is refused and /// never falls back to the registry's active account, unlike `resolve_account`. fn resolve_export_account(wanted: &str) -> Result { diff --git a/tests/test_attachment.sh b/tests/test_attachment.sh index 4b89566..ce0862b 100755 --- a/tests/test_attachment.sh +++ b/tests/test_attachment.sh @@ -219,6 +219,40 @@ answer=$(sh "$script" pick) check "a cancelled picker is cancelled, not an error" "$(json_field error "$answer")" "cancelled" unset OMAMAIL_PICK_OUT OMAMAIL_PICK_EXIT +# A folder for Save as .eml: the chooser is asked for a directory, and only +# its first absolute answer is returned. +cat > "$work/bin/omarchy-file-select" <<'STUB' +#!/bin/sh +printf '%s\n' "$*" > "$OMAMAIL_PICK_ARGS" +printf '%s\n' "$OMAMAIL_PICK_OUT" +exit "${OMAMAIL_PICK_EXIT:-0}" +STUB +chmod +x "$work/bin/omarchy-file-select" +OMAMAIL_PICK_ARGS=$work/pick-args +OMAMAIL_PICK_OUT=$(printf '%s\n' "/home/ada/Mail archive" /home/ada/other) +export OMAMAIL_PICK_ARGS OMAMAIL_PICK_OUT +answer=$(sh "$script" folder) +check "folder says ok" "$(json_field ok "$answer")" "True" +picked=$(printf '%s' "$answer" | python3 -c 'import json,sys; print("\n".join(json.load(sys.stdin)["paths"]))') +check "folder returns only the first folder" "$picked" "/home/ada/Mail archive" +case "$(cat "$OMAMAIL_PICK_ARGS")" in + *--directory*) ok "folder asks the chooser for a directory" ;; + *) bad "folder asks the chooser for a directory" ;; +esac +OMAMAIL_PICK_OUT=/home/ada/Mail/ +answer=$(sh "$script" folder) +picked=$(printf '%s' "$answer" | python3 -c 'import json,sys; print(json.load(sys.stdin)["paths"][0])') +check "a trailing slash is dropped" "$picked" "/home/ada/Mail" +OMAMAIL_PICK_OUT=relative/folder +answer=$(sh "$script" folder) +check "a relative folder is refused as cancelled" "$(json_field error "$answer")" "cancelled" +OMAMAIL_PICK_EXIT=1 +OMAMAIL_PICK_OUT= +export OMAMAIL_PICK_EXIT OMAMAIL_PICK_OUT +answer=$(sh "$script" folder) +check "a cancelled folder chooser is cancelled" "$(json_field error "$answer")" "cancelled" +unset OMAMAIL_PICK_OUT OMAMAIL_PICK_EXIT OMAMAIL_PICK_ARGS + # forget only deletes files this script wrote into the compose dir. printf 'keep\n' > "$work/outside.txt" sh "$script" forget "$work/compose" "$work/outside.txt" >/dev/null 2>&1 || true diff --git a/ui/App.qml b/ui/App.qml index e3d7a34..3a01abd 100644 --- a/ui/App.qml +++ b/ui/App.qml @@ -2429,6 +2429,8 @@ Item { panelFontFamily: root.fontFamily } + EmlSavedToast { app: root } + // --------------------------------------------------------- status bar Item { diff --git a/ui/Service.qml b/ui/Service.qml index 108f47d..82f5151 100644 --- a/ui/Service.qml +++ b/ui/Service.qml @@ -504,12 +504,14 @@ Item { return true } - function chooseFiles(callback) { + function chooseFiles(callback) { return choose("pick", callback) } + function chooseFolder(callback) { return choose("folder", callback) } + function choose(mode, callback) { if (platform && typeof platform.chooseFiles === "function") - return platform.chooseFiles(callback) + return mode === "pick" && platform.chooseFiles(callback) var request = hostProcessComponent.createObject(root, { operation: "result", callback: callback, - command: [root.pluginDir + "/scripts/attachment.sh", "pick"] + command: [root.pluginDir + "/scripts/attachment.sh", mode] }) if (!request) { if (typeof callback === "function") callback(({ok:false,error:"No file picker is available"})) @@ -2230,6 +2232,9 @@ Item { function canExportEmlFor(id) { return MessageActions.canExportEmlFor(root, id) } function accountForMessage(id) { return MessageActions.accountForMessage(root, id) } function exportEmlFor(accountId, id) { return MessageActions.exportEmlFor(root, accountId, id) } + function canChooseEmlFolder(id) { return MessageActions.canChooseEmlFolder(root, id) } + function exportEmlToFolder(accountId, id) { return MessageActions.exportEmlToFolder(root, accountId, id) } + signal emlSaved(var result) function exportEml(id) { return MessageActions.exportEml(root, id) } function exportFromView(view, cursorId) { return MessageActions.exportFromView(root, view, cursorId) } function markAllRead() { return MessageActions.markAllRead(root) } @@ -2663,6 +2668,7 @@ Item { onReplySent: function(sendId) { root.replySent(String(sendId || "")) } onReplyFailed: function(sendId) { root.forwardReplyFailure(index, sendId) } onMonitoredMigrated: function(ids) { root.setMonitoredIds(index, ids) } + onEmlSaved: function(result) { root.emlSaved(result) } // What a merged list is made of, and everything a merged list says // about itself. `recount` is not enough and is deliberately not used: diff --git a/ui/account/MailAccount.qml b/ui/account/MailAccount.qml index e92e2b8..54e24ec 100644 --- a/ui/account/MailAccount.qml +++ b/ui/account/MailAccount.qml @@ -1998,7 +1998,8 @@ Item { return runNativeAction([], "markRead", false, false, true) } - // Save the message's original bytes as .eml in Downloads. One request per + // Save the message's original bytes as .eml in Downloads, or in a folder + // the user picked. One request per // mailbox at a time, and the notice names the file the backend actually // wrote. The id is this mailbox's own, resolved by the service. property bool exportingEml: false @@ -2011,8 +2012,11 @@ Item { return "" } - function exportEml(id) { + signal emlSaved(var result) + + function exportEml(id, directory) { var target = String(id || "") + var folder = String(directory || "") if (!ready || !backend || target === "") return false if (!canExportEml) { fail("This mailbox cannot save messages as .eml") @@ -2024,6 +2028,7 @@ Item { } clearNotice() var parameters = {account: accountId, id: target, suggestedName: subjectForEml(target)} + if (folder !== "") parameters.directory = folder exportingEml = true exportingEmlId = target // The busy state is visible from the moment the work starts, not only when @@ -2033,10 +2038,11 @@ Item { root.exportingEml = false root.exportingEmlId = "" if (error) { - root.fail(MessageActions.exportErrorText(error)) + root.fail(MessageActions.exportErrorText(error, folder)) return } root.note(MessageActions.exportSavedNotice(result)) + root.emlSaved(result) }) return true } diff --git a/ui/account/MessageActions.js b/ui/account/MessageActions.js index 0b402ad..630ad44 100644 --- a/ui/account/MessageActions.js +++ b/ui/account/MessageActions.js @@ -35,7 +35,7 @@ function accountForMessage(service, id) { // message, captured by a caller that must keep them across an account // switch. A non-unified view refuses when the captured mailbox is no longer // the one on screen: 42:INBOX is a different message in the next account. -function exportEmlFor(service, accountId, id) { +function exportEmlFor(service, accountId, id, directory) { var target = String(id || "") if (target === "") return false if (!service.backendCanExportEml) { @@ -59,7 +59,21 @@ function exportEmlFor(service, accountId, id) { owner.fail("This mailbox cannot save messages as .eml") return false } - return owner.exportEml(target) + return owner.exportEml(target, directory) +} +// The same export into a folder the user picks first. Only the desktop plugin +// has the out-of-process chooser. The boundary above runs again once the +// chooser answers, so an account switch while it was open still refuses. +function canChooseEmlFolder(service, id) { + return !!service && !service.standalone && canExportEmlFor(service, id) +} +function exportEmlToFolder(service, accountId, id) { + if (String(id || "") === "" || !service || service.standalone || !service.backendCanExportEml) return false + return service.chooseFolder(function(answer) { + var folder = answer && answer.ok && answer.paths ? String(answer.paths[0] || "") : "" + if (folder !== "") exportEmlFor(service, accountId, id, folder) + else if (answer && answer.error !== "cancelled") service.fail(String(answer.error || "No folder picker is available")) + }) } function exportEml(service, id) { if (!canExportEmlFor(service, id)) { @@ -104,6 +118,19 @@ function exportSavedNotice(result) { return at > 0 ? "Saved " + name + " to " + path.substring(0, at) : "Saved " + (name || "the message as .eml") } +// What the saved-file toast shows: the name, and the folder it went to with +// the home directory shortened, so the folder is the part that stays visible. +function exportSavedFile(result, home) { + var path = String(result && result.path || "") + var at = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + var folder = at > 0 ? path.substring(0, at) : "" + var root = String(home || "") + var shown = root !== "" && (folder === root || folder.indexOf(root + "/") === 0) + ? "~" + folder.substring(root.length) : folder + return { name: String(result && result.filename || "") || path.substring(at + 1), + folder: folder, shownFolder: shown } +} + // The backend refuses with a code; the status line says what happened. var EXPORT_ERRORS = { mail_export_too_large: "This message is larger than 25 MB, so it was not saved", @@ -116,8 +143,10 @@ var EXPORT_ERRORS = { request_cancelled: "Saving the message as .eml was cancelled", backend_needs_update: "Saving .eml needs a newer Omamail backend" } -function exportErrorText(error) { +function exportErrorText(error, directory) { var code = String(error && error.message || error || "") + if (code === "mail_export_write_failed" && String(directory || "") !== "") + return "Could not write the .eml file to " + directory return EXPORT_ERRORS.hasOwnProperty(code) ? EXPORT_ERRORS[code] : "Could not save the message as .eml" } diff --git a/ui/components/EmlSavedToast.qml b/ui/components/EmlSavedToast.qml new file mode 100644 index 0000000..4e93c7c --- /dev/null +++ b/ui/components/EmlSavedToast.qml @@ -0,0 +1,179 @@ +import QtQuick +import Quickshell +import qs.Commons +import qs.Ui +import "../account/MessageActions.js" as MessageActions + +// Says that a Save as .eml finished, and where the file went. The status line +// says it too, but a caption at the window's edge was easy to miss for a file +// written somewhere on disk; this card names the file and the folder, and +// offers to open that folder. It listens to the service itself, so the window +// only places it. +Rectangle { + id: root + + // The window, for its service and theme colours. One property rather than + // seven, because App.qml sits against the repository's file-size ceiling. + required property var app + readonly property var service: app ? app.service : null + readonly property color textColor: app ? app.foreground : Color.foreground + readonly property color dimColor: app ? app.dim : textColor + readonly property color accentColor: app ? app.accent : Color.accent + readonly property color popupBackgroundColor: app ? app.popupBackground : Qt.rgba(0, 0, 0, 1) + readonly property color popupBorderColor: app ? app.popupBorder : textColor + readonly property string panelFontFamily: app ? app.fontFamily : Style.font.family + // The widest the card may grow; the name and folder elide inside it. + property real maximumWidth: Style.space(440) + // Long enough to read a path and reach the button, short enough not to + // linger over the next message. + property int timeout: 8000 + + // The file the backend wrote, which can carry a " (2)" the subject did not. + property string filename: "" + // The folder as shown, home shortened to ~, and the real one to open. + property string folderLabel: "" + property string folder: "" + readonly property bool shown: filename !== "" + + function show(result) { + var saved = MessageActions.exportSavedFile(result, Quickshell.env("HOME")) + filename = saved.name + folder = saved.folder + folderLabel = saved.shownFolder + if (shown) hideTimer.restart() + } + function dismiss() { + hideTimer.stop() + filename = "" + folder = "" + folderLabel = "" + } + function openFolder() { + var target = folder + dismiss() + if (target !== "" && root.service && typeof root.service.openExternal === "function") + root.service.openExternal(target) + } + + Connections { + target: root.service + ignoreUnknownSignals: true + function onEmlSaved(result) { root.show(result) } + } + + Timer { + id: hideTimer + interval: root.timeout + onTriggered: root.dismiss() + } + + readonly property real chromeWidth: mark.width + openButton.width + closeButton.width + + content.spacing * 3 + Style.space(18) + + // Placed by itself, over the status line's right end where the draft and + // send toasts sit, because the window file has no room left to spare. + anchors.right: parent ? parent.right : undefined + anchors.rightMargin: Style.space(16) + anchors.bottom: parent ? parent.bottom : undefined + anchors.bottomMargin: Style.space(28) + Style.space(12) + z: 80 + visible: shown + implicitWidth: Math.min(maximumWidth, + Math.max(nameText.implicitWidth, folderText.implicitWidth) + chromeWidth) + implicitHeight: Math.max(content.implicitHeight + Style.space(14), Style.space(48)) + width: implicitWidth + height: implicitHeight + radius: Style.cornerRadius + color: Qt.rgba(popupBackgroundColor.r, popupBackgroundColor.g, + popupBackgroundColor.b, 1) + border.width: Style.normalBorderWidth + border.color: popupBorderColor + + Accessible.role: Accessible.AlertMessage + Accessible.name: "Saved " + root.filename + " in " + root.folderLabel + + // Hovering holds the card, so it does not leave from under the pointer. + HoverHandler { + onHoveredChanged: if (hovered) hideTimer.stop(); else if (root.shown) hideTimer.restart() + } + + Row { + id: content + anchors.left: parent.left + anchors.leftMargin: Style.space(12) + anchors.right: parent.right + anchors.rightMargin: Style.space(6) + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(10) + + ActionIcon { + id: mark + anchors.verticalCenter: parent.verticalCenter + name: "check" + color: root.accentColor + iconSize: Style.font.icon + width: Style.font.icon + height: Style.font.icon + } + + Column { + anchors.verticalCenter: parent.verticalCenter + width: Math.max(0, content.width - mark.width - openButton.width + - closeButton.width - content.spacing * 3) + spacing: Style.space(2) + + Text { + id: nameText + objectName: "eml-saved-name" + width: parent.width + text: "Saved " + root.filename + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.bodySmall + elide: Text.ElideMiddle + } + Text { + id: folderText + objectName: "eml-saved-folder" + width: parent.width + visible: root.folderLabel !== "" + text: "in " + root.folderLabel + textFormat: Text.PlainText + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + // The end of a path is the part that tells folders apart. + elide: Text.ElideLeft + } + } + + Button { + id: openButton + objectName: "eml-saved-open-folder" + anchors.verticalCenter: parent.verticalCenter + visible: root.folder !== "" + text: "Open folder..." + foreground: root.accentColor + accent: root.accentColor + bordered: true + fontFamily: root.panelFontFamily + fontSize: Style.font.caption + onClicked: root.openFolder() + } + + IconButton { + id: closeButton + objectName: "eml-saved-close" + anchors.verticalCenter: parent.verticalCenter + iconName: "close" + iconSize: Style.font.iconSmall + size: Style.space(22) + tooltipText: "Dismiss" + foreground: root.dimColor + hoverColor: root.textColor + fontFamily: root.panelFontFamily + onClicked: root.dismiss() + } + } +} diff --git a/ui/components/MessageMenu.qml b/ui/components/MessageMenu.qml index 681aa3c..760ab66 100644 --- a/ui/components/MessageMenu.qml +++ b/ui/components/MessageMenu.qml @@ -36,7 +36,7 @@ Item { property string nativeId: "" readonly property var menuRows: [continueRow, replyRow, replyAllRow, forwardRow, archiveRow, unarchiveRow, moveRow, - trashRow, spamRow, readRow, starRow, exportRow, browserRow, aiRow] + trashRow, spamRow, readRow, starRow, exportRow, exportFolderRow, 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 @@ -156,6 +156,15 @@ Item { root.service.exportEmlFor(account, id) } + // The same, into a folder the user picks before anything is fetched. + function exportMessageToFolder() { + var account = root.ownerAccountId + var id = root.nativeId + menu.close() + if (root.service && typeof root.service.exportEmlToFolder === "function") + root.service.exportEmlToFolder(account, id) + } + QQC.Popup { id: menu width: Style.space(200) @@ -279,6 +288,14 @@ Item { // browser does. onActivated: root.exportMessage() } + MenuRow { + id: exportFolderRow + objectName: "message-menu-export-eml-folder" + visible: exportRow.visible && typeof root.service.canChooseEmlFolder === "function" + && root.service.canChooseEmlFolder(root.messageId) + text: "Save as .eml to folder..." + onActivated: root.exportMessageToFolder() + } MenuSeparatorLine { width: menu.width - menu.leftPadding - menu.rightPadding diff --git a/ui/components/MessageReader.qml b/ui/components/MessageReader.qml index e2533eb..1a6856e 100644 --- a/ui/components/MessageReader.qml +++ b/ui/components/MessageReader.qml @@ -117,6 +117,19 @@ Item { }) } + // Save as .eml from the reader: the message on screen, to Downloads or to a + // folder picked first. The owner is captured now, before any chooser opens. + readonly property bool canSaveEml: !!service && !!summary && !isDraft + && typeof service.canExportEmlFor === "function" && service.canExportEmlFor(selectedId) + readonly property bool canSaveEmlToFolder: canSaveEml + && typeof service.canChooseEmlFolder === "function" && service.canChooseEmlFolder(selectedId) + function saveEml(chooseFolder) { + if (!canSaveEml) return false + var id = selectedId + if (!chooseFolder) return service.exportEml(id) + return service.exportEmlToFolder(service.accountForMessage(id), service.sourceIdFor(id)) + } + function scrollBy(steps) { var maximum = Math.max(0, bodyFlick.contentHeight - bodyFlick.height) bodyFlick.contentY = Math.max(0, Math.min(maximum, @@ -1001,6 +1014,7 @@ Item { y: actionsRow.stacked ? messageActions.height + Style.space(4) : 0 implicitWidth: modeTrack.width + (openWebButton.visible ? Style.space(6) + openWebButton.width : 0) + + (saveEmlButton.visible ? Style.space(6) + saveEmlButton.width : 0) implicitHeight: Math.max(modeTrack.height, openWebButton.visible ? openWebButton.height : 0) width: implicitWidth @@ -1061,6 +1075,23 @@ Item { fontFamily: root.panelFontFamily onClicked: if (root.service && root.summary) root.service.openInBrowser(root.selectedId) } + // Takes the message out of the window as a file, like the browser + // button takes it out to the web. A click saves to Downloads; the + // body's right-click menu and the list's menu also offer a folder. + IconButton { + id: saveEmlButton + objectName: "reader-save-eml-button" + visible: root.canSaveEml + x: (openWebButton.visible ? openWebButton.x + openWebButton.width : modeTrack.width) + + Style.space(6) + y: modeTrack.y + height: modeTrack.height + iconName: "download" + tooltipText: "Save as .eml to Downloads · ctrl+shift+s" + foreground: root.dimColor; hoverColor: root.textColor + fontFamily: root.panelFontFamily + onClicked: root.saveEml(false) + } } } } @@ -1107,6 +1138,9 @@ Item { if (root.service && typeof root.service.copyText === "function") root.service.copyText(text) } onOpenLinkRequested: function(url) { root.openLink(url) } + canSaveEml: root.canSaveEml + canSaveEmlToFolder: root.canSaveEmlToFolder + onSaveEmlRequested: function(chooseFolder) { root.saveEml(chooseFolder) } } ImagePopover { diff --git a/ui/components/TextMenu.qml b/ui/components/TextMenu.qml index 37cd828..c0af709 100644 --- a/ui/components/TextMenu.qml +++ b/ui/components/TextMenu.qml @@ -43,9 +43,14 @@ Item { readonly property bool spellingActionsVisible: spellingMisspelled && spellingWord !== "" readonly property bool opened: menu.opened readonly property bool hasSelection: !!target && String(target.selectedText || "") !== "" + // The reader's body offers the message itself as a file too. Off in the + // composer, which has no saved message yet. + property bool canSaveEml: false + property bool canSaveEmlToFolder: false readonly property var menuRows: [ suggestion0, suggestion1, suggestion2, suggestion3, suggestion4, - ignoreRow, addRow, cutRow, copyRow, pasteRow, selectAllRow, openLinkRow, copyLinkRow + ignoreRow, addRow, cutRow, copyRow, pasteRow, selectAllRow, openLinkRow, copyLinkRow, + saveEmlRow, saveEmlFolderRow ] readonly property alias cutRow: cutRow @@ -56,12 +61,15 @@ Item { readonly property alias copyLinkRow: copyLinkRow readonly property alias ignoreWordRow: ignoreRow readonly property alias addToDictionaryRow: addRow + readonly property alias saveEmlRow: saveEmlRow + readonly property alias saveEmlFolderRow: saveEmlFolderRow signal copyRequested(string text) // Paste is the owner's: a compose form tries the clipboard for an image // before it pastes text, and only it knows how. signal pasteRequested(var target) signal openLinkRequested(string url) + signal saveEmlRequested(bool chooseFolder) signal spellingCorrect(string replacement) signal spellingIgnore(string word) signal spellingAddToDictionary(string word) @@ -255,6 +263,26 @@ Item { text: "Copy URL" onActivated: { var url = root.link; menu.close(); root.copyRequested(url) } } + + MenuSeparatorLine { + visible: root.canSaveEml + width: menu.width - menu.leftPadding - menu.rightPadding + lineColor: root.textColor + } + MenuRow { + id: saveEmlRow + objectName: "text-menu-save-eml" + visible: root.canSaveEml + text: "Save as .eml" + onActivated: { menu.close(); root.saveEmlRequested(false) } + } + MenuRow { + id: saveEmlFolderRow + objectName: "text-menu-save-eml-folder" + visible: root.canSaveEml && root.canSaveEmlToFolder + text: "Save as .eml to folder..." + onActivated: { menu.close(); root.saveEmlRequested(true) } + } } } diff --git a/ui/keys/Keymap.js b/ui/keys/Keymap.js index 872c427..344cdde 100644 --- a/ui/keys/Keymap.js +++ b/ui/keys/Keymap.js @@ -77,7 +77,7 @@ var BINDINGS = [ hint: { list: "trash", reader: "trash" } }, { id: "star", keys: ["s"], contexts: MAIL, group: "Acting", label: "Star or unstar" }, - // Save the original message bytes to Downloads. + // Save the original message bytes to Downloads. The menus also offer a folder. { id: "exportEml", keys: ["Ctrl+Shift+S"], contexts: MAIL, group: "Acting", label: "Save as .eml" }, // `v` because that is the key Gmail moves a message with, and issue #58 asks diff --git a/ui/tests/qml/tst_eml_saved_toast.qml b/ui/tests/qml/tst_eml_saved_toast.qml new file mode 100644 index 0000000..773913b --- /dev/null +++ b/ui/tests/qml/tst_eml_saved_toast.qml @@ -0,0 +1,101 @@ +import QtQuick 2.15 +import QtTest 1.3 +import "../../components" as Omamail + +// The saved-file card: it appears when the service says a .eml was written, +// names the file and the folder, opens that folder on request, and goes away +// on its own or when dismissed. +Item { + id: window + width: 900 + height: 600 + + QtObject { + id: fakeService + property var opened: [] + signal emlSaved(var result) + function openExternal(target) { opened = opened.concat([String(target)]); return true } + } + + // Stands in for App.qml: the card reads the service and the theme off it. + QtObject { + id: fakeApp + property var service: fakeService + property color foreground: Qt.rgba(1, 1, 1, 1) + property color dim: Qt.rgba(0.6, 0.6, 0.6, 1) + property color accent: Qt.rgba(1, 0.5, 0, 1) + property color popupBackground: Qt.rgba(0.1, 0.1, 0.1, 1) + property color popupBorder: Qt.rgba(0.4, 0.4, 0.4, 1) + property string fontFamily: "monospace" + } + + Omamail.EmlSavedToast { + id: toast + app: fakeApp + timeout: 300 + } + + TestCase { + name: "EmlSavedToast" + 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 saved(path, filename) { + fakeService.emlSaved({ ok: true, path: path, filename: filename, bytes: 10 }) + wait(10) + } + + function init() { + toast.dismiss() + fakeService.opened = [] + } + + function test_nothing_shows_until_a_file_is_saved() { + compare(toast.visible, false) + } + + function test_a_save_names_the_file_and_the_folder() { + saved("/srv/mail/Project update (2).eml", "Project update (2).eml") + compare(toast.visible, true) + compare(named(toast, "eml-saved-name").text, "Saved Project update (2).eml") + compare(named(toast, "eml-saved-folder").text, "in /srv/mail") + verify(toast.x + toast.width <= window.width, "the card stays inside the window") + verify(toast.y + toast.height <= window.height) + } + + function test_open_folder_opens_the_folder_and_closes_the_card() { + saved("/srv/mail/Note.eml", "Note.eml") + var button = named(toast, "eml-saved-open-folder") + verify(button && button.visible) + button.clicked() + compare(fakeService.opened, ["/srv/mail"], "the folder, never the file itself") + compare(toast.visible, false) + } + + function test_dismiss_and_timeout_both_hide_it() { + saved("/srv/mail/Note.eml", "Note.eml") + named(toast, "eml-saved-close").clicked() + compare(toast.visible, false) + saved("/srv/mail/Note.eml", "Note.eml") + compare(toast.visible, true) + tryCompare(toast, "visible", false, 2000, "it leaves on its own") + } + + function test_a_second_save_replaces_the_first() { + saved("/srv/mail/One.eml", "One.eml") + saved("/srv/other/Two.eml", "Two.eml") + compare(named(toast, "eml-saved-name").text, "Saved Two.eml") + compare(toast.folder, "/srv/other") + } + } +} diff --git a/ui/tests/qml/tst_message_menu_export.qml b/ui/tests/qml/tst_message_menu_export.qml index d58e805..652d06e 100644 --- a/ui/tests/qml/tst_message_menu_export.qml +++ b/ui/tests/qml/tst_message_menu_export.qml @@ -35,6 +35,13 @@ Item { var at = String(id).indexOf("/") return at > 0 ? String(id).substring(at + 1) : String(id) } + property bool folderable: true + property var chosen: [] + function canChooseEmlFolder(id) { return exportable && folderable } + function exportEmlToFolder(accountId, id) { + chosen = chosen.concat([{ account: String(accountId), id: String(id) }]) + return true + } function exportEmlFor(accountId, id) { exported = exported.concat([{ account: String(accountId), id: String(id) }]) return true @@ -59,6 +66,7 @@ Item { // exportRow sits after star, before the browser and AI rows. function exportRow() { return menu.menuRows[11] } + function exportFolderRow() { return menu.menuRows[12] } function summary() { return { id: "42:INBOX", subject: "Project update", unread: false, @@ -93,7 +101,11 @@ Item { wait(20) } - function cleanup() { menu.close() } + function cleanup() { + menu.close() + fakeService.chosen = [] + fakeService.folderable = true + } function test_the_row_appears_only_when_the_service_says_it_can() { fakeService.exportable = true @@ -115,6 +127,25 @@ Item { compare(menu.opened, false, "the menu closes on choosing") } + function test_the_folder_row_routes_the_owner_and_native_id() { + fakeService.exportable = true + showMember(fakeService.ada + "/17:INBOX") + compare(exportFolderRow().visible, true) + compare(String(exportFolderRow().text), "Save as .eml to folder...") + exportFolderRow().activated() + compare(fakeService.chosen, [{ account: fakeService.ada, id: "17:INBOX" }]) + compare(fakeService.exported, [], "the Downloads path is not taken as well") + compare(menu.opened, false) + } + + function test_the_folder_row_needs_a_chooser() { + fakeService.exportable = true + fakeService.folderable = false + show() + compare(exportRow().visible, true) + compare(exportFolderRow().visible, false) + } + // A stop on the conversation rail is one message, and its id is the // composed member id. The menu keeps the account and the member's native // id, so the export reaches that member rather than the list's root row. diff --git a/ui/tests/qml/tst_reader_text_menu.qml b/ui/tests/qml/tst_reader_text_menu.qml index 6cfdee0..1655dc0 100644 --- a/ui/tests/qml/tst_reader_text_menu.qml +++ b/ui/tests/qml/tst_reader_text_menu.qml @@ -4,8 +4,8 @@ import qs.Commons import "../../components" as Omamail import "../../message/Html.js" as Html -// A right-click on the message body: Copy for what is selected, and Open and -// Copy URL when the click lands on a link. +// A right-click on the message body: Copy for what is selected, Open and Copy +// URL when the click lands on a link, and the message itself as a .eml file. Item { width: 900 height: 600 @@ -55,6 +55,19 @@ Item { function getMessage() {} function showRemoteImages() {} + // Save as .eml from the reader: the toolbar button and the body menu. + property bool exportable: true + property bool folderable: true + property var exported: [] + function canExportEmlFor(id) { return exportable } + function canChooseEmlFolder(id) { return exportable && folderable } + function exportEml(id) { exported = exported.concat([{ id: String(id), folder: false }]); return true } + function accountForMessage(id) { return "imap:reader@example.com" } + function sourceIdFor(id) { return "native-" + id } + function exportEmlToFolder(account, id) { + exported = exported.concat([{ account: String(account), id: String(id), folder: true }]) + return true + } function copyText(text) { copied = copied.concat([String(text)]); return true } function openExternal(url) { opened = opened.concat([String(url)]); return true } } @@ -130,6 +143,9 @@ Item { body().deselect() mailService.copied = [] mailService.opened = [] + mailService.exported = [] + mailService.exportable = true + mailService.folderable = true } function cleanup() { menu().close() } @@ -168,6 +184,49 @@ Item { compare(mailService.copied, ["https://example.com/board"]) } + function test_the_body_menu_saves_the_message_as_eml() { + var edit = body() + var point = pointOf(edit, "Person 1") + mouseClick(edit, point.x, point.y, Qt.RightButton) + wait(20) + compare(menu().saveEmlRow.visible, true) + compare(menu().saveEmlFolderRow.visible, true) + menu().saveEmlRow.activated() + compare(mailService.exported, [{ id: "message-9", folder: false }]) + compare(menu().opened, false) + + mouseClick(edit, point.x, point.y, Qt.RightButton) + wait(20) + menu().saveEmlFolderRow.activated() + compare(mailService.exported[1], { account: "imap:reader@example.com", + id: "native-message-9", folder: true }, "the owner and native id, captured now") + } + + function test_the_rows_follow_what_the_service_can_do() { + mailService.folderable = false + var edit = body() + var point = pointOf(edit, "Person 1") + mouseClick(edit, point.x, point.y, Qt.RightButton) + wait(20) + compare(menu().saveEmlRow.visible, true) + compare(menu().saveEmlFolderRow.visible, false, "no chooser, no folder row") + menu().close() + mailService.exportable = false + mouseClick(edit, point.x, point.y, Qt.RightButton) + wait(20) + compare(menu().saveEmlRow.visible, false) + } + + function test_the_toolbar_button_saves_to_downloads() { + var button = named(reader, "reader-save-eml-button") + verify(button, "the reader toolbar has a save button") + compare(button.visible, true) + button.clicked() + compare(mailService.exported, [{ id: "message-9", folder: false }]) + mailService.exportable = false + compare(button.visible, false, "hidden where export is not possible") + } + function test_open_link_opens_it_outside() { var edit = body() var point = pointOf(edit, "Open the board") diff --git a/ui/tests/test_eml_export.js b/ui/tests/test_eml_export.js index 5dbaa33..e72e1dc 100644 --- a/ui/tests/test_eml_export.js +++ b/ui/tests/test_eml_export.js @@ -93,4 +93,52 @@ for (const code of ["mail_export_write_failed", "mail_export_message_missing", " assert.strictEqual(actions.exportErrorText({ message: "mail_tls_failed" }), "Could not save the message as .eml") assert.strictEqual(actions.exportErrorText({ message: "constructor" }), "Could not save the message as .eml") assert.strictEqual(actions.exportErrorText(null), "Could not save the message as .eml") +// A picked folder rides the same dispatch boundary, captured owner and all. +const folderCalls = [] +const desk = account("imap:desk@example.org", "imap") +desk.exportEml = (nativeId, directory) => { folderCalls.push({ id: nativeId, directory }); return true } +let chooserAnswer = null +const plugin = { current: desk, unified: false, standalone: false, selectedId: "", + backendCanExportEml: true, failures: [], fail: text => plugin.failures.push(text), + findAccount: id => id === desk.accountId ? desk : null, + hostForId: () => plugin.current, sourceIdFor: id => id, + chooseFolder: done => { done(chooserAnswer); return true } } +plugin.canExportEmlFor = id => actions.canExportEmlFor(plugin, id) +assert.strictEqual(actions.canChooseEmlFolder(plugin, "9:INBOX"), true) +chooserAnswer = { ok: true, paths: ["/home/ada/Mail archive"] } +assert.strictEqual(actions.exportEmlToFolder(plugin, desk.accountId, "9:INBOX"), true) +assert.deepStrictEqual(folderCalls.pop(), { id: "9:INBOX", directory: "/home/ada/Mail archive" }) +chooserAnswer = { ok: false, error: "cancelled" } +actions.exportEmlToFolder(plugin, desk.accountId, "9:INBOX") +assert.strictEqual(folderCalls.length, 0, "a cancelled chooser saves nothing") +assert.deepStrictEqual(plugin.failures, [], "and says nothing") +chooserAnswer = { ok: false, error: "No folder picker is available" } +actions.exportEmlToFolder(plugin, desk.accountId, "9:INBOX") +assert.deepStrictEqual(plugin.failures, ["No folder picker is available"]) +// An account switch while the chooser was open refuses, as a stale menu does. +chooserAnswer = { ok: true, paths: ["/home/ada/Mail archive"] } +plugin.chooseFolder = done => { plugin.current = bob; done(chooserAnswer); return true } +plugin.findAccount = id => [desk, bob].find(a => a.accountId === id) || null +actions.exportEmlToFolder(plugin, desk.accountId, "9:INBOX") +assert.strictEqual(folderCalls.length, 0, "the folder answer cannot reach another mailbox") +plugin.current = desk +plugin.standalone = true +assert.strictEqual(actions.canChooseEmlFolder(plugin, "9:INBOX"), false, + "the standalone app has no out-of-process chooser") +assert.strictEqual(actions.exportEmlToFolder(plugin, desk.accountId, "9:INBOX"), false) +plugin.standalone = false +plugin.backendCanExportEml = false +assert.strictEqual(actions.exportEmlToFolder(plugin, desk.accountId, "9:INBOX"), false, + "no chooser opens for a backend that cannot export") + +assert.deepStrictEqual(JSON.parse(JSON.stringify(actions.exportSavedFile({ filename: "Project update (2).eml", + path: "/home/ada/Downloads/Project update (2).eml" }, "/home/ada"))), + { name: "Project update (2).eml", folder: "/home/ada/Downloads", shownFolder: "~/Downloads" }) +assert.strictEqual(actions.exportSavedFile({ path: "/home/adam/x.eml" }, "/home/ada").shownFolder, + "/home/adam", "a sibling of home is not shortened") +assert.strictEqual(actions.exportSavedFile({ path: "/srv/mail/x.eml" }, "").shownFolder, "/srv/mail") +assert.strictEqual(actions.exportErrorText({ message: "mail_export_write_failed" }, "/home/ada/Mail"), + "Could not write the .eml file to /home/ada/Mail", "a picked folder is named in the failure") +assert.strictEqual(actions.exportErrorText({ message: "mail_export_write_failed" }), + "Could not write the .eml file to Downloads") console.log("eml export API gate and account routing tests passed")