From 3ae77c61dd7b4b7af55af9918272a6be4e0ee9be Mon Sep 17 00:00:00 2001 From: Jason Lee Date: Tue, 29 Sep 2026 22:05:25 +0800 Subject: [PATCH 01/22] Add a Settings button that makes Omamail the default mail client (#301) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Omarchy's `SUPER+SHIFT+E` opens HEY's web app directly (`{ webapp = "https://app.hey.com" }` in `default/hypr/bindings/applications.lua`) and reads no default, so claiming `mailto:` alone leaves the key opening HEY. This follows omanta's approach for `SUPER+SHIFT+F`: - `scripts/default-mail.sh on ` registers `omamail.desktop` as the `x-scheme-handler/mailto` default and appends a managed block to `~/.config/hypr/bindings.lua` that unbinds and rebinds `SUPER+SHIFT+E` (open Omamail) and `SUPER+SHIFT+ALT+E` (new message, `{"compose":true}`), then reloads Hyprland. Omarchy's own files are never touched. - `off` removes the block and leaves the file byte-identical; `status` prints `default` or `not-default`. - Settings gains a **Default mail client** section with **Set as default** / **Undo**. `Service.qml` runs the script from the plugin directory, so the feature is QML plus a script and needs no backend release β€” there is no Rust or `backend-api.json` change. The status is read when the service starts, when the page's `service` binds and whenever the page comes into view, so a change made outside the window is reflected. The section is shown only where the platform declares `mailto`. ## Screenshots Pending: before/after of Settings β†’ Default mail client. ## Release Notes - Add Settings β†’ Default mail client, which makes Omamail open `mailto:` links, `SUPER+SHIFT+E` and `SUPER+SHIFT+ALT+E`, with an Undo that restores Omarchy's own email binding. ## Verification - `tests/test_default_mail.sh` (added to `make test-shell`): on, idempotent second on, status, byte-identical off, unknown action refused β€” in a throwaway config/data home. - Tested by hand in the linked plugin: Set as default, `SUPER+SHIFT+E` / `SUPER+SHIFT+ALT+E`, Undo. - `make test-js test-shell`, `make qml-check`, `omarchy plugin validate .`, `git diff --check` pass. - `make test-qml`: 8 `KeyboardReaderNavigation` failures, identical on clean `main`. πŸ€– Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- Makefile | 1 + README.md | 8 ++- scripts/default-mail.sh | 106 +++++++++++++++++++++++++++++++++ tests/test_default_mail.sh | 43 +++++++++++++ ui/Service.qml | 41 +++++++++++++ ui/components/SettingsPage.qml | 102 +++++++++++++++++++++++++++++++ 6 files changed, 300 insertions(+), 1 deletion(-) create mode 100755 scripts/default-mail.sh create mode 100755 tests/test_default_mail.sh diff --git a/Makefile b/Makefile index ca55d4f..be0aa22 100644 --- a/Makefile +++ b/Makefile @@ -190,6 +190,7 @@ test-shell-portable: bash tests/test_agent_job.sh bash tests/test_link_plugin.sh bash tests/test_mailto.sh + bash tests/test_default_mail.sh bash tests/test_transport.sh bash tests/test_jmap_transport.sh python3 tests/test_jmap_stream.py diff --git a/README.md b/README.md index d4bbbf7..e5ad9b0 100644 --- a/README.md +++ b/README.md @@ -67,9 +67,15 @@ Choose a provider in Settings. Gmail needs a Google OAuth client; Outlook needs See [mailbox setup](docs/MAILBOXES.md) for provider instructions and limitations, including Microsoft 365 and Proton Mail Bridge. +## Make Omamail the default mail client + +Omarchy opens HEY's web app on `SUPER+SHIFT+E`. Choose **Settings β†’ Default mail client β†’ Set as default** to make Omamail open `mailto:` links, `SUPER+SHIFT+E`, and `SUPER+SHIFT+ALT+E` for a new message. + +The key bindings go in a clearly marked block in `~/.config/hypr/bindings.lua`; Omarchy's own files are never changed. **Undo** removes the block and leaves the file as it was. + ## Open the Omarchy plugin from the keyboard -Add this to `~/.config/hypr/bindings.lua`: +To use another key, add this to `~/.config/hypr/bindings.lua`: ```lua o.bind("SUPER + SHIFT + G", "Omamail", "omarchy shell shell toggle omamail '{}'") diff --git a/scripts/default-mail.sh b/scripts/default-mail.sh new file mode 100755 index 0000000..11165cc --- /dev/null +++ b/scripts/default-mail.sh @@ -0,0 +1,106 @@ +#!/bin/sh +# Makes Omamail the desktop's mail client, or hands the job back. +# +# default-mail.sh on claim mailto: and SUPER+SHIFT+E +# default-mail.sh off restore Omarchy's own email bindings +# default-mail.sh status print `default` or `not-default` +# +# Two things decide "which mail client" on Omarchy, and a switch that moved +# only one would leave the other opening HEY: +# +# - the x-scheme-handler/mailto default, which register-mailto.sh owns +# - SUPER+SHIFT+E and SUPER+SHIFT+ALT+E, overridden by a managed block in +# ~/.config/hypr/bindings.lua (hl.unbind + o.bind, the documented pattern) +# +# Omarchy's own files are never touched. `off` removes the block and leaves the +# file byte-identical to what it was before `on`; the mailto default stays with +# Omamail because Omarchy ships no handler to give it back to. +set -eu + +CONFIG_HOME=${XDG_CONFIG_HOME:-${HOME:?}/.config} +BINDINGS_FILE="$CONFIG_HOME/hypr/bindings.lua" +BLOCK_BEGIN="-- >>> omamail default mail client, do not edit by hand" +BLOCK_END="-- <<< omamail default mail client" + +fail() { + printf '%s\n' "$1" >&2 + exit 1 +} + +usage() { + fail 'usage: default-mail.sh on | off | status' +} + +bindings_block() { + cat < 0; blanks--) print ""; print } + ' "$BINDINGS_FILE" > "$tmp" + mv "$tmp" "$BINDINGS_FILE" +} + +add_block() { + mkdir -p "$(dirname "$BINDINGS_FILE")" + [ -f "$BINDINGS_FILE" ] || : > "$BINDINGS_FILE" + remove_block + printf '\n%s\n' "$(bindings_block)" >> "$BINDINGS_FILE" +} + +reload_hyprland() { + if [ -n "${HYPRLAND_INSTANCE_SIGNATURE:-}" ] && command -v hyprctl >/dev/null 2>&1; then + hyprctl reload >/dev/null 2>&1 || true + fi +} + +mailto_default() { + command -v xdg-mime >/dev/null 2>&1 || return 0 + xdg-mime query default x-scheme-handler/mailto 2>/dev/null || true +} + +case "${1:-}" in + on) + [ "$#" -eq 2 ] || usage + plugin_dir=$(cd "$2" && pwd) + sh "$plugin_dir/scripts/register-mailto.sh" "$plugin_dir" --claim-default + add_block + reload_hyprland + printf '%s\n' 'Omamail is now the default mail client.' + printf '%s\n' 'SUPER+SHIFT+E opens Omamail; SUPER+SHIFT+ALT+E starts a new message.' + ;; + off) + [ "$#" -eq 1 ] || usage + remove_block + reload_hyprland + printf '%s\n' "SUPER+SHIFT+E is Omarchy's own email binding again." + ;; + status) + [ "$#" -eq 1 ] || usage + if has_block && [ "$(mailto_default)" = omamail.desktop ]; then + printf '%s\n' default + else + printf '%s\n' not-default + fi + ;; + *) usage ;; +esac diff --git a/tests/test_default_mail.sh b/tests/test_default_mail.sh new file mode 100755 index 0000000..a8c41b8 --- /dev/null +++ b/tests/test_default_mail.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# default-mail.sh claims mailto: and Omarchy's SUPER+SHIFT+E, and undoing it +# must leave the user's bindings.lua exactly as it was. Runs against a +# throwaway config and data home; Hyprland is never reloaded. +set -eu + +root=$(cd "$(dirname "$0")/.." && pwd) +script="$root/scripts/default-mail.sh" +fail() { printf 'test_default_mail.sh: %s\n' "$1" >&2; exit 1; } + +[ -x "$script" ] || fail "scripts/default-mail.sh must be executable" + +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +export XDG_CONFIG_HOME="$tmp/config" XDG_DATA_HOME="$tmp/data" HYPRLAND_INSTANCE_SIGNATURE= +bindings="$XDG_CONFIG_HOME/hypr/bindings.lua" +mkdir -p "$(dirname "$bindings")" +printf -- '-- mine\nhl.unbind("PRINT")\n' > "$bindings" +cp "$bindings" "$tmp/original" + +[ "$(sh "$script" status)" = not-default ] || fail "a fresh config must not report default" + +sh "$script" on "$root" >/dev/null +grep -qxF 'hl.unbind("SUPER + SHIFT + E")' "$bindings" || fail "on must unbind Omarchy's SUPER+SHIFT+E" +grep -qF "o.bind(\"SUPER + SHIFT + E\", \"Email\", \"omarchy-shell shell summon omamail '{}'\")" "$bindings" \ + || fail "on must bind SUPER+SHIFT+E to summon Omamail" +grep -qF 'compose' "$bindings" || fail "on must bind SUPER+SHIFT+ALT+E to a new message" +[ -f "$XDG_DATA_HOME/applications/omamail.desktop" ] || fail "on must register omamail.desktop" +if command -v xdg-mime >/dev/null 2>&1; then + [ "$(sh "$script" status)" = default ] || fail "on must report default" +fi + +sh "$script" on "$root" >/dev/null +[ "$(grep -c 'omamail default mail client, do not edit' "$bindings")" = 1 ] \ + || fail "a second on must not add a second block" + +sh "$script" off >/dev/null +cmp -s "$tmp/original" "$bindings" || fail "off must restore bindings.lua byte for byte" +[ "$(sh "$script" status)" = not-default ] || fail "off must report not-default" + +if sh "$script" bogus >/dev/null 2>&1; then fail "an unknown action must fail"; fi + +printf 'test_default_mail.sh ok\n' diff --git a/ui/Service.qml b/ui/Service.qml index 7da0c91..10faa33 100644 --- a/ui/Service.qml +++ b/ui/Service.qml @@ -389,6 +389,29 @@ Item { mailtoInstaller.running = true } + // Whether mailto: links and Omarchy's SUPER+SHIFT+E open Omamail. Empty + // until default-mail.sh has been asked; the settings page asks on open, + // because either half can change behind this window's back. + property string defaultMailClient: "" + property bool defaultMailClientBusy: false + property string defaultMailClientError: "" + + function refreshDefaultMailClient() { + if (!hasMailto || pluginDir === "" || defaultMailClientProcess.running) return + defaultMailClientProcess.command = [pluginDir + "/scripts/default-mail.sh", "status"] + defaultMailClientProcess.running = true + } + + function setDefaultMailClient(enabled) { + if (!hasMailto || pluginDir === "" || defaultMailClientProcess.running) return + defaultMailClientBusy = true + defaultMailClientError = "" + defaultMailClientProcess.command = enabled + ? [pluginDir + "/scripts/default-mail.sh", "on", pluginDir] + : [pluginDir + "/scripts/default-mail.sh", "off"] + defaultMailClientProcess.running = true + } + function applySettings(values) { var next = normalizedSettings(values) if (JSON.stringify(next) !== JSON.stringify(settings)) settings = next @@ -2799,6 +2822,23 @@ Item { stderr: StdioCollector { waitForEnd: true } } + Process { + id: defaultMailClientProcess + stdout: StdioCollector { waitForEnd: true } + stderr: StdioCollector { waitForEnd: true } + onExited: function(exitCode) { + if (root.defaultMailClientBusy) { + root.defaultMailClientBusy = false + if (exitCode !== 0) root.defaultMailClientError = + String(stderr.text || "").trim() || "Could not change the default mail client" + // The status read cannot start from inside this process's own exit. + Qt.callLater(root.refreshDefaultMailClient) + return + } + if (exitCode === 0) root.defaultMailClient = String(stdout.text || "").trim() + } + } + Component.onCompleted: { barBridge = BarBridge.publish(function() { return { @@ -2813,6 +2853,7 @@ Item { Qt.callLater(root.restoreAccountRegistry) Qt.callLater(root.refreshRecipientContacts) Qt.callLater(root.registerMailtoHandler) + Qt.callLater(root.refreshDefaultMailClient) } property var barBridge: null diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml index fbd4d66..7f0c0d3 100644 --- a/ui/components/SettingsPage.qml +++ b/ui/components/SettingsPage.qml @@ -44,6 +44,8 @@ Column { var values = [{ key: "backend", title: "Mail backend", y: backendSetup.y }] if (!root.service || root.service.hasTray !== false) values.push({ key: "bar", title: "Bar", y: barHeading.y }) + if (root.service && root.service.hasMailto === true) + values.push({ key: "mailClient", title: "Default mail client", y: mailClientHeading.y }) values.push({ key: "reading", title: "Reading", y: readingHeading.y }) if (!root.service || root.service.hasNotifications !== false || String(root.service.notificationError || "") !== "") @@ -240,7 +242,17 @@ Column { ensureSignatureAccount() ensureNameAccount() } + // The page is built with the window, before `service` is bound, and either + // half of the answer can change from a terminal while the window is open β€” + // so ask whenever the page comes into view, not once. + function refreshDefaultMailClient() { + if (visible && service && typeof service.refreshDefaultMailClient === "function") + service.refreshDefaultMailClient() + } + onServiceChanged: refreshDefaultMailClient() + onVisibleChanged: refreshDefaultMailClient() Component.onCompleted: { + refreshDefaultMailClient() renderSignaturePreview() ensureSignatureAccount() ensureNameAccount() @@ -426,6 +438,96 @@ Column { } } + // --------------------------------------------------- default mail client + // + // Omarchy opens HEY's web app on SUPER+SHIFT+E, and mailto: links go to + // whatever claimed them. scripts/default-mail.sh moves both, and undoing it + // gives the key back to Omarchy. + + Text { + id: mailClientHeading + visible: !!root.service && root.service.hasMailto === true + text: "DEFAULT MAIL CLIENT" + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + font.letterSpacing: 1 + } + + Rectangle { + id: mailClientRow + objectName: "default-mail-client-settings" + visible: !!root.service && root.service.hasMailto === true + width: parent.width + implicitHeight: Math.max(mailClientText.implicitHeight, mailClientButton.implicitHeight) + + Style.space(16) + radius: Style.cornerRadius + color: Style.normalFillFor(root.textColor, root.accentColor) + + readonly property bool isDefault: !!root.service + && root.service.defaultMailClient === "default" + + Column { + id: mailClientText + anchors.left: parent.left + anchors.leftMargin: Style.space(12) + anchors.right: mailClientButton.left + anchors.rightMargin: Style.space(10) + anchors.verticalCenter: parent.verticalCenter + spacing: Style.space(2) + + Text { + width: parent.width + text: mailClientRow.isDefault + ? "Omamail is the default mail client" + : "Set up Omamail as the default mail client" + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.bodySmall + wrapMode: Text.WordWrap + textFormat: Text.PlainText + } + + Text { + width: parent.width + text: "Opens mailto: links, SUPER+SHIFT+E, and SUPER+SHIFT+ALT+E for a new message." + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + textFormat: Text.PlainText + } + + Text { + width: parent.width + visible: text !== "" + text: root.service ? String(root.service.defaultMailClientError || "") : "" + color: root.urgentColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + textFormat: Text.PlainText + } + } + + IconTextButton { + id: mailClientButton + objectName: "defaultMailClientButton" + anchors.right: parent.right + anchors.rightMargin: Style.space(10) + anchors.verticalCenter: parent.verticalCenter + enabled: !!root.service && !root.service.defaultMailClientBusy + && root.service.defaultMailClient !== "" + text: mailClientRow.isDefault ? "Undo" : "Set as default" + tooltipText: mailClientRow.isDefault + ? "Give SUPER+SHIFT+E back to Omarchy's own email binding" + : "Make Omamail open mailto: links and SUPER+SHIFT+E" + foreground: root.textColor + fontFamily: root.panelFontFamily + onClicked: root.service.setDefaultMailClient(!mailClientRow.isDefault) + } + } + // --------------------------------------------------------------- reading Text { From af8a7aef4f7522adc098fab738178f884d57eba5 Mon Sep 17 00:00:00 2001 From: Nico Duldhardt <36307788+klaudworks@users.noreply.github.com> Date: Wed, 30 Sep 2026 03:41:27 +0200 Subject: [PATCH 02/22] Add a redesigned calendar and native Google integration (#300) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## A more complete calendar in Omamail This PR redesigns the calendar: clearer views, easier navigation, better event editing, and useful reminders. Google Calendar is the first provider with the deeper native integration in this work, including calendar discovery, attendance updates and event management. The redesigned views and navigation apply to the calendar as a whole. New drag/resize writes and desktop reminders are Google-only; other providers retain their existing, more limited create/edit/delete behavior. Google-specific features are called out below. ## 1. A clearer month view Multi-day events now form one continuous bar, with continuation marks when they cross a week boundary. Overlapping trips and all-day events get separate rows. The month uses five or six weeks as needed, with lighter grid lines, a clearer today marker and more room for events. Narrow Month rows put the event title before the time, so a short cell still tells you what is happening. Busy-day previews show the event count and cap their height, with a visible scrollbar for longer lists.
Before/after: narrow Month titles and a long busy-day preview **Narrow Month β€” title first instead of a time taking most of the row.** ![Narrow Month before and after](https://github.com/user-attachments/assets/83ebc1af-83af-44d3-b164-c88473ba1da5) **Busy-day preview β€” bounded height, event count and scrolling.** ![Long overflow preview before and after](https://github.com/user-attachments/assets/f1c25ca9-050e-408e-a5eb-3fe788739c18)
The same synthetic month is shown in both images. Look at **Lakeside holiday**, **Design sprint** and **Design conference**: repeated daily blocks become readable spans. | Before | After | | --- | --- | | ![Month before: repeated daily blocks and fixed six-week grid](https://github.com/user-attachments/assets/30802c1e-9a5b-405b-8d5c-6f5a661f5c69) | ![Month after: continuous multi-day bars, separate overlap rows and lighter grid](https://github.com/user-attachments/assets/a7912d29-50c6-4eab-bd4e-21373c75b535) | ### See everything on a busy day Hover a day with **β€œ+ more…”** to see its complete event list. The day stays highlighted, entries can be opened directly, and longer lists scroll. You can inspect a busy day while keeping the rest of the month in view. Here, Friday has eight events across three calendars. The after image shows all eight, alongside the multi-day bars and redesigned month layout. | Before: hovering leaves the extra events hidden | After: a full-day preview opens | | --- | --- | | ![Busy-day hover before](https://github.com/user-attachments/assets/c13a877e-6aee-4aa6-a198-a379a56c97cd) | ![Busy-day hover after: eight events with names and time ranges](https://github.com/user-attachments/assets/342f0204-77e5-4210-bdf0-e61e72f1fb6d) | ## 2. Better Day and Week views - **A permanent all-day lane.** Click or drag in it to create an all-day event, even when the lane is empty. - **Continuous bars at the top.** Multi-day all-day events and timed events lasting at least a full local day sit above the hourly grid. Timed events keep their original start/end times; this is a display change. - **A clear distinction for timed spans.** Top-lane timed events say β€œTimed”; the current-time line stays behind event cards so it cannot strike through a meeting title. - **Readable overlaps.** Simultaneous meetings use separate columns and can be selected independently. - **All 24 hours are reachable.** Day and Week open around the morning and scroll from midnight to midnight. - **Clearer interaction.** Drag to create a time range. On Google calendars, move an event or resize either edge; a preview shows the change and failed saves restore the previous position. Other providers change event times through their existing editor. This comparison combines a long timed conference, a two-day workshop, a birthday, overlapping meetings and the current-time indicator. | Before | After | | --- | --- | | ![Week before: the long conference fills the hourly grid and all-day events repeat per day](https://github.com/user-attachments/assets/84fd4e30-3522-484d-9ca3-7c4a87da9a60) | ![Week after: continuous top-lane bars and separated overlapping meetings](https://github.com/user-attachments/assets/e11a79f7-74a8-4b73-9f84-516388bb140b) |
Before/after: an empty all-day lane is still useful The same week with the top-lane events removed. The new lane remains available for click/drag creation. | Before | After | | --- | --- | | ![Empty all-day lane before](https://github.com/user-attachments/assets/654e1af6-6925-4c5e-bcf9-13fbfd299417) | ![Empty all-day lane after](https://github.com/user-attachments/assets/402abc36-e72f-42b9-9535-42229c18d5c4) |
### Navigation that takes less space
Before/after: timed-span labels and a readable current meeting ![Week label and current-time refinements](https://github.com/user-attachments/assets/0b49c412-6966-49c1-bd69-d36632b6c357)
Day, Week, Month and Agenda share one dropdown, with their keyboard shortcuts shown beside them. Previous/next arrows surround the date, clicking the date opens a picker, and Today sits alongside it. The separate Create event button is replaced by direct calendar interaction and the existing keyboard shortcut. Agenda lists upcoming and ongoing events. Finished events drop out automatically.
Screenshots: Day, Agenda and the date picker These are new views/states; the Week comparison above shows the previous calendar experience. **Day** ![Day view](https://github.com/user-attachments/assets/7d6de2bc-0df2-46dd-9803-101cd31231bb) **Agenda** ![Agenda view](https://github.com/user-attachments/assets/cf42c6e9-e8c0-4776-bf46-edea51d45168) **Date picker** ![Date picker](https://github.com/user-attachments/assets/daddc390-2df4-415e-9837-2867710e500b)
## 3. A more capable event editor The editor brings the calendar, dates, times and event options together: - Choose the destination calendar, grouped by account. - Set separate start/end dates and switch between timed and all-day events. - Keep a clearly labelled Description directly below the title. - Suggest guests by name or address from the same known email contacts as the mail composer. Choose with a click or Up/Down and Enter; already-added addresses are excluded. - Edit the location, description, guests, time zone, availability, privacy and reminders where supported. - Add Google Meet and edit supported repeating-event rules. Advanced recurrence rules are preserved. - Press **Enter** to save and close. Invalid ranges show an error and prevent saving; a failed save keeps the form open. - Keep Save, Cancel and save errors in a fixed footer, even when the form scrolls. Keyboard-focused fields and guest suggestions scroll into view. - See persistent field labels, an explicit local-time indicator and reminder units. Time zone, availability and visibility live under **More options**. | Before | After | | --- | --- | | ![Event editor before](https://github.com/user-attachments/assets/ab27092c-0b3e-4269-850d-03812d002ff3) | ![Event editor after](https://github.com/user-attachments/assets/8bc49395-cf94-443d-b42a-028d4516fb61) | ### A compact form with visible feedback Description sits directly below Title with a persistent label. Typing a guest's name or email shows the same contact suggestions as composing mail. Enter chooses a suggestion while the list is open; Escape dismisses it without closing the event. Choosing a guest inserts only the email address and never submits the event. **Before/after: persistent labels, simpler default form and fixed action footer.** ![Editor before and after](https://github.com/user-attachments/assets/af9c6509-7a58-43f4-a599-a428b9d81644) **Before/after: a failed save in the same 660 Γ— 900 window.** The error was below the scrolling viewport; it is now visible beside the save actions without manual scrolling. ![Failed save before and after](https://github.com/user-attachments/assets/6dda2870-60a2-496f-b7ac-8aae56941240)
More editor comparisons: guest suggestions, reminder units and dark theme ![Guest suggestions before and after](https://github.com/user-attachments/assets/c1a57a01-b1f2-41b0-856c-622d0650f80f) ![Custom reminder units before and after](https://github.com/user-attachments/assets/69299e3f-23db-463c-aabb-cd6811682de5) ![Dark editor before and after](https://github.com/user-attachments/assets/888f95ca-463e-4316-8423-173b56d5592a)
## 4. Google integration that updates the actual calendar This goes beyond displaying Google events: | Action | What Omamail now does | | --- | --- | | **Connect calendars** | Finds the account's calendars, including shared and hidden entries. Lets you choose which to show and respects read-only access. | | **Answer an invitation in mail** | Yes / Maybe / No updates your own attendance in Google Calendar, then reads the event back to confirm the result. The native RSVP path does not send a second reply email. | | **Reopen an invitation or event** | Refreshes attendance and guest details, so the displayed answers can follow changes made elsewhere. | | **Edit or move an event** | Saves changes to the selected Google calendar. Supports moving eligible organizer-owned events between calendars in the same account. | | **Change an event with guests** | Offers a choice to notify guests or save without sending an update. Deletion has the same notification choice. | | **Work with a repeating event** | Loads the parent when editing the whole series and preserves existing recurrence exceptions. | | **Undo a supported change** | Checks the event revision before writing, to avoid overwriting a newer change. | | **Open meeting details** | Shows guest response states and the meeting link, with a copy action. | If an invitation cannot be matched to Google Calendar, or the connected backend is API 5, Omamail offers **Open Calendar** and clearly labelled **email-only** responses. An email-only reply does not mark Calendar attendance as confirmed. Gmail-generated travel events also explain their editing restrictions instead of offering unsupported time changes.
Before/after: Gmail invitations on the pinned API-5 backend The API-5 backend cannot execute native attendance updates. The invitation now offers explicit email-only responses instead of native choices that fail. These synthetic production-component captures use identical 900 Γ— 600 dimensions, Solarized Light and scale 1; baseline `76c4e3a`. | Before | After | | --- | --- | | ![Before: unavailable native attendance choices on API 5](https://github.com/user-attachments/assets/9568c8ce-6309-4995-80ef-145436d4dd52) | ![After: clearly labelled email-only replies](https://github.com/user-attachments/assets/4d2c8505-2ad5-460f-ad43-cc2ba4965b52) |
The fallback shows one clear set of response choices. Event details put **Join meeting** and **Edit** near the title, followed by the description and guests. One **Delete...** control reveals the notification/series choices before the existing confirmation dialog.
Before/after: meeting details, delete choices and email-only invitation fallback ![Narrow meeting details before and after](https://github.com/user-attachments/assets/3823c758-2acd-4320-9a7c-4d1302587578) ![Delete choices before and after](https://github.com/user-attachments/assets/26bda0dd-4ed7-45bd-8082-30a41048e7c0) ![Invitation fallback before and after](https://github.com/user-attachments/assets/75c70e93-e396-4955-b3a8-a38c22453d68)
Screenshot: guest responses and meeting details ![Guest response states and meeting link](https://github.com/user-attachments/assets/fa909533-d264-4292-b069-0c26bec102f7) This synthetic capture illustrates the UI. It is not evidence of a live Google RSVP round trip; testing and remaining checks are listed below.
### Other providers keep their limited behavior Microsoft/Outlook, iCloud and generic CalDAV keep the shared redesigned views and their existing basic event operations, with read-only and recurring-CalDAV restrictions preserved. Deep native attendance, transfers and advanced Google options remain Google-specific. New drag/resize writes and desktop reminders are explicitly restricted to Google, including polling and candidate generation: previously saved non-Google reminder settings cannot enable them. Microsoft creation omits the unsupported Repeat control and ignores stale repeat state after switching calendars. This is a compatibility boundary, not an expansion of the other provider adapters. Inherited limitations remain, including Outlook's preview-based description editing and incomplete attendee-status normalization; the new gestures no longer expose that editing path.
Before/after: limited Microsoft editor and calendar settings Synthetic production-component captures at identical 1000 Γ— 1100 dimensions, Solarized Light, font base 14 and scale 1; baseline `c50c3f1`. The Microsoft editor no longer offers repetition that saving would reject. Settings remove non-Google reminder controls, including the global reminder section when no Google calendar is connected. | Microsoft editor β€” before | Microsoft editor β€” after | | --- | --- | | ![Microsoft editor before](https://github.com/user-attachments/assets/03a99433-5a5d-496e-b2be-f1862c9f438d) | ![Microsoft editor after](https://github.com/user-attachments/assets/65bdc041-728c-4392-9ca7-aee4b37cbdaa) | | Microsoft settings β€” before | Microsoft settings β€” after | | --- | --- | | ![Microsoft settings before](https://github.com/user-attachments/assets/b1a714a5-9c64-4345-a975-574d0fd4d5be) | ![Microsoft settings after](https://github.com/user-attachments/assets/5330d9da-3daa-44e6-ba6a-d268494f97e6) |
## 5. Clearer setup and reminders Settings now start with accounts and use **one calendar list** for visibility and reminder preferences. Each account has a dropdown for its default calendar for new events. Default-calendar and reminder settings can be saved for any available account, even when another mailbox is selected; event writes retain their mailbox scope. Google setup reuses the Gmail account and shared OAuth client, with specific actions to retry discovery, sign in again or enable the Calendar API. Google desktop reminders have a global on/off switch, per-calendar timing and a snooze duration. They run while Omamail is running, even with its window closed. Hiding a Google calendar does not turn off its reminders. Google event reminders respect events that explicitly have no reminders. Notifications request **Open, Snooze and Dismiss**, but some desktop notification cards expose only the default action. Delivered reminders therefore also appear in the calendar and matching event details, with visible **Snooze** and **Dismiss** buttons. Opening a notification no longer dismisses its reminder. Failed reminder actions leave the controls available with an error; successful actions remove the notice. Old notification callbacks cannot acknowledge a newer delivery in the same running instance. A private persistent ledger prevents duplicate claims across shell and standalone instances. Each due event retains its own details and independent actions: dismissing one cannot dismiss or cancel another event's snooze, including records from an older grouped ledger. Reaching the desktop notification-process limit does not remove events from the in-app inbox. The in-app action list is session-local; restoring that list across restarts and cross-instance action synchronization remain runtime verification gaps.
Before/after: two reminders due in the same poll The grouped response exposed only the first event and a count. Each event now has its own title, Open, Snooze and Dismiss controls. These synthetic production-component captures replay the old and new response shapes for the same events at identical 900 Γ— 600 dimensions, Solarized Light and scale 1; baseline `76c4e3a`. | Before | After | | --- | --- | | ![Before: second event hidden behind a count](https://github.com/user-attachments/assets/dda748c0-3123-49ea-b160-9e021485aa04) | ![After: both events independently actionable](https://github.com/user-attachments/assets/fd6c7474-5d56-440b-b5fd-d5e185fbcc46) |
**Before/after: reminder actions in narrow event details.** ![Reminder event actions before and after](https://github.com/user-attachments/assets/4a61f5bf-311d-4564-b53d-5810be58a662)
Reminder actions in the calendar and a failed-action state ![Calendar reminders before and after](https://github.com/user-attachments/assets/fa73b844-a4e6-40ca-8207-0a8bb68becb9) **After: failure keeps the reminder and its actions available.** ![Reminder action error](https://github.com/user-attachments/assets/3f90d952-8e9f-430b-bd54-137e22720524)
| Before | After | | --- | --- | | ![Calendar settings before](https://github.com/user-attachments/assets/a06afb96-12a7-4a27-8185-f21d020cd179) | ![Calendar settings after](https://github.com/user-attachments/assets/e6d795c1-5218-4e40-ae5e-28ef15969c11) |
More setup screenshots: connected accounts, selection, recovery and narrow layouts These pairs show the final settings refinement compared with the earlier version of this calendar implementation. | State | Before refinement | After refinement | | --- | --- | --- | | One list for each account's calendars | ![Connected before](https://github.com/user-attachments/assets/a255701d-4644-46c5-9273-deaaac4fdc54) | ![Connected after](https://github.com/user-attachments/assets/4c2e2bd9-3455-4f81-872c-542a61cfbf71) | | First-time setup | ![Initial before](https://github.com/user-attachments/assets/c1cd9fd5-012a-41c2-bc8a-fe2e54c6d5c7) | ![Initial after](https://github.com/user-attachments/assets/734b16a6-18e1-472e-8db0-d3904bf73812) | | Choose calendars | ![Selection before](https://github.com/user-attachments/assets/2d4e7f98-33b8-43a7-9d2c-1d29744680d5) | ![Selection after](https://github.com/user-attachments/assets/9561df5a-9cc6-4f66-b712-8bea261e8398) | | Recover from a connection error | ![Recovery before](https://github.com/user-attachments/assets/8214eb6e-9cde-4ead-a760-ea0501c0b70e) | ![Recovery after](https://github.com/user-attachments/assets/de744b3b-4cbe-4686-b46f-18ca95780e53) | | Narrow settings | ![Narrow before](https://github.com/user-attachments/assets/6a168898-4217-419f-a3a0-a26bb5ade876) | ![Narrow after](https://github.com/user-attachments/assets/23379946-da80-4a38-afbb-d417aa607e60) | **Reminder timing:** Off, Use Google event reminders, or Custom timing. ![Expanded reminder options](https://github.com/user-attachments/assets/b9e796ad-4b98-4b80-ad51-73a5b08d820f)
## Testing and review status **Latest diagnostics repair (`63b6716`):** added the backend’s `calendar_organizer_mismatch` identifier to the exact diagnostics allowlist, fixing the portable-test failure on `d393151`. The full portable shell suite and full `make validate` pass locally on this head. Fresh CI is pending; earlier green runs do not establish the status of this commit. **Validation:** Full `make validate` passes for `3704706`: Rust, JavaScript, shell/source checks, QML suites, standalone UI tests, QML lint and plugin validation. Both the development API-6 contract and pinned 0.10.7/API-5 released contract pass. Regression tests first failed against the original implementation, then passed for API-5 email-only replies, settings for another account, all-day drag moves across spring/autumn DST, and independent simultaneous reminders. The reminder tests also cover legacy grouped records and retaining inbox entries when the desktop process limit is reached. Provider-limit, editor interaction, reminder retry/stale-callback and event-identity coverage remain included. All 85 synthetic audit after captures, four provider-limit images and four review-repair images were inspected. This follow-up has not been installed locally. Cross-platform CI for `3704706` is pending. Previous cross-platform CI passed all 14 checks, including both macOS jobs, Linux/Windows standalone apps and backends, native credential contracts, portable tests and published/unreleased backend gates. Results for the newly pushed head must be checked separately. The concurrency regression reproduced a first lock-file creation failure on macOS with OS error `ENOENT`, matching the documented Darwin `openat(O_CREAT)` create-or-open race ([upstream report](https://github.com/golang/go/issues/81246)). The fix uses exclusive creation followed, only on `EEXIST`, by a non-creating open of the existing lock file. Both calls remain descriptor-relative and no-follow; ownership, link-count, private-mode and ACL validation still precede locking. Concurrent initialization, reminder claims and unsafe-existing-lock regressions now pass in macOS CI as well as locally. Focused tests cover multi-day layout, overlap selection, full-day scrolling and 23:00 event creation, drag/resize rollback, Enter-to-save, invalid dates, timed/all-day request conversion, discovery recovery, attendance handling and reminder behavior. One user-requested calendar transfer was also checked against Google with a follow-up read. **Ready for review; remaining verification:** broader live Google checks remain, especially attendance matching outside the primary calendar, recurrence exceptions, all-day conversion and partial-transfer/Undo behavior. Reminder restart, suspend, cross-instance actions and Do Not Disturb behavior also need more runtime coverage. Desktop notification delivery is currently Linux-specific. Synthetic invitation and reminder interaction screenshots are included above; these do not establish live provider or desktop lifecycle behavior.
Implementation and security notes for reviewers - Calendar sources, caches and selections retain account/calendar identity. Google discovery keeps access, time-zone, reminder and conferencing metadata; older backend versions are gated from unsupported features. - Native attendance writes validate the responding attendee, use event revision checks and confirm the result by reading it back. The current lookup starts with the primary calendar copy. - Reminder fetching is independent of the visible date range. A private, locked, atomically written ledger records claims, snoozes and dismissals. - Concurrent first-time lock creation avoids Darwin's create-or-open race. Regression coverage includes concurrent initialization and refusal of symlinks, hard links, non-private files and macOS ACL grants without modifying rejected entries. - API-6 methods and contract cases are included. The published backend pin and version/API handshake are preserved. - Scoped tests cover origin/TLS/redirect restrictions, identity refusal, unsafe reminder-storage paths and notification escaping/actions. The macOS fixture resolves the trusted temporary parent and sets private fixture permissions; production storage checks remain unchanged. **Security verdict: NOT VERIFIED for release.** The scoped checks pass, but the complete new Google integration and reminder lifecycle still need the runtime evidence described above before approval.
About the screenshots All images are synthetic Qt component captures using production calendar components and standalone UI adapters, with synthetic accounts/events and Solarized Light colours. They are not private live-mail screenshots. PNGs are uploaded to GitHub attachments and are not committed. Each before/after pair uses the same events, dates, window dimensions, theme, font size and scale. Main Month/Week scenes are 1440 Γ— 1000, font base 14, scale 1. Editor/settings and additional view captures are 1200 Γ— 1000. Settings-refinement pairs are 1000 Γ— 1200, or 660 Γ— 1200 for the narrow view. The main baseline is the pre-workspace calendar at `d583ab6`; settings-refinement pairs use `976c97a`. Before/after hover captures place the pointer over the same busy date. Week captures show each version's initial presentation of the same date range; the redesign's morning scroll position and long-event placement are intentional differences. The labelled side-by-side audit comparisons use `612a92a` as their baseline. Each half retains the same dimensions, fixture state, theme and scale: 1200 Γ— 1100 for the editor, 660 Γ— 900 for save failure and narrow details, 660 Γ— 1000 for narrow Month, 1440 Γ— 1000 for Week, and 900 Γ— 700 for the invitation fallback. Dark editor and reminder/overflow comparisons use 1200 Γ— 1000. The evidence includes 85 after-state captures and matched baselines; images were reviewed at contact-sheet and full resolution. No real event or RSVP mutation was made for this audit.
## Release Notes - Redesign the calendar with clearer Month and Week layouts, Day and Agenda views, simpler navigation and full-day scrolling. - Show continuous multi-day events, a permanent all-day lane and complete busy-day hover previews. - Improve event creation and editing with multi-date ranges, richer options and Enter-to-save validation; enable drag/resize changes for Google events. - Suggest calendar guests from known email contacts and place a clearly labelled description below the event title. - Keep event save controls and errors visible, label reminder units, and simplify meeting details and invitation fallback choices. - Add deeper Google Calendar integration for calendar selection, event management, attendance updates and guest response details. - Simplify calendar settings and add Google desktop reminders with snooze and dismiss actions. - Preserve other calendar providers' existing limited event operations without offering Google-only gestures or reminders. - Make delivered reminders actionable inside the calendar even when the desktop notification omits action buttons. - Keep Gmail email-only invitation replies available on the pinned backend, save calendar preferences across accounts, and preserve all-day dates when dragging across daylight-saving changes. - Keep simultaneous reminders independently visible and actionable, including when the desktop notification-process limit is reached. --------- Co-authored-by: Jason Lee Co-authored-by: Claude Opus 5.5 --- Makefile | 7 +- app/qml/imports/qs/Ui/Dropdown.qml | 41 +- app/qml/styles/Omamail/ComboBox.qml | 96 ++ app/qml/styles/Omamail/qmldir | 2 + app/tests/qml/tst_standalone_composition.qml | 29 +- backend-api.json | 50 +- docs/KEYS.md | 12 +- manifest.json | 19 + scripts/diagnostics.py | 3 + scripts/notify-mail.py | 9 +- src/auth/callback.rs | 3 + src/backend/methods.rs | 2 + src/backend/mod.rs | 45 + src/cache/store.rs | 2 +- src/calendar/attendance.rs | 266 ++++++ src/calendar/discovery.rs | 141 ++- src/calendar/mod.rs | 109 ++- src/calendar/reminders.rs | 352 +++++++ src/calendar/tests.rs | 129 +++ src/platform/private_fs/unix.rs | 12 +- src/platform/tests.rs | 72 ++ tests/test_agent_native_bridge.py | 46 +- tests/test_calendar_notifications.py | 95 ++ tests/test_notification.py | 7 + tests/test_qml_text_format.py | 5 +- tests/test_source.sh | 27 +- ui/App.qml | 116 +-- ui/Service.qml | 25 + ui/account/Accounts.js | 1 + ui/account/MailAccount.qml | 2 + ui/account/Rsvp.qml | 148 ++- ui/backend/Runtime.qml | 6 +- ui/calendar/Cache.js | 25 +- ui/calendar/Calendar.js | 357 ++++++- ui/calendar/CalendarCache.qml | 4 +- ui/calendar/CalendarController.qml | 308 +++++- ui/calendar/CalendarReminderInbox.qml | 53 ++ ui/calendar/CalendarReminders.qml | 108 +++ ui/calendar/Reminders.js | 45 + ui/calendar/Sources.js | 43 +- ui/components/CalendarEventComposer.qml | 895 ++++++++++++++--- ui/components/CalendarEventDetail.qml | 282 ++++-- ui/components/CalendarReminderPanel.qml | 114 +++ ui/components/CalendarSettings.qml | 913 ++++++++++++------ ui/components/CalendarView.qml | 953 +++++++++++++++++-- ui/components/ConfirmDeleteDialog.qml | 83 +- ui/components/InviteCard.qml | 44 +- ui/components/MessageReader.qml | 3 + ui/components/SettingsPage.qml | 14 +- ui/components/ShortcutHelp.qml | 1 + ui/components/WeekCalendarView.qml | 423 ++++++-- ui/components/WindowMoveArea.qml | 24 + ui/keys/Keymap.js | 19 +- ui/providers/OAuth.js | 3 +- ui/providers/Registry.js | 8 + ui/tests/qml/tst_app_compose_pending.qml | 2 +- ui/tests/qml/tst_app_navigation.qml | 14 +- ui/tests/qml/tst_backend_runtime.qml | 27 + ui/tests/qml/tst_calendar_attendance.qml | 150 +++ ui/tests/qml/tst_calendar_controller.qml | 129 ++- ui/tests/qml/tst_calendar_detail_refresh.qml | 156 +++ ui/tests/qml/tst_calendar_event_composer.qml | 230 +++++ ui/tests/qml/tst_calendar_gestures.qml | 223 +++++ ui/tests/qml/tst_calendar_reminder_inbox.qml | 150 +++ ui/tests/qml/tst_calendar_settings.qml | 95 +- ui/tests/qml/tst_confirm_delete.qml | 77 ++ ui/tests/qml/tst_preview_on_cursor.qml | 4 + ui/tests/test_calendar_cache.js | 13 + ui/tests/test_calendar_feed.js | 186 +++- ui/tests/test_calendar_reminders.js | 21 + ui/tests/test_calendar_sources.js | 16 + ui/tests/test_oauth.js | 4 +- 72 files changed, 7222 insertions(+), 876 deletions(-) create mode 100644 app/qml/styles/Omamail/ComboBox.qml create mode 100644 src/calendar/attendance.rs create mode 100644 src/calendar/reminders.rs create mode 100644 tests/test_calendar_notifications.py create mode 100644 ui/calendar/CalendarReminderInbox.qml create mode 100644 ui/calendar/CalendarReminders.qml create mode 100644 ui/calendar/Reminders.js create mode 100644 ui/components/CalendarReminderPanel.qml create mode 100644 ui/components/WindowMoveArea.qml create mode 100644 ui/tests/qml/tst_calendar_attendance.qml create mode 100644 ui/tests/qml/tst_calendar_detail_refresh.qml create mode 100644 ui/tests/qml/tst_calendar_gestures.qml create mode 100644 ui/tests/qml/tst_calendar_reminder_inbox.qml create mode 100644 ui/tests/qml/tst_confirm_delete.qml create mode 100644 ui/tests/test_calendar_reminders.js diff --git a/Makefile b/Makefile index be0aa22..8f789af 100644 --- a/Makefile +++ b/Makefile @@ -66,14 +66,15 @@ QML_FILES := ui/Service.qml ui/BarWidget.qml ui/App.qml ui/compose/RecoveryContr ui/components/SettingsSidebar.qml \ ui/components/CalendarSettings.qml \ ui/components/CalendarEventComposer.qml \ - ui/components/CalendarEventDetail.qml \ + ui/components/CalendarEventDetail.qml ui/components/CalendarReminderPanel.qml \ ui/components/CalendarPalette.qml \ ui/components/ConfirmDeleteDialog.qml \ ui/components/SetupPage.qml \ ui/components/ShortcutHelp.qml \ - ui/calendar/CalendarController.qml ui/calendar/CalendarCache.qml \ + ui/calendar/CalendarController.qml ui/calendar/CalendarCache.qml ui/calendar/CalendarReminders.qml ui/calendar/CalendarReminderInbox.qml \ ui/components/CalendarView.qml \ ui/components/WeekCalendarView.qml \ + ui/components/WindowMoveArea.qml \ ui/bar/BarPreview.qml APP_QML_FILES := app/qml/Main.qml app/qml/StandaloneShell.qml app/qml/StandaloneManifest.qml APP_BUILD_DIR ?= app/build @@ -138,6 +139,7 @@ test-js: node ui/tests/test_calendar_cache.js node ui/tests/test_calendar_feed.js node ui/tests/test_calendar_sources.js + node ui/tests/test_calendar_reminders.js node ui/tests/test_calendar_palette.js node ui/tests/test_bar_preview.js node ui/tests/test_unsubscribe.js @@ -179,6 +181,7 @@ test-shell-portable: sh tests/test_dev.sh python3 tests/test_attachment_common.py python3 tests/test_notification.py + python3 tests/test_calendar_notifications.py python3 tests/test_curl_config.py python3 tests/test_public_http.py python3 tests/test_contacts.py diff --git a/app/qml/imports/qs/Ui/Dropdown.qml b/app/qml/imports/qs/Ui/Dropdown.qml index bb2fdb7..a64fd01 100644 --- a/app/qml/imports/qs/Ui/Dropdown.qml +++ b/app/qml/imports/qs/Ui/Dropdown.qml @@ -67,14 +67,45 @@ Item { palette.button: root.background palette.highlight: root.accent palette.window: root.background + font.family: root.fontFamily + font.pixelSize: Style.font.bodySmall + // One row per option at the shell's popup row height: the cursor row takes + // the hover fill, the chosen one a check, and neither is coloured with the + // accent. delegate: QQC.ItemDelegate { + id: option required property var modelData - width: combo.width + required property int index + width: combo.width - 2 height: root.popupRowHeight - text: String(modelData.label || "") - font.family: root.fontFamily - palette.text: root.foreground - palette.highlight: root.accent + leftPadding: Style.spacing.controlPaddingX + rightPadding: Style.spacing.controlPaddingX + highlighted: combo.highlightedIndex === index + contentItem: Row { + spacing: Style.space(6) + Text { + width: Style.space(12) + anchors.verticalCenter: parent.verticalCenter + text: option.index === combo.currentIndex ? "βœ“" : "" + color: root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.bodySmall + } + Text { + anchors.verticalCenter: parent.verticalCenter + width: option.availableWidth - Style.space(18) + text: String(option.modelData.label || "") + textFormat: Text.PlainText + elide: Text.ElideRight + color: root.foreground + font.family: root.fontFamily + font.pixelSize: Style.font.bodySmall + } + } + background: Rectangle { + color: option.highlighted || option.hovered + ? Style.hoverFillFor(root.foreground, root.accent) : "transparent" + } } onActivated: function(index) { if (index < 0 || index >= root.options.length) return diff --git a/app/qml/styles/Omamail/ComboBox.qml b/app/qml/styles/Omamail/ComboBox.qml new file mode 100644 index 0000000..c18278d --- /dev/null +++ b/app/qml/styles/Omamail/ComboBox.qml @@ -0,0 +1,96 @@ +import QtQuick +import QtQuick.Templates as T +import qs.Commons + +// The shell's Dropdown, drawn here: a platform ComboBox brings its own +// up/down arrows and its own type size, which read as a foreign control in a +// settings row whose other controls follow the shell's scale. +T.ComboBox { + id: control + + readonly property color semanticForeground: palette.buttonText + readonly property color semanticAccent: palette.highlight + readonly property int chevronSize: Math.max(8, Math.round(Style.font.bodySmall * 0.7)) + + implicitWidth: Style.spacing.dropdownWidth + implicitHeight: Style.spacing.controlHeight + leftPadding: Style.spacing.controlPaddingX + rightPadding: Style.spacing.controlPaddingX * 2 + chevronSize + font.pixelSize: Style.font.bodySmall + + contentItem: Text { + text: control.displayText + font: control.font + color: control.semanticForeground + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + textFormat: Text.PlainText + } + + indicator: Canvas { + objectName: "omamail-combobox-chevron" + x: control.width - width - Style.spacing.controlPaddingX + y: (control.height - height) / 2 + width: control.chevronSize + height: Math.round(control.chevronSize / 2) + 2 + onPaint: { + var ctx = getContext("2d") + ctx.reset() + ctx.strokeStyle = control.semanticForeground + ctx.lineWidth = 1.5 + ctx.beginPath() + ctx.moveTo(1, 1) + ctx.lineTo(width / 2, height - 1) + ctx.lineTo(width - 1, 1) + ctx.stroke() + } + Connections { + target: control + function onSemanticForegroundChanged() { parent.requestPaint() } + } + } + + // The trigger holds the selected fill while its list is open, so the list + // reads as attached to the control that opened it. + background: Rectangle { + objectName: "omamail-combobox-background" + radius: Style.cornerRadius + color: control.pressed ? Style.pressedFillFor(control.semanticForeground, control.semanticAccent) + : control.popup.visible ? Style.selectedFillFor(control.semanticForeground, control.semanticAccent) + : control.visualFocus ? Style.focusFillFor(control.semanticForeground, control.semanticAccent) + : control.hovered ? Style.hoverFillFor(control.semanticForeground, control.semanticAccent) + : Style.normalFillFor(control.semanticForeground, control.semanticAccent) + border.width: Style.normalBorderWidth + border.color: control.visualFocus || control.hovered + ? Style.hoverBorderFor(control.semanticForeground, control.semanticAccent) + : Style.normalBorderFor(control.semanticForeground, control.semanticAccent) + } + + popup: T.Popup { + readonly property real below: control.mapToItem(null, 0, control.height).y + readonly property real windowHeight: control.Window.window ? control.Window.window.height : below + implicitHeight + // Below the trigger when it fits, above it when it does not, then kept + // inside the window. + y: below + implicitHeight <= windowHeight ? control.height + 2 + : Math.max(-control.mapToItem(null, 0, 0).y, -implicitHeight - 2) + width: control.width + implicitHeight: Math.min(contentItem.implicitHeight + topPadding + bottomPadding, + Style.spacing.popupRowHeight * 8 + topPadding + bottomPadding) + padding: 1 + + contentItem: ListView { + clip: true + implicitHeight: contentHeight + model: control.delegateModel + currentIndex: control.highlightedIndex + boundsBehavior: Flickable.StopAtBounds + } + + background: Rectangle { + color: Color.popups.background + border.width: 1 + border.color: Color.popups.border + radius: Style.cornerRadius + } + } +} diff --git a/app/qml/styles/Omamail/qmldir b/app/qml/styles/Omamail/qmldir index deec378..0df3117 100644 --- a/app/qml/styles/Omamail/qmldir +++ b/app/qml/styles/Omamail/qmldir @@ -7,3 +7,5 @@ Switch 2.0 Switch.qml Switch 6.0 Switch.qml ToolTip 2.0 ToolTip.qml ToolTip 6.0 ToolTip.qml +ComboBox 2.0 ComboBox.qml +ComboBox 6.0 ComboBox.qml diff --git a/app/tests/qml/tst_standalone_composition.qml b/app/tests/qml/tst_standalone_composition.qml index bfb3fda..61a05d2 100644 --- a/app/tests/qml/tst_standalone_composition.qml +++ b/app/tests/qml/tst_standalone_composition.qml @@ -170,40 +170,33 @@ TestCase { var settings = createTemporaryObject(calendarComponent, testCase) verify(settings) wait(0) + // A switch like every other setting on the page, and its input is the + // only thing that answers the pointer and the keyboard. var trigger = findChild(settings, "calendar-source-toggle") verify(trigger) - var input = findChild(trigger, "button-input") - var graphic = findChild(trigger, "toggle-switch-input") - var ring = findChild(trigger, "toggle-switch-cursor-ring") - verify(input && graphic && ring) - compare(graphic.enabled, false) - compare(graphic.focusPolicy, Qt.NoFocus) - var position = trigger.mapToItem(testCase, trigger.width / 2, trigger.height / 2) + var input = findChild(trigger, "toggle-switch-input") + verify(input) + compare(trigger.checked, true) + var position = input.mapToItem(testCase, input.width / 2, input.height / 2) verify(position.x >= 0 && position.x < testCase.width && position.y >= 0 && position.y < testCase.height, "toggle location: " + position) - verify(trigger.visible && trigger.enabled && input.visible && input.enabled, - "trigger visible/enabled: " + trigger.visible + "/" + trigger.enabled - + ", input: " + input.visible + "/" + input.enabled) - mouseClick(trigger, trigger.width / 2, trigger.height / 2) + verify(input.visible && input.enabled, "input visible/enabled: " + input.visible + "/" + input.enabled) + mouseClick(input, input.width / 2, input.height / 2) compare(calendarFixture.toggleCalls, 1) compare(calendarFixture.enabledValue, false) wait(0) trigger = findChild(settings, "calendar-source-toggle") - input = findChild(trigger, "button-input") - ring = findChild(trigger, "toggle-switch-cursor-ring") + input = findChild(trigger, "toggle-switch-input") + compare(trigger.checked, false) focusParking.forceActiveFocus() for (var tab = 0; tab < 20 && !input.activeFocus; tab++) keyClick(Qt.Key_Tab) - verify(input.activeFocus, "the wrapper, not the decorative switch, receives Tab") - verify(trigger.hot) - verify(ring.visible, "keyboard focus keeps the switch's cursor ring visible") + verify(input.activeFocus, "the visibility switch receives Tab") keyClick(Qt.Key_Space) compare(calendarFixture.toggleCalls, 2) compare(calendarFixture.enabledValue, true) wait(0) trigger = findChild(settings, "calendar-source-toggle") - graphic = findChild(trigger, "toggle-switch-input") compare(trigger.checked, true) - compare(graphic.checked, true) } function test_standalone_controls_use_semantic_omamail_style() { diff --git a/backend-api.json b/backend-api.json index df3049f..164b1fd 100644 --- a/backend-api.json +++ b/backend-api.json @@ -95,6 +95,8 @@ "public.unsubscribe", "calendar.request", "calendar.discover", + "calendar.attendance", + "calendar.reminders", "auth.form", "auth.begin", "auth.poll", @@ -231,6 +233,50 @@ "params": {"provider": "imap", "operation": "query", "mailbox": "all"}, "equals": {"value": "search:ALL"} }, + { + "name": "Reminder view cache has an independent namespace", + "method": "cache.calendarRead", + "params": {"name":"calendar-reminders"}, + "equals": {"version":3}, + "types": {"ranges":"object"} + }, + { + "name": "Reminder actions validate before opening the ledger", + "method": "calendar.reminders", + "params": {"operation":"dismiss","now":1,"key":"../outside"}, + "errorCode": -32602 + }, + { + "name": "Simultaneous reminders retain each event identity", + "method": "calendar.reminders", + "params": { + "operation": "poll", "now": 1400000, "lastCheck": 1300000, + "candidates": [ + {"key":"contract-one","occurrence":"contract-one","eventId":"one","sourceId":"calendar","accountId":"synthetic","title":"First meeting","start":2000000,"end":5600000,"due":1400000}, + {"key":"contract-two","occurrence":"contract-two","eventId":"two","sourceId":"calendar","accountId":"synthetic","title":"Second meeting","start":2000000,"end":5600000,"due":1400000} + ] + }, + "equals": {"notifications.length":2,"notifications.0.eventId":"one","notifications.1.eventId":"two","notifications.1.title":"Second meeting"}, + "types": {"notifications.0.key":"string","notifications.1.key":"string"} + }, + { + "name": "Google attendance rejects unsupported answers before authentication", + "method": "calendar.attendance", + "params": {"accountId":"missing@example.org","uid":"invite","organizer":"organizer@example.org","response":"yes"}, + "errorCode": -32602 + }, + { + "name": "Google attendance requires the invitation organizer before authentication", + "method": "calendar.attendance", + "params": {"accountId":"missing@example.org","uid":"invite","response":"accepted"}, + "errorCode": -32602 + }, + { + "name": "Google calendar identity is validated before authentication", + "method": "calendar.request", + "params": {"source":{"kind":"google","accountId":"missing@example.org","calendarId":".."},"operation":"get","eventId":"event"}, + "errorCode": -32000 + }, { "name": "iCloud request refuses an external credential origin", "method": "calendar.request", @@ -810,7 +856,7 @@ } ], "unreleased": { - "methods": [], - "cases": ["IMAP All mail resolves to account-wide listing", "IMAP text search includes archived mail", "Outlook text search includes archived mail", "IMAP address search includes archived mail", "IMAP account search refuses an expired work continuation", "IMAP account search refuses a malformed page cursor"] + "methods": ["calendar.attendance", "calendar.reminders"], + "cases": ["IMAP All mail resolves to account-wide listing", "IMAP text search includes archived mail", "Outlook text search includes archived mail", "IMAP address search includes archived mail", "IMAP account search refuses an expired work continuation", "IMAP account search refuses a malformed page cursor", "Google calendar identity is validated before authentication", "Google attendance rejects unsupported answers before authentication", "Google attendance requires the invitation organizer before authentication", "Reminder actions validate before opening the ledger", "Reminder view cache has an independent namespace", "Simultaneous reminders retain each event identity"] } } diff --git a/docs/KEYS.md b/docs/KEYS.md index 6d99e81..202a8fd 100644 --- a/docs/KEYS.md +++ b/docs/KEYS.md @@ -41,6 +41,7 @@ readonly property string keyContext: | `reader` | A message open | The mailbox keys, plus reply/forward and zoom. `j`/`k` move the mailbox cursor and immediately open its message; `Shift+J`/`Shift+K` scroll the message body | | `search` | A query being typed | `Escape`, and the modified keys | | `compose` | A draft being written | `Escape`, `Ctrl+Return`, and the modified keys | +| `eventCompose` | Creating or editing an event | `Enter` saves and closes after success; `Escape` closes; modified keys remain available | | `assistant` | Typing or reading in the AI dock | `Return`/`Enter` sends, `Escape`, and the modified keys | | `assistantCommands` | Choosing an AI slash command | `Up`, `Down`, `Return`, `Enter`, `Escape`, and the modified keys | | `page` | Setup or settings | `Escape`, and the modified keys | @@ -79,7 +80,7 @@ event is left alone, preserving normal typing, IME input and line breaks. context. **A text-entry context binds no bare key but `Escape`, except AI send and command -selection described above.** +selection described above and Enter to save in the single-line event editor.** There is no "is the user typing" question anywhere in the code, because there is nothing left for it to answer: if a bare letter is not bound in `compose`, it cannot fire there, and the field gets it the way any other character arrives. @@ -147,8 +148,15 @@ used to exist, and they had. | `calendarNextPeriod` | `l`, `Right` | calendar | Next week or month | | `calendarToday` | `t` | calendar | Go to today | | `calendarWeek` | `w` | calendar | Show week view | +| `calendarDay` | `d` | calendar | Show day view | +| `calendarAgenda` | `a` | calendar | Show agenda view | +| `calendarUndo` | `u` | calendar | Undo the last event change | | `calendarMonth` | `m` | calendar | Show month view | | `send` | `Ctrl+Return`, `Ctrl+Enter` | compose | Send | +| `saveEvent` | `Return`, `Enter`, `Ctrl+Return`, `Ctrl+Enter` | eventCompose | Save and close the event | +| `guestNext` | `Down` | eventGuests | Next guest suggestion | +| `guestPrevious` | `Up` | eventGuests | Previous guest suggestion | +| `guestChoose` | `Return`, `Enter` | eventGuests | Choose guest suggestion | | `undoSend` | `Alt+Z` | all | Undo send | | `search` | `/` | mail | Search | | `goMailbox` | `Ctrl+1`, `Ctrl+2`, `Ctrl+3`, `Ctrl+4`, `Ctrl+5`, `Ctrl+6`, `Ctrl+7`, `Ctrl+8`, `Ctrl+9` | mail | Go to that mailbox | @@ -185,6 +193,8 @@ The delayed-send toast does not create a keyboard context. The current screen ke Back and `Escape` close an untouched composition immediately without saving, including a prefilled reply, forward, or existing provider draft. After a user edit, they open a modal with Cancel, Discard, and Save draft. Save draft initially has focus; Tab and Shift+Tab cycle through the buttons, and Enter activates the focused choice. Escape inside the popup cancels and returns to composing. A failed save restores the changed draft. The composer's bottom Discard button exits immediately. +The event and label delete confirmation initially focuses Delete. Tab and Shift+Tab cycle between Delete and Cancel; Return or Enter activates the focused button. Escape cancels. + ## Why the rail is numbered and not chorded `g i`, `g s`, `g u` and `g t` used to open the mailboxes, and they were two diff --git a/manifest.json b/manifest.json index d257b0b..d450571 100644 --- a/manifest.json +++ b/manifest.json @@ -46,6 +46,8 @@ "oauthPort": 9481, "undoSendSeconds": 10, "unifiedCalendarView": false, + "calendarRemindersEnabled": true, + "calendarSnoozeMinutes": 5, "openOnClick": "Window", "showBarIcon": true, "suggestEvents": false @@ -152,6 +154,23 @@ "defaultValue": false, "description": "Show calendars from every connected account instead of following the current mailbox." }, + { + "key": "calendarRemindersEnabled", + "type": "boolean", + "label": "Calendar desktop reminders", + "defaultValue": true, + "description": "Show reminders while Omamail is running. Configure calendars and timing inside Calendar settings." + }, + { + "key": "calendarSnoozeMinutes", + "type": "integer", + "label": "Calendar snooze minutes", + "min": 1, + "max": 1440, + "step": 1, + "defaultValue": 5, + "description": "How long to snooze a calendar desktop reminder." + }, { "key": "openOnClick", "type": "enum", diff --git a/scripts/diagnostics.py b/scripts/diagnostics.py index ebbfee4..4caf165 100644 --- a/scripts/diagnostics.py +++ b/scripts/diagnostics.py @@ -34,6 +34,9 @@ auth_random_failed auth_redirect_refused auth_refresh_failed auth_response_too_large auth_secret_invalid auth_signed_out auth_timeout auth_too_many_accounts auth_too_many_flows auth_transport_failed calendar_auth_refused calendar_auth_required calendar_input_too_large +calendar_ambiguous_invitation calendar_attendance_unconfirmed calendar_attendee_not_found +calendar_conflict calendar_invitation_cancelled calendar_invitation_not_found calendar_not_found calendar_organizer_mismatch +calendar_reminder_not_found calendar_reminders_invalid calendar_reminders_unavailable calendar_too_many_reminders calendar_invalid_input calendar_invalid_operation calendar_invalid_response calendar_invalid_url calendar_keyring_failed calendar_network_failed calendar_origin_refused calendar_password_invalid calendar_password_missing calendar_provider_unsupported calendar_request_failed diff --git a/scripts/notify-mail.py b/scripts/notify-mail.py index 1a5bb6a..8bd0ed8 100644 --- a/scripts/notify-mail.py +++ b/scripts/notify-mail.py @@ -17,6 +17,9 @@ def paint(element, color): def main(args): + calendar = bool(args and args[0] == '--calendar') + if calendar: + args = args[1:] if (len(args) != 5 or args[2] != '--' or any(not re.fullmatch(r'#[0-9a-fA-F]{6}(?:[0-9a-fA-F]{2})?', c) for c in args[:2])): @@ -45,8 +48,10 @@ def main(args): # at the last boundary so native notification APIs still receive plain text. title = escape(title, quote=False) body = escape(body, quote=False) - os.execvp('notify-send', ['notify-send', '-a', 'Omamail', '-i', str(path), - '--action=default=Read...', '--', title, body]) + actions = (['--action=default=Open event...', '--action=snooze=Snooze', '--action=dismiss=Dismiss'] + if calendar else ['--action=default=Read...']) + os.execvp('notify-send', ['notify-send', '-a', 'Omamail', '-i', str(path)] + + actions + ['--', title, body]) if __name__ == '__main__': diff --git a/src/auth/callback.rs b/src/auth/callback.rs index 9e88669..42acd96 100644 --- a/src/auth/callback.rs +++ b/src/auth/callback.rs @@ -147,6 +147,9 @@ async fn finish_google(mut response: Value, client_id: &str) -> Result Some( self.gmail @@ -334,7 +335,51 @@ impl Session { }; return Box::pin(crate::calendar::call(params, token.as_deref())).await; } + if method == "calendar.attendance" { + crate::calendar::attendance::validate(params)?; + let token = self + .gmail + .access_token(params["accountId"].as_str().ok_or("invalid_params")?) + .await?; + let account = params["accountId"].as_str().ok_or("invalid_params")?; + let mut addresses = vec![account.to_owned()]; + if let Ok(aliases) = self + .gmail + .call("gmail.sendAs", &json!({"accountId":account})) + .await + { + for alias in aliases.as_array().into_iter().flatten() { + if let Some(email) = alias["email"].as_str().filter(|email| { + !email.is_empty() + && email.len() <= 1024 + && !email.chars().any(char::is_control) + }) { + addresses.push(email.to_owned()); + } + } + } + return crate::calendar::attendance::google(params, &token, &addresses).await; + } + if method == "calendar.reminders" { + let params = params.clone(); + return tokio::task::spawn_blocking(move || crate::calendar::reminders::call(¶ms)) + .await + .map_err(|_| "calendar_reminders_unavailable")?; + } if method == "calendar.discover" { + if let Some(account) = params["accountId"] + .as_str() + .filter(|id| id.contains('@') && !id.contains(':')) + { + if params.as_object().is_none_or(|fields| fields.len() != 1) + || account.len() > 1024 + || account.chars().any(|c| c.is_control() || c.is_whitespace()) + { + return Err("invalid_params"); + } + let token = self.gmail.access_token(account).await?; + return crate::calendar::discover_google(account, &token).await; + } return Box::pin(crate::calendar::discover(params)).await; } if method == "cache.bodyPutUpload" { diff --git a/src/cache/store.rs b/src/cache/store.rs index da59353..1545055 100644 --- a/src/cache/store.rs +++ b/src/cache/store.rs @@ -50,7 +50,7 @@ pub(super) fn call_at(root: &Path, method: &str, params: &Value) -> Result Result<(), &'static str> { + match event["organizer"]["email"].as_str() { + Some(email) if email.eq_ignore_ascii_case(organizer) => Ok(()), + _ => Err("calendar_organizer_mismatch"), + } +} + +fn own_attendee<'a>(event: &'a Value, addresses: &[String]) -> Result<&'a Value, &'static str> { + let mut matches = event["attendees"] + .as_array() + .into_iter() + .flatten() + .filter(|attendee| { + attendee["self"] == true + && attendee["email"].as_str().is_some_and(|email| { + addresses + .iter() + .any(|address| email.eq_ignore_ascii_case(address)) + }) + }); + let found = matches.next().ok_or("calendar_attendee_not_found")?; + if matches.next().is_some() { + return Err("calendar_ambiguous_invitation"); + } + Ok(found) +} + +fn choose<'a>( + items: &'a [Value], + uid: &str, + original: Option<&str>, +) -> Result<&'a Value, &'static str> { + let mut matches = items.iter().filter(|event| { + event["iCalUID"] == uid + && match original { + None => event.get("recurringEventId").is_none(), + Some(start) => { + event["originalStartTime"]["dateTime"] == start + || event["originalStartTime"]["date"] == start + || event["originalStartTime"]["dateTime"] + .as_str() + .zip(chrono::DateTime::parse_from_rfc3339(start).ok()) + .is_some_and(|(remote, expected)| { + chrono::DateTime::parse_from_rfc3339(remote).ok() == Some(expected) + }) + } + } + }); + let found = matches.next().ok_or("calendar_invitation_not_found")?; + if matches.next().is_some() { + return Err("calendar_ambiguous_invitation"); + } + Ok(found) +} + +async fn request( + source: &Value, + operation: &str, + fields: Value, + token: &str, +) -> Result { + let mut params = fields; + params["source"] = source.clone(); + params["operation"] = json!(operation); + let result = super::call(¶ms, Some(token)).await?; + serde_json::from_str(result["body"].as_str().ok_or("calendar_invalid_response")?) + .map_err(|_| "calendar_invalid_response") +} + +pub fn validate(params: &Value) -> Result<(), &'static str> { + let fields = params.as_object().ok_or("invalid_params")?; + if fields + .keys() + .any(|key| { + !["accountId", "uid", "organizer", "originalStart", "response"].contains(&key.as_str()) + }) + { + return Err("invalid_params"); + } + let account = super::text(params, "accountId")?; + if !account.contains('@') || account.contains(':') || account.chars().any(char::is_whitespace) { + return Err("invalid_params"); + } + super::text(params, "uid")?; + let organizer = super::text(params, "organizer").map_err(|_| "invalid_params")?; + if !organizer.contains('@') || organizer.chars().any(char::is_whitespace) { + return Err("invalid_params"); + } + if params.get("originalStart").is_some() { + let original = super::text(params, "originalStart")?; + if chrono::DateTime::parse_from_rfc3339(original).is_err() + && chrono::NaiveDate::parse_from_str(original, "%Y-%m-%d").is_err() + { + return Err("invalid_params"); + } + } + if !matches!( + params["response"].as_str(), + None | Some("accepted" | "tentative" | "declined") + ) { + return Err("invalid_params"); + } + if fields + .get("response") + .is_some_and(|value| !value.is_string()) + { + return Err("invalid_params"); + } + Ok(()) +} + +pub async fn google( + params: &Value, + token: &str, + addresses: &[String], +) -> Result { + tokio::time::timeout( + std::time::Duration::from_secs(27), + google_inner(params, token, addresses), + ) + .await + .map_err(|_| "calendar_timeout")? +} + +async fn google_inner( + params: &Value, + token: &str, + addresses: &[String], +) -> Result { + validate(params)?; + let account = super::text(params, "accountId")?; + let uid = super::text(params, "uid")?; + let organizer = super::text(params, "organizer")?; + let source = json!({"kind":"google", "accountId":account, "calendarId":"primary"}); + let listing = request(&source, "lookup", json!({"uid":uid}), token).await?; + let mut items = listing["items"] + .as_array() + .cloned() + .ok_or("calendar_invalid_response")?; + let original = params["originalStart"].as_str(); + if let Some(start) = original { + let parents: Vec = items + .iter() + .filter(|event| event["iCalUID"] == uid && event["recurrence"].is_array()) + .filter_map(|event| event["id"].as_str().map(str::to_owned)) + .collect(); + if parents.len() > 1 { + return Err("calendar_ambiguous_invitation"); + } + if let Some(parent) = parents.first() { + let instances = request( + &source, + "instances", + json!({"eventId":parent,"originalStart":start}), + token, + ) + .await?; + items = instances["items"] + .as_array() + .cloned() + .ok_or("calendar_invalid_response")?; + } + } + let event = choose(&items, uid, original)?; + same_organizer(event, organizer)?; + if event["status"] == "cancelled" { + if params.get("response").is_some() { + return Err("calendar_invitation_cancelled"); + } + return Ok(json!({"event":event,"response":"","cancelled":true})); + } + // Primary-calendar self is additionally checked against the signed-in + // account or its Gmail-verified send-as identities. A sender cannot + // nominate an arbitrary attendee to modify. + let own = own_attendee(event, addresses)?; + let answering_as = super::text(own, "email")?; + let id = super::text(event, "id")?; + let result = if let Some(response) = params["response"].as_str() { + let etag = super::text(event, "etag")?; + request(&source, "update", json!({"eventId":id,"ifMatch":etag,"sendUpdates":"all", + "body":json!({"attendeesOmitted":true,"attendees":[{"email":answering_as,"responseStatus":response}]}).to_string()}), token).await?; + // Only a read-back confirms success, including propagation policies + // which can reset an attendee to needsAction after a successful PATCH. + request(&source, "get", json!({"eventId":id}), token).await? + } else { + event.clone() + }; + same_organizer(&result, organizer)?; + let attendee = own_attendee(&result, addresses)?; + if let Some(expected) = params["response"].as_str() { + if attendee["responseStatus"] != expected { + return Err("calendar_attendance_unconfirmed"); + } + } + Ok(json!({"event":result,"response":attendee["responseStatus"]})) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn matching_never_uses_moved_start_or_another_attendee() { + let event = json!({"iCalUID":"series","id":"instance","recurringEventId":"parent", + "originalStartTime":{"dateTime":"2026-10-01T10:00:00+02:00"}, + "start":{"dateTime":"2026-10-02T08:00:00Z"}, + "attendees":[{"self":true,"email":"owner@example.org"}]}); + let items = vec![event.clone()]; + assert!(choose(&items, "series", Some("2026-10-01T08:00:00Z")).is_ok()); + assert!(choose(&items, "series", Some("2026-10-02T08:00:00Z")).is_err()); + assert!(choose(&items, "series", None).is_err()); + assert!(own_attendee(&event, &["attacker@example.org".into()]).is_err()); + assert!( + own_attendee( + &event, + &["primary@example.org".into(), "owner@example.org".into()] + ) + .is_ok() + ); + assert!( + choose( + &[event.clone(), event], + "series", + Some("2026-10-01T08:00:00Z") + ) + .is_err() + ); + } + + #[test] + fn an_invitation_reusing_a_uid_is_not_another_organizers_event() { + let event = json!({"iCalUID":"meeting","organizer":{"email":"Boss@Example.org"}}); + assert!(same_organizer(&event, "boss@example.org").is_ok()); + assert_eq!( + same_organizer(&event, "attacker@example.net"), + Err("calendar_organizer_mismatch") + ); + assert_eq!( + same_organizer(&json!({"iCalUID":"meeting"}), "boss@example.org"), + Err("calendar_organizer_mismatch") + ); + } + + #[test] + fn attendance_requires_the_invitation_organizer() { + let base = json!({"accountId":"me@example.org","uid":"meeting","response":"accepted"}); + assert_eq!(validate(&base), Err("invalid_params")); + for organizer in ["", "boss", "boss @example.org", "boss@example.org\n"] { + let mut params = base.clone(); + params["organizer"] = json!(organizer); + assert!(validate(¶ms).is_err(), "{organizer:?}"); + } + let mut params = base; + params["organizer"] = json!("boss@example.org"); + assert!(validate(¶ms).is_ok()); + } +} diff --git a/src/calendar/discovery.rs b/src/calendar/discovery.rs index 0b7613a..cee8d80 100644 --- a/src/calendar/discovery.rs +++ b/src/calendar/discovery.rs @@ -43,8 +43,8 @@ fn bounded_text(value: &Value, key: &str) -> Option { } fn source_id(provider: &str, account: &str, remote: &str, is_default: bool) -> String { - if provider == "microsoft" && is_default { - return format!("microsoft:{account}"); + if matches!(provider, "microsoft" | "google") && is_default { + return format!("{provider}:{account}"); } let mut digest = Sha256::new(); digest.update(provider.as_bytes()); @@ -55,7 +55,7 @@ fn source_id(provider: &str, account: &str, remote: &str, is_default: bool) -> S format!("{provider}:{account}:{:x}", digest.finalize()) } -async fn response_body(mut response: Response) -> Result { +pub(super) async fn response_body(mut response: Response) -> Result { if response .content_length() .is_some_and(|size| size > DISCOVERY_LIMIT as u64) @@ -82,6 +82,105 @@ async fn microsoft(account: &str) -> Result { microsoft_with_client(super::client()?, account, &token).await } +pub async fn google(account: &str, token: &str) -> Result { + if account.is_empty() + || account.contains(':') + || !account.contains('@') + || account.len() > 1024 + || account.chars().any(char::is_whitespace) + || account.chars().any(char::is_control) + { + return Err("invalid_params"); + } + tokio::time::timeout( + std::time::Duration::from_secs(27), + google_pages(account, token), + ) + .await + .map_err(|_| "calendar_timeout")? +} + +fn google_calendar(account: &str, value: &Value) -> Result { + let id = bounded_text(value, "id").ok_or("calendar_invalid_response")?; + if value["id"].as_str() != Some(id.as_str()) || matches!(id.as_str(), "." | "..") { + return Err("calendar_invalid_response"); + } + let primary = value["primary"] == true; + let role = bounded_text(value, "accessRole").unwrap_or_default(); + let name = bounded_text(value, "summaryOverride") + .or_else(|| bounded_text(value, "summary")) + .unwrap_or_else(|| id.clone()); + Ok(json!({ + "sourceId":source_id("google", account, &id, primary), + "calendarId":id,"name":name,"isDefault":primary, + "readOnly":!matches!(role.as_str(), "owner" | "writer"), + "accessRole":role,"timeZone":bounded_text(value, "timeZone").unwrap_or_default(), + "selected":value["selected"] == true,"hidden":value["hidden"] == true, + "defaultReminders":value["defaultReminders"].as_array().cloned().unwrap_or_default(), + "canCreateMeet":value["conferenceProperties"]["allowedConferenceSolutionTypes"] + .as_array().is_some_and(|types| types.iter().any(|kind| kind == "hangoutsMeet")) + })) +} + +async fn google_pages(account: &str, token: &str) -> Result { + let origin = + Url::parse("https://www.googleapis.com/calendar/v3/users/me/calendarList").unwrap(); + let mut page_token = String::new(); + let mut calendars = Vec::new(); + let mut bytes = 0; + let mut seen = std::collections::HashSet::new(); + for _ in 0..100 { + let mut url = origin.clone(); + url.query_pairs_mut() + .extend_pairs([("showHidden", "true"), ("maxResults", "250")]); + if !page_token.is_empty() { + url.query_pairs_mut().append_pair("pageToken", &page_token); + } + let response = super::client()? + .get(url) + .bearer_auth(token) + .send() + .await + .map_err(|_| "calendar_network_failed")?; + if matches!(response.status().as_u16(), 401 | 403) { + return Err("calendar_auth_refused"); + } + if !response.status().is_success() { + return Err("calendar_request_failed"); + } + let body = response_body(response).await?; + bytes += body.len(); + if bytes > DISCOVERY_LIMIT { + return Err("calendar_response_too_large"); + } + let payload: Value = + serde_json::from_str(&body).map_err(|_| "calendar_invalid_response")?; + for value in payload["items"] + .as_array() + .ok_or("calendar_invalid_response")? + { + if value["deleted"] == true { + continue; + } + let item = google_calendar(account, value)?; + if seen.insert(item["calendarId"].as_str().unwrap().to_owned()) { + calendars.push(item); + } + if calendars.len() > MAX_CALENDARS { + return Err("calendar_too_many_calendars"); + } + } + match bounded_text(&payload, "nextPageToken") { + Some(next) if next != page_token => page_token = next, + None if payload.get("nextPageToken").is_none() => { + return Ok(json!({"provider":"google","accountId":account,"calendars":calendars})); + } + _ => return Err("calendar_invalid_response"), + } + } + Err("calendar_too_many_pages") +} + async fn microsoft_with_client( client: &reqwest::Client, account: &str, @@ -514,6 +613,42 @@ pub async fn discover(params: &Value) -> Result { mod tests { use super::*; + #[test] + fn google_projection_keeps_hidden_permissions_and_refuses_noncanonical_ids() { + let source = google_calendar( + "me@example.org", + &json!({"id":"team@example.org","summary":"Team", + "accessRole":"reader","hidden":true,"timeZone":"Europe/Paris", + "defaultReminders":[{"method":"popup","minutes":10}], + "conferenceProperties":{"allowedConferenceSolutionTypes":["hangoutsMeet"]}}), + ) + .unwrap(); + assert_eq!(source["selected"], false); + assert_eq!(source["hidden"], true); + assert_eq!(source["readOnly"], true); + assert_eq!(source["timeZone"], "Europe/Paris"); + assert_eq!(source["defaultReminders"][0]["minutes"], 10); + assert_eq!(source["canCreateMeet"], true); + for id in [ + "..", + ".", + " leading", + "trailing ", + "trailing\n", + "nul\0", + "cr\r", + ] { + assert!( + google_calendar("me@example.org", &json!({"id":id})).is_err(), + "{id:?}" + ); + } + assert_ne!( + source["sourceId"], + google_calendar("other@example.org", &json!({"id":"team@example.org"})).unwrap()["sourceId"] + ); + } + #[test] fn discovery_accepts_only_one_supported_account() { assert_eq!( diff --git a/src/calendar/mod.rs b/src/calendar/mod.rs index 18903b8..4bf97d0 100644 --- a/src/calendar/mod.rs +++ b/src/calendar/mod.rs @@ -3,8 +3,11 @@ use reqwest::{Client, Method, Url}; use serde_json::{Value, json}; use std::{sync::OnceLock, time::Duration}; +pub mod attendance; mod discovery; +pub mod reminders; pub use discovery::discover; +pub use discovery::google as discover_google; const LIMIT: usize = 16 * 1024 * 1024; static CLIENT: OnceLock> = OnceLock::new(); @@ -85,6 +88,7 @@ struct Request { source_id: String, username: String, account_id: String, + if_match: Option, } fn prepare(params: &Value) -> Result { @@ -92,8 +96,8 @@ fn prepare(params: &Value) -> Result { let kind = text(source, "kind")?; let op = text(params, "operation")?; let method = match op { - "list" => Method::GET, - "create" => Method::POST, + "list" | "get" | "lookup" | "instances" => Method::GET, + "create" | "move" => Method::POST, "update" => Method::PATCH, "delete" => Method::DELETE, _ => return Err("calendar_invalid_operation"), @@ -110,9 +114,36 @@ fn prepare(params: &Value) -> Result { source_id: String::new(), username: String::new(), account_id: String::new(), + if_match: params + .get("ifMatch") + .map(|_| text(params, "ifMatch").map(str::to_owned)) + .transpose()?, }; match kind { "google" | "microsoft" => { + if kind == "google" { + let calendar_id = source["calendarId"] + .as_str() + .filter(|id| !id.is_empty()) + .unwrap_or("primary"); + if calendar_id == "." + || calendar_id == ".." + || calendar_id.len() > 8192 + || calendar_id.chars().any(char::is_control) + { + return Err("calendar_invalid_input"); + } + request.url = + Url::parse("https://www.googleapis.com/calendar/v3/calendars").unwrap(); + request + .url + .path_segments_mut() + .unwrap() + .push(calendar_id) + .push("events"); + } else if !matches!(op, "list" | "create" | "update" | "delete") { + return Err("calendar_invalid_operation"); + } if kind == "microsoft" { // Legacy/default sources serialize an empty identity. They // still address /me/calendarView until discovery names one. @@ -149,13 +180,58 @@ fn prepare(params: &Value) -> Result { .unwrap(); } } - if op == "update" || op == "delete" { + if matches!(op, "get" | "update" | "delete" | "instances" | "move") { let id = text(params, "eventId")?; if id == "." || id == ".." { return Err("calendar_invalid_input"); } request.url.path_segments_mut().unwrap().push(id); } + if op == "instances" { + request.url.path_segments_mut().unwrap().push("instances"); + request + .url + .query_pairs_mut() + .append_pair("showDeleted", "true"); + if params.get("originalStart").is_some() { + request + .url + .query_pairs_mut() + .append_pair("originalStart", text(params, "originalStart")?); + } + } + if op == "lookup" { + request.url.query_pairs_mut().extend_pairs([ + ("iCalUID", text(params, "uid")?), + ("showHiddenInvitations", "true"), + ("showDeleted", "true"), + ("maxResults", "2500"), + ]); + } + if op == "move" { + request.url.path_segments_mut().unwrap().push("move"); + request + .url + .query_pairs_mut() + .append_pair("destination", text(params, "destination")?); + } + if kind == "google" && matches!(op, "create" | "update" | "move" | "delete") { + if let Some(updates) = params["sendUpdates"].as_str() { + if !["all", "externalOnly", "none"].contains(&updates) { + return Err("calendar_invalid_input"); + } + request + .url + .query_pairs_mut() + .append_pair("sendUpdates", updates); + } + if matches!(op, "create" | "update") { + request + .url + .query_pairs_mut() + .append_pair("conferenceDataVersion", "1"); + } + } if op == "list" { let start = text(params, "start")?; let end = text(params, "end")?; @@ -186,6 +262,9 @@ fn prepare(params: &Value) -> Result { } } "caldav" | "icloud" => { + if !matches!(op, "list" | "create" | "update" | "delete") { + return Err("calendar_invalid_operation"); + } let base = if kind == "icloud" { request.account_id = text(source, "accountId")?.into(); discovery::icloud_url(text(source, "url")?)? @@ -210,6 +289,10 @@ fn prepare(params: &Value) -> Result { Ok(request) } +pub fn validate(params: &Value) -> Result<(), &'static str> { + prepare(params).map(|_| ()) +} + /// OAuth tokens remain inside Rust; CalDAV credentials are loaded only after /// validating the exact destination, and redirects are never followed. pub async fn call(params: &Value, token: Option<&str>) -> Result { @@ -258,8 +341,10 @@ where } else { None }; - let paginated = - params["operation"] == "list" && !matches!(request.kind.as_str(), "caldav" | "icloud"); + let paginated = matches!( + params["operation"].as_str(), + Some("list" | "lookup" | "instances") + ) && !matches!(request.kind.as_str(), "caldav" | "icloud"); let origin = request.url.clone(); let mut result = execute( client()?, @@ -375,6 +460,14 @@ async fn execute( password: Option<&str>, ) -> Result { let mut builder = client.request(request.method.clone(), request.url); + // Google's empty-body POST endpoints (events.move) require an explicit + // length. reqwest/hyper may otherwise omit framing for a zero-byte body. + if request.method == Method::POST && request.body.is_empty() { + builder = builder.header(reqwest::header::CONTENT_LENGTH, "0"); + } + if let Some(etag) = request.if_match { + builder = builder.header("If-Match", etag); + } if matches!(request.kind.as_str(), "caldav" | "icloud") { builder = builder.basic_auth(request.username, password); if request.method.as_str() == "REPORT" { @@ -401,6 +494,12 @@ async fn execute( .await .map_err(|_| "calendar_network_failed")?; let status = response.status(); + if status.as_u16() == 412 { + return Err("calendar_conflict"); + } + if status.as_u16() == 404 { + return Err("calendar_not_found"); + } if status.as_u16() == 401 || status.as_u16() == 403 { return Err("calendar_auth_refused"); } diff --git a/src/calendar/reminders.rs b/src/calendar/reminders.rs new file mode 100644 index 0000000..09a3dbd --- /dev/null +++ b/src/calendar/reminders.rs @@ -0,0 +1,352 @@ +//! The reminder ledger is independent of the evictable view cache. A locked, +//! atomic claim is shared by shell and standalone instances on this machine. +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::{io::Read, path::Path}; + +const LIMIT: usize = 4 * 1024 * 1024; +type Result = std::result::Result; + +fn key(value: &str) -> String { + format!("{:x}", Sha256::digest(value.as_bytes())) +} + +fn validate(params: &Value) -> Result<()> { + let fields = params.as_object().ok_or("invalid_params")?; + if fields.keys().any(|field| { + ![ + "operation", + "candidates", + "now", + "lastCheck", + "key", + "minutes", + ] + .contains(&field.as_str()) + }) { + return Err("invalid_params"); + } + if !params["now"].as_i64().is_some_and(|now| now > 0) { + return Err("invalid_params"); + } + match params["operation"].as_str() { + Some("poll") => { + let candidates = params["candidates"].as_array().ok_or("invalid_params")?; + if candidates.len() > 5000 { + return Err("calendar_too_many_reminders"); + } + for candidate in candidates { + for field in [ + "key", + "occurrence", + "eventId", + "sourceId", + "title", + "accountId", + ] { + let text = candidate[field].as_str().ok_or("invalid_params")?; + if text.len() > 8192 || text.contains('\0') { + return Err("invalid_params"); + } + } + for field in ["start", "end", "due"] { + if !candidate[field].as_i64().is_some_and(|time| time > 0) { + return Err("invalid_params"); + } + } + if candidate["end"].as_i64() <= candidate["start"].as_i64() { + return Err("invalid_params"); + } + } + } + Some("snooze" | "dismiss" | "failed") => { + let id = params["key"].as_str().ok_or("invalid_params")?; + if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("invalid_params"); + } + if params["operation"] == "snooze" + && !params["minutes"] + .as_i64() + .is_some_and(|n| (1..=1440).contains(&n)) + { + return Err("invalid_params"); + } + } + _ => return Err("invalid_params"), + } + if serde_json::to_vec(params) + .map_err(|_| "invalid_params")? + .len() + > LIMIT + { + return Err("calendar_too_many_reminders"); + } + Ok(()) +} + +pub fn call(params: &Value) -> Result { + validate(params)?; + let root = crate::platform::dirs::AppDirs::discover()?.config; + call_at(&root, params) +} + +fn call_at(root: &Path, params: &Value) -> Result { + validate(params)?; + let dir = crate::cache::directories(root, &["omamail"], true)? + .ok_or("calendar_reminders_unavailable")?; + let _lock = match crate::platform::private_fs::lock_exclusive(&dir, ".calendar-reminders.lock") + { + Ok(lock) => lock, + Err("private_fs_busy") if params["operation"] == "poll" => { + return Ok(json!({"notifications":[],"retry":true})); + } + Err(error) => return Err(error), + }; + let mut bytes = Vec::new(); + if let Some(file) = crate::cache::regular(&dir, "calendar-reminders.json", false)? { + file.take(LIMIT as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|_| "calendar_reminders_unavailable")?; + } + if bytes.len() > LIMIT { + return Err("calendar_too_many_reminders"); + } + let mut ledger: Value = if bytes.is_empty() { + json!({}) + } else { + serde_json::from_slice(&bytes).map_err(|_| "calendar_reminders_invalid")? + }; + let entries = ledger.as_object_mut().ok_or("calendar_reminders_invalid")?; + let now = params["now"].as_i64().ok_or("invalid_params")?; + entries.retain(|_, entry| entry["end"].as_i64().unwrap_or(0).saturating_add(86400000) > now); + let mut notifications: Vec = Vec::new(); + if params["operation"] == "poll" { + let candidates = params["candidates"].as_array().ok_or("invalid_params")?; + let last_check = params["lastCheck"].as_i64().unwrap_or(0); + let mut caught_up = std::collections::HashSet::new(); + for candidate in candidates { + let id = key(candidate["key"].as_str().unwrap()); + let occurrence = key(candidate["occurrence"].as_str().unwrap()); + let start = candidate["start"].as_i64().unwrap(); + let end = candidate["end"].as_i64().unwrap(); + if end <= now { + continue; + } + let previous = entries.get(&id); + let pending = + previous.filter(|record| record["start"] == start && record["pending"] == true); + if previous.is_some_and(|record| record["start"] == start && record["pending"] != true) + { + continue; + } + let due = pending + .and_then(|record| record["due"].as_i64()) + .unwrap_or(candidate["due"].as_i64().unwrap()); + let on_time = + due <= now && now - due <= 60000 && (pending.is_some() || due > last_check); + let catch_up = due <= now && start <= now && now - start <= 600000; + if !on_time && !catch_up { + continue; + } + if !on_time + && catch_up + && (!caught_up.insert(occurrence.clone()) + || entries.values().any(|entry| { + entry["occurrence"] == occurrence + && entry["start"] == start + && entry["pending"] != true + })) + { + continue; + } + let mut record = candidate.clone(); + record["key"] = json!(id); + record["occurrence"] = json!(occurrence); + record["pending"] = json!(false); + entries.insert(id, record.clone()); + notifications.push(record); + } + } else { + let id = params["key"].as_str().unwrap(); + // One action owns one reminder, including entries from an older ledger + // that grouped unrelated events under relatedKeys. + let record = entries.get_mut(id).ok_or("calendar_reminder_not_found")?; + record["pending"] = json!(params["operation"] != "dismiss"); + if params["operation"] != "dismiss" { + let minutes = if params["operation"] == "failed" { + 1 + } else { + params["minutes"].as_i64().unwrap() + }; + record["due"] = json!(now.saturating_add(minutes * 60000)); + } + } + let bytes = serde_json::to_vec(&ledger).map_err(|_| "calendar_reminders_invalid")?; + if bytes.len() > LIMIT { + return Err("calendar_too_many_reminders"); + } + crate::platform::private_fs::atomic_replace(&dir, "calendar-reminders.json", &bytes)?; + Ok(json!({"notifications":notifications})) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fixture_root(name: &str) -> std::path::PathBuf { + // macOS exposes its temporary directory through /var, a symlink to + // /private/var. Resolve the trusted fixture parent before exercising + // the production no-symlink storage boundary. + let root = std::env::temp_dir() + .canonicalize() + .unwrap() + .join(format!("omamail-reminders-{name}-{}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + // CI may use a group-writable umask; the fixture itself must obey + // the same private-directory policy as the real config root. + std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); + } + root + } + + #[test] + fn simultaneous_reminders_keep_each_event_and_action_independent() { + let root = fixture_root("simultaneous"); + let candidates: Vec = (1..=2) + .map(|i| { + json!({ + "key":format!("event-{i}"), "occurrence":format!("event-{i}"), + "start":2000000, "end":5600000, "due":1400000, + "eventId":format!("event-{i}"), "sourceId":"calendar", + "accountId":"synthetic", "title":format!("Meeting {i}") + }) + }) + .collect(); + let mut poll = + json!({"operation":"poll","now":1400000,"lastCheck":1300000,"candidates":candidates}); + let result = call_at(&root, &poll).unwrap(); + let notices = result["notifications"].as_array().unwrap(); + assert_eq!(notices.len(), 2); + assert_eq!(notices[0]["eventId"], "event-1"); + assert_eq!(notices[1]["eventId"], "event-2"); + assert_eq!(notices[1]["title"], "Meeting 2"); + assert!( + call_at(&root, &poll).unwrap()["notifications"] + .as_array() + .unwrap() + .is_empty() + ); + + // An older ledger may still carry a bundled action target. It must not + // let dismissing one event overwrite the other event's later snooze. + let path = root.join("omamail/calendar-reminders.json"); + let mut ledger: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + let first = notices[0]["key"].as_str().unwrap(); + let second = notices[1]["key"].as_str().unwrap(); + ledger[first]["relatedKeys"] = json!([second]); + std::fs::write(&path, serde_json::to_vec(&ledger).unwrap()).unwrap(); + call_at( + &root, + &json!({"operation":"snooze","now":1400000,"key":second,"minutes":5}), + ) + .unwrap(); + call_at( + &root, + &json!({"operation":"dismiss","now":1400000,"key":first}), + ) + .unwrap(); + poll["now"] = json!(1700000); + let result = call_at(&root, &poll).unwrap(); + let notices = result["notifications"].as_array().unwrap(); + assert_eq!(notices.len(), 1); + assert_eq!(notices[0]["eventId"], "event-2"); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn claims_are_durable_and_snooze_never_replays_an_ended_event() { + let root = fixture_root("durable"); + let candidate = json!({"key":"occurrence\n10", "occurrence":"occurrence", "start":2000000, + "end":5600000,"due":1400000,"eventId":"event","sourceId":"calendar","accountId":"synthetic","title":"Planning"}); + let mut poll = + json!({"operation":"poll","now":1400000,"lastCheck":1300000,"candidates":[candidate]}); + let peer_root = root.clone(); + let peer_poll = poll.clone(); + let peer = std::thread::spawn(move || call_at(&peer_root, &peer_poll).unwrap()); + let local = call_at(&root, &poll).unwrap(); + let remote = peer.join().unwrap(); + assert_eq!( + local["notifications"].as_array().unwrap().len() + + remote["notifications"].as_array().unwrap().len(), + 1, + "concurrent shell and standalone claimers must not both deliver" + ); + let first = if local["notifications"].as_array().unwrap().is_empty() { + remote + } else { + local + }; + assert_eq!(first["notifications"].as_array().unwrap().len(), 1); + assert!( + call_at(&root, &poll).unwrap()["notifications"] + .as_array() + .unwrap() + .is_empty() + ); + let id = first["notifications"][0]["key"].clone(); + call_at( + &root, + &json!({"operation":"snooze","now":1400000,"key":id,"minutes":5}), + ) + .unwrap(); + poll["now"] = json!(1700000); + assert_eq!( + call_at(&root, &poll).unwrap()["notifications"] + .as_array() + .unwrap() + .len(), + 1 + ); + call_at( + &root, + &json!({"operation":"snooze","now":1700000,"key":id,"minutes":120}), + ) + .unwrap(); + poll["now"] = json!(8900000); + assert!( + call_at(&root, &poll).unwrap()["notifications"] + .as_array() + .unwrap() + .is_empty() + ); + let refused = root.join("not-created"); + assert!( + call_at( + &refused, + &json!({"operation":"dismiss","now":1,"key":"../escape"}) + ) + .is_err() + ); + assert!(!refused.exists()); + #[cfg(unix)] + { + let outside = root.join("outside"); + std::fs::write(&outside, b"private marker").unwrap(); + let ledger = root.join("omamail/calendar-reminders.json"); + std::fs::remove_file(&ledger).unwrap(); + std::os::unix::fs::symlink(&outside, &ledger).unwrap(); + assert!(call_at(&root, &poll).is_err()); + assert_eq!(std::fs::read(&outside).unwrap(), b"private marker"); + assert!( + std::fs::symlink_metadata(&ledger) + .unwrap() + .file_type() + .is_symlink() + ); + } + std::fs::remove_dir_all(&root).unwrap(); + } +} diff --git a/src/calendar/tests.rs b/src/calendar/tests.rs index 804cc83..01f724e 100644 --- a/src/calendar/tests.rs +++ b/src/calendar/tests.rs @@ -1,4 +1,37 @@ use super::*; + +#[test] +fn google_requests_keep_calendar_identity_and_preconditions() { + let request = prepare(&json!({"source":{"kind":"google","calendarId":"family/a?b@example.org"}, + "operation":"update","eventId":"instance/one","body":"{}","ifMatch":"\"revision\"","sendUpdates":"all"})).unwrap(); + assert_eq!(request.url.host_str(), Some("www.googleapis.com")); + assert_eq!( + decoded_path(&request.url), + vec![ + b"".to_vec(), + b"calendar".to_vec(), + b"v3".to_vec(), + b"calendars".to_vec(), + b"family/a?b@example.org".to_vec(), + b"events".to_vec(), + b"instance/one".to_vec() + ] + ); + assert_eq!(request.if_match.as_deref(), Some("\"revision\"")); + assert!( + request + .url + .query_pairs() + .any(|(k, v)| k == "conferenceDataVersion" && v == "1") + ); + assert!( + prepare( + &json!({"source":{"kind":"google","calendarId":".."},"operation":"get","eventId":"x"}) + ) + .is_err() + ); + assert!(prepare(&json!({"source":{"kind":"caldav"},"operation":"move"})).is_err()); +} use tokio::{ io::{AsyncReadExt, AsyncWriteExt}, net::TcpListener, @@ -209,6 +242,7 @@ async fn server(response: &'static str) -> (Url, tokio::task::JoinHandle fn local_request(url: Url) -> Request { Request { + if_match: None, url, method: Method::GET, body: String::new(), @@ -219,6 +253,47 @@ fn local_request(url: Url) -> Request { } } +#[tokio::test] +async fn google_mutation_keeps_revision_and_never_follows_redirect() { + let client = Client::builder() + .no_proxy() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(2)) + .build() + .unwrap(); + let target = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let response = Box::leak(format!("HTTP/1.1 307 Temporary Redirect\r\nLocation: http://{}/stolen\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", target.local_addr().unwrap()).into_boxed_str()); + let (url, task) = server(response).await; + let mut request = prepare(&json!({"source":{"kind":"google","calendarId":"shared@example.org"}, + "operation":"update","eventId":"event","body":"{\"summary\":\"synthetic\"}","ifMatch":"\"revision\"","sendUpdates":"none"})).unwrap(); + request.url = url; + assert!( + execute(&client, request, Some("synthetic-calendar-token"), None) + .await + .is_err() + ); + let bytes = String::from_utf8(task.await.unwrap()) + .unwrap() + .to_lowercase(); + assert!(bytes.starts_with("patch ")); + assert!(bytes.contains("if-match: \"revision\"")); + assert!(bytes.contains("authorization: bearer synthetic-calendar-token")); + assert!( + tokio::time::timeout(Duration::from_millis(100), target.accept()) + .await + .is_err() + ); + for suffix in ["\r", "\n", "\r\n", "\0"] { + assert!( + prepare( + &json!({"source":{"kind":"google"},"operation":"update","eventId":"event", + "body":"{}","ifMatch":format!("revision{suffix}")}) + ) + .is_err() + ); + } +} + #[tokio::test] async fn native_http_returns_body_and_refuses_redirects() { let client = Client::builder() @@ -271,6 +346,60 @@ async fn native_http_bounds_downloads() { task.await.unwrap(); } +#[tokio::test] +async fn google_move_sends_explicit_zero_content_length() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let mut request = prepare(&json!({"source":{"kind":"google","calendarId":"family@example.test"}, + "operation":"move","eventId":"meeting","destination":"owner@example.test","sendUpdates":"none"})).unwrap(); + assert_eq!(request.method, Method::POST); + assert!(request.url.path().ends_with("/events/meeting/move")); + assert!( + request + .url + .query_pairs() + .any(|(key, value)| key == "destination" && value == "owner@example.test") + ); + request.url.set_scheme("http").unwrap(); + request.url.set_host(Some("127.0.0.1")).unwrap(); + request + .url + .set_port(Some(listener.local_addr().unwrap().port())) + .unwrap(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut headers = Vec::new(); + loop { + let mut byte = [0]; + socket.read_exact(&mut byte).await.unwrap(); + headers.push(byte[0]); + if headers.ends_with(b"\r\n\r\n") { + break; + } + assert!(headers.len() < 16384); + } + let text = String::from_utf8(headers).unwrap().to_lowercase(); + let framed = text.contains("\r\ncontent-length: 0\r\n"); + let reply = if framed { + "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}" + } else { + "HTTP/1.1 411 Length Required\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + }; + socket.write_all(reply.as_bytes()).await.unwrap(); + assert!(framed, "empty Google POST must state its content length"); + }); + let client = Client::builder() + .no_proxy() + .timeout(Duration::from_secs(2)) + .build() + .unwrap(); + assert!( + execute(&client, request, Some("synthetic-token"), None) + .await + .is_ok() + ); + server.await.unwrap(); +} + #[tokio::test] async fn independent_calendar_requests_progress_concurrently() { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); diff --git a/src/platform/private_fs/unix.rs b/src/platform/private_fs/unix.rs index 38cebed..1033a6b 100644 --- a/src/platform/private_fs/unix.rs +++ b/src/platform/private_fs/unix.rs @@ -412,14 +412,22 @@ impl Drop for ExclusiveLock { pub(crate) fn lock_exclusive(dir: &File, name: &str) -> Result { validate_owned_root(dir)?; let name = cstr(name.as_ref())?; - let fd = unsafe { + let flags = libc::O_RDWR | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC; + // Darwin can return a spurious ENOENT when concurrent openat(O_CREAT) + // callers race the first creation. Use exclusive creation followed by a + // non-creating open of the winner; both remain relative to the pinned dir. + // https://github.com/golang/go/issues/81246 + let mut fd = unsafe { libc::openat( dir.as_raw_fd(), name.as_ptr(), - libc::O_RDWR | libc::O_CREAT | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC, + flags | libc::O_CREAT | libc::O_EXCL, 0o600, ) }; + if fd < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::EEXIST) { + fd = unsafe { libc::openat(dir.as_raw_fd(), name.as_ptr(), flags) }; + } if fd < 0 { return Err("cache_unsafe_path"); } diff --git a/src/platform/tests.rs b/src/platform/tests.rs index 3793756..1dca73e 100644 --- a/src/platform/tests.rs +++ b/src/platform/tests.rs @@ -202,6 +202,78 @@ mod unix { 0o600 ); } + + #[test] + fn concurrent_private_directory_and_lock_creation() { + let temp = Temp::new(); + for round in 0..32 { + let root = temp.0.join(format!("claim-{round}")); + let start = std::sync::Barrier::new(2); + std::thread::scope(|scope| { + let claim = || { + start.wait(); + let dir = directories(&root, &["omamail"], true) + .expect("concurrent reminder directory creation") + .expect("created reminder directory"); + let _lock = match lock_exclusive(&dir, "lease") { + Ok(lock) => lock, + Err("private_fs_busy") => return, + Err(error) => panic!( + "concurrent reminder lock creation: {error}; OS error: {}", + std::io::Error::last_os_error() + ), + }; + regular(&dir, "ledger", false).expect("read ledger while holding its lock"); + atomic_replace(&dir, "ledger", b"{}") + .expect("replace ledger while holding its lock"); + }; + let peer = scope.spawn(claim); + claim(); + peer.join().unwrap(); + }); + } + } + + #[test] + fn existing_lock_entries_are_validated_without_modifying_them() { + let temp = Temp::new(); + let dir = directories(&temp.0, &["omamail"], true).unwrap().unwrap(); + let victim = temp.0.join("victim"); + fs::write(&victim, b"private marker").unwrap(); + fs::set_permissions(&victim, fs::Permissions::from_mode(0o600)).unwrap(); + let lock_path = temp.0.join("omamail/lease"); + symlink(&victim, &lock_path).unwrap(); + assert!(matches!( + lock_exclusive(&dir, "lease"), + Err("cache_unsafe_path") + )); + assert!( + fs::symlink_metadata(&lock_path) + .unwrap() + .file_type() + .is_symlink() + ); + fs::remove_file(&lock_path).unwrap(); + fs::hard_link(&victim, &lock_path).unwrap(); + assert!(matches!( + lock_exclusive(&dir, "lease"), + Err("cache_unsafe_path") + )); + assert!(lock_path.exists()); + fs::remove_file(&lock_path).unwrap(); + fs::write(&lock_path, b"not private").unwrap(); + fs::set_permissions(&lock_path, fs::Permissions::from_mode(0o644)).unwrap(); + assert!(matches!( + lock_exclusive(&dir, "lease"), + Err("cache_unsafe_path") + )); + assert_eq!( + fs::metadata(&lock_path).unwrap().permissions().mode() & 0o777, + 0o644 + ); + assert_eq!(fs::read(&lock_path).unwrap(), b"not private"); + assert_eq!(fs::read(&victim).unwrap(), b"private marker"); + } #[tokio::test] async fn ipc_is_anchored_handles_long_unicode_roots_and_reclaims_stale_sockets() { use crate::platform::ipc::{LocalEndpoint, check_peer}; diff --git a/tests/test_agent_native_bridge.py b/tests/test_agent_native_bridge.py index 28d97f2..a438bb1 100644 --- a/tests/test_agent_native_bridge.py +++ b/tests/test_agent_native_bridge.py @@ -8,7 +8,9 @@ import json import os from pathlib import Path +import signal import subprocess +import threading import time import unittest @@ -54,11 +56,27 @@ def call(self, *args, value=None, ok=True): return answer['result'] if answer.get('ok') else answer.get('error', {}).get('code', '') def cleanup(self): + active = [] for ident in self.ids: - subprocess.run([str(BINARY),'--json','call','agent.jobCancel'], - input=json.dumps({'id':ident}), text=True, env=self.env, - capture_output=True, timeout=8) - time.sleep(.3) + result = subprocess.run([str(BINARY),'--json','call','agent.jobCancel'], + input=json.dumps({'id':ident}), text=True, env=self.env, + capture_output=True, timeout=8) + # Some tests intentionally remove jobs or invalidate their storage. + if result.returncode == 0: + job = json.loads(result.stdout)['result'] + if job['state'] in ('queued', 'running'): + active.append(ident) + # Cancellation only signals the detached worker. It must finish its + # final display/job writes before TemporaryDirectory removes storage. + deadline = time.monotonic() + 8 + while active: + active = [ident for ident in active + if self.call('show', ident)['job']['state'] in ('queued', 'running')] + if not active: + break + if time.monotonic() >= deadline: + self.fail('Cancelled workers did not settle before cleanup: ' + ', '.join(active)) + time.sleep(.04) self.assertFalse((self.root/'TERMINAL').exists()) def test_background_stdin_result_and_resume(self): @@ -114,6 +132,26 @@ def test_cancel_and_active_limit(self): self.assertEqual(self.wait(ident)['job']['state'],'cancelled') self.assertFalse(Path('/proc/%d'%pid).exists()) + def test_cleanup_waits_for_delayed_worker_shutdown(self): + self.agent('time.sleep(30)') + ident = self.new() + job = self.wait(ident, ('running',))['job'] + pid = job['pid'] + # Freeze the worker so cancellation cannot finish within the former + # 300ms cleanup sleep. Resume it independently of the cleanup call. + os.kill(pid, signal.SIGSTOP) + resume = threading.Timer(1, lambda: os.kill(pid, signal.SIGCONT)) + resume.start() + try: + self.cleanup() + saved = json.loads((self.store/ident/'job.json').read_text()) + self.assertEqual(saved['state'], 'cancelled') + self.assertNotIn('pid', saved) + finally: + resume.join() + self.call('cancel', ident) + self.wait(ident) + def test_deadline_and_stale_worker(self): # Actual short-deadline/native pipe cleanup is exercised by worker.rs's # injected-duration tests; production exposes no timeout-bypass setting. diff --git a/tests/test_calendar_notifications.py b/tests/test_calendar_notifications.py new file mode 100644 index 0000000..25c9094 --- /dev/null +++ b/tests/test_calendar_notifications.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Exercise real libnotify actions on a private D-Bus, never the desktop bus.""" +import importlib.util +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +def peer(): + import dbus + import dbus.mainloop.glib + import dbus.service + from gi.repository import GLib + + dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) + loop = GLib.MainLoop() + observed = {} + + class Notifications(dbus.service.Object): + @dbus.service.method('org.freedesktop.Notifications', out_signature='as') + def GetCapabilities(self): + return ['actions', 'body', 'body-markup'] + + @dbus.service.method('org.freedesktop.Notifications', out_signature='ssss') + def GetServerInformation(self): + return ('Synthetic calendar peer', 'Omamail tests', '1', '1.2') + + @dbus.service.method('org.freedesktop.Notifications', in_signature='susssasa{sv}i', out_signature='u') + def Notify(self, app, replaces, icon, summary, body, actions, hints, expires): + observed.update(summary=str(summary), body=str(body), actions=list(map(str, actions))) + GLib.timeout_add(100, lambda: (self.ActionInvoked(1, 'snooze'), self.NotificationClosed(1, 2), False)[2]) + return dbus.UInt32(1) + + @dbus.service.signal('org.freedesktop.Notifications', signature='us') + def ActionInvoked(self, notification_id, action): + pass + + @dbus.service.signal('org.freedesktop.Notifications', signature='uu') + def NotificationClosed(self, notification_id, reason): + pass + + bus = dbus.SessionBus() + name = dbus.service.BusName('org.freedesktop.Notifications', bus) + server = Notifications(bus, '/org/freedesktop/Notifications') + with tempfile.TemporaryDirectory() as directory: + marker = Path(directory) / 'forbidden' + child = subprocess.Popen([sys.executable, str(ROOT / 'scripts/notify-mail.py'), '--calendar', + '#657b83', '#268bd2', '--', ' & Planning', f'$(touch {marker}) β€” δ½ ε₯½'], + env=dict(os.environ, XDG_CACHE_HOME=str(Path(directory) / 'cache')), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + + def finish(): + if child.poll() is not None: + loop.quit() + return False + return True + + GLib.timeout_add(20, finish) + GLib.timeout_add_seconds(10, lambda: (child.kill(), loop.quit(), False)[2]) + loop.run() + stdout, stderr = child.communicate(timeout=2) + observed.update(exit=child.returncode, action=stdout.strip(), marker=marker.exists(), stderr=stderr) + print(json.dumps(observed)) + # Keep the bus objects alive until the client has completed. + del server, name + + +class CalendarNotifications(unittest.TestCase): + @unittest.skipUnless(shutil.which('dbus-run-session') and shutil.which('notify-send') + and importlib.util.find_spec('dbus') and importlib.util.find_spec('gi'), + 'requires notify-send, private D-Bus and Python GLib bindings') + def test_real_notify_send_routes_snooze_and_escapes_sender_markup(self): + result = subprocess.run(['dbus-run-session', '--', sys.executable, __file__, '--peer'], + capture_output=True, text=True, timeout=15) + self.assertEqual(result.returncode, 0, result.stderr) + observed = json.loads(result.stdout) + self.assertEqual(observed['exit'], 0, observed['stderr']) + self.assertEqual(observed['action'], 'snooze') + self.assertEqual(observed['summary'], '<img> & Planning') + self.assertEqual(observed['actions'], ['default', 'Open event...', 'snooze', 'Snooze', 'dismiss', 'Dismiss']) + self.assertFalse(observed['marker'], 'sender text was executed') + + +if __name__ == '__main__': + if '--peer' in sys.argv: + peer() + else: + unittest.main() diff --git a/tests/test_notification.py b/tests/test_notification.py index fdeddd1..d13da9c 100644 --- a/tests/test_notification.py +++ b/tests/test_notification.py @@ -64,6 +64,13 @@ def test_sender_markup_is_escaped_only_at_notify_send(self): self.assertEqual(result.returncode, 0) args = json.loads((tmp / 'argv').read_text()) self.assertEqual(args[-2:], ['<img> & sender', 'body <b>&']) + result = subprocess.run(['python3', str(ROOT / 'scripts/notify-mail.py'), '--calendar', + '#eeeeee', '#abcdef', '--', ' & event', '--action=evil'], env=env) + self.assertEqual(result.returncode, 0) + args = json.loads((tmp / 'argv').read_text()) + self.assertEqual(args[-3:], ['--', '<img> & event', '--action=evil']) + self.assertEqual([arg for arg in args[:-3] if arg.startswith('--action=')], + ['--action=default=Open event...', '--action=snooze=Snooze', '--action=dismiss=Dismiss']) if __name__ == '__main__': diff --git a/tests/test_qml_text_format.py b/tests/test_qml_text_format.py index 5847482..9bcbb6f 100644 --- a/tests/test_qml_text_format.py +++ b/tests/test_qml_text_format.py @@ -35,7 +35,10 @@ # The address goes in there, so the guard has to follow the value: read # from the element, the reference to `.email` is no longer visible and # this check would pass a Text that had stopped saying it was plain. - r"|primaryText\b|secondaryText\b)") + r"|primaryText\b|secondaryText\b" + # A discovered calendar's name is chosen by whoever shared it, and its + # detail line names a server somebody else configured. + r"|modelData\s*\.\s*name\b|sourceDetail\b)") # Strings and comments, masked in one pass so that neither can hide inside the # other. Masking strings alone let an apostrophe in a `//` comment open a diff --git a/tests/test_source.sh b/tests/test_source.sh index 940d1fc..72b5fea 100755 --- a/tests/test_source.sh +++ b/tests/test_source.sh @@ -351,16 +351,16 @@ for icon in chevronLeft chevronRight chevronDown mail; do fail "Icons.js does not define the $icon icon" fi done -grep -q 'text: "Week"' components/CalendarView.qml \ - || fail "the calendar needs a week-view control" +grep -q 'objectName: "calendar-view-selector"' components/CalendarView.qml \ + || fail "the calendar needs a view dropdown" python3 - <<'PY' from pathlib import Path text = Path("components/CalendarView.qml").read_text() -if text.index('text: "Week"') > text.index('text: "Month"'): +if '["Day", "Week", "Month", "Agenda"]' not in text: raise SystemExit("test_source.sh: Week must appear before Month in the view switcher") -if 'text: "Go to today"' not in text: +if 'text: "Today"' not in text or 'onClicked: root.goToday()' not in text: raise SystemExit("test_source.sh: Today must read as a navigation action") -today = text.index('text: "Go to today"') +today = text.index('text: "Today"') right = text.index('anchors.right: parent.right') if today > right: raise SystemExit("test_source.sh: Go to today must sit with the date on the left") @@ -431,7 +431,7 @@ text = Path("App.qml").read_text() header = text[text.index("id: headerRight"):text.index("PanelSeparator {", text.index("id: headerRight"))] if "spacing: Style.space(8)" not in header: raise SystemExit("test_source.sh: refresh needs breathing room before the header action") -for name in ("create-event-button", "compose-button"): +for name in ("compose-button",): marker = 'objectName: "' + name + '"' start = text.index(marker) opening = text.rfind("\n Button {", 0, start) @@ -456,7 +456,8 @@ app = Path("App.qml").read_text() sidebar_use = app[app.index("id: sidebar"):app.index("MailboxTabs {")] if "!root.calendarVisible" in sidebar_use or "calendarSelected: root.calendarVisible" not in sidebar_use: raise SystemExit("test_source.sh: the mailbox sidebar must remain visible and select Calendar") -header = app[app.index("id: headerRight"):app.index("// mailbox as a whole")] +header_start = app.index("id: headerRight") +header = app[header_start:app.index("PanelSeparator {", header_start)] if 'iconName: root.calendarVisible ? "mail" : "calendar"' in header: raise SystemExit("test_source.sh: Calendar navigation belongs in the sidebar, not the header") @@ -477,12 +478,12 @@ if "calendarTodayBackgroundColor: root.calendarTodayBackground" not in app: raise SystemExit("test_source.sh: App must pass the system Today background token") if "readonly property color calendarBorder: Style.normalBorderColor" not in app: raise SystemExit("test_source.sh: calendar borders must originate from the system border token") -if "readonly property color calendarTodayBackground: Style.selectedAccentFill" not in app: +if "readonly property color calendarTodayBackground: Qt.alpha(root.accent, 0.035)" not in app: raise SystemExit("test_source.sh: Today must use the quieter system accent fill token") if "calendarBorderWidth: root.calendarBorderWidth" not in app: raise SystemExit("test_source.sh: App must pass the system calendar border width") -if "border.color: root.calendarBorderColor" not in calendar or "border.width: root.calendarBorderWidth" not in calendar: - raise SystemExit("test_source.sh: month cells must consume the themed calendar border") +if "color: Qt.alpha(root.calendarBorderColor, 0.25)" not in calendar or "width: root.calendarBorderWidth" not in calendar or "height: root.calendarBorderWidth" not in calendar: + raise SystemExit("test_source.sh: month dividers must consume the themed calendar border") if "? root.calendarTodayBackgroundColor" not in calendar: raise SystemExit("test_source.sh: the Month Today cell must consume the themed background") if ("calendarBorderColor: root.calendarBorderColor" not in calendar @@ -527,7 +528,7 @@ service = Path("Service.qml").read_text() if "readonly property var pendingSendHost" not in service: raise SystemExit("test_source.sh: an undoable send must remain reachable across accounts") PY -grep -q 'allDayEventsOnDay' components/WeekCalendarView.qml \ +grep -q 'Calendar.displayInAllDayLane' components/WeekCalendarView.qml \ || fail "all-day events must have a pinned week-view lane" grep -q 'signal createAt' components/WeekCalendarView.qml \ || fail "empty week slots must start event creation" @@ -581,9 +582,9 @@ grep -q 'leaving.kind === "calendarDetail"' App.qml \ if grep -q 'Shortcut { sequence: "Escape"' components/CalendarEventComposer.qml; then fail "event creation must use the central Escape route, not an ambiguous duplicate" fi -grep -q 'text: "Make recurring"' components/CalendarEventComposer.qml \ +grep -q 'objectName: "event-repeat-selector"' components/CalendarEventComposer.qml \ || fail "event creation needs an optional recurrence section" -grep -q 'text: "Add a calendar"' components/CalendarSettings.qml \ +grep -q 'text: "Connect a CalDAV calendar\.\.\."' components/CalendarSettings.qml \ || fail "settings must let a user add a calendar" grep -q 'placeholderText: "Calendar name"' components/CalendarSettings.qml \ || fail "calendar setup needs a name field" diff --git a/ui/App.qml b/ui/App.qml index 84d69a8..ae08007 100644 --- a/ui/App.qml +++ b/ui/App.qml @@ -119,7 +119,7 @@ Item { readonly property color borderColor: Style.normalBorderColor readonly property int borderWidth: Style.normalBorderWidth readonly property color calendarBorder: Style.normalBorderColor - readonly property color calendarTodayBackground: Style.selectedAccentFill + readonly property color calendarTodayBackground: Qt.alpha(root.accent, 0.035) readonly property int calendarBorderWidth: Style.normalBorderWidth readonly property color dim: Qt.rgba( foreground.r * 0.68 + background.r * 0.32, @@ -1063,8 +1063,15 @@ Item { if (id === "calendarNextPeriod") return calendarView.movePeriod(1) if (id === "calendarToday") return calendarView.goToday() if (id === "calendarWeek") return calendarView.setView("week") + if (id === "calendarDay") return calendarView.setView("day") + if (id === "calendarAgenda") return calendarView.setView("agenda") + if (id === "calendarUndo") return root.service.calendarController.undoLastChange() if (id === "calendarMonth") return calendarView.setView("month") if (id === "send") return compose.submit() + if (id === "saveEvent") return eventComposer.submit("all") + if (id === "guestNext") return eventComposer.moveGuestSuggestion(1) + if (id === "guestPrevious") return eventComposer.moveGuestSuggestion(-1) + if (id === "guestChoose") return eventComposer.chooseGuestSuggestion() if (id === "undoSend") { undoPendingSend(); return } if (id === "search") return searchBar.focusField() if (id === "goMailbox") return goSlot(Keymap.slotFor(id, sequence)) @@ -1107,6 +1114,8 @@ Item { // purpose: a QQC.Popup with CloseOnEscape consumes the key itself, so a // branch for them here would never run. Everything else is the history. function goBack() { + if (eventComposer.guestSuggestionsOpen) { eventComposer.dismissGuestSuggestions(); return } + if (calendarView.dismissPreview()) return if (activeAssistant && activeAssistant.commandsOpen) { activeAssistant.dismissCommands(); return } if (activeAssistant && activeAssistant.historyMode) { activeAssistant.historyMode = false; activeAssistant.takeFocus(); return } if (activeAssistant && activeAssistant.interrupt()) return @@ -1361,24 +1370,15 @@ Item { nav = Nav.push(Nav.resetTo(nav, rootKind()), Nav.entry("settings")) } - // A delete asks first, and asks naming the target. Only the confirmation - // reaches the controller, with the event the dialog named. + // Confirm the named event or series before deleting it. function requestEventDelete(sourceId, event) { - if (!event) return - confirmDeleteDialog.openFor({ - kind: "event", - name: String(event.summary || "Untitled event"), - message: "This event will be permanently deleted.", - sourceId: String(sourceId || ""), - event: event - }) + if (event && service) confirmDeleteDialog.openFor(service.calendarController.deleteRequest(sourceId, event)) } - function confirmDelete(request) { if (!service) return if (request.kind === "event" && request.event) { - service.calendarController.deleteEvent(request.sourceId, request.event) + service.calendarController.confirmDelete(request) calendarView.closeDetail() } if (request.kind === "label" && request.labelId) service.deleteLabel(request.labelId, request.accountId) @@ -1528,20 +1528,15 @@ Item { assistantCommands: !!root.activeAssistant && root.activeAssistant.commandsOpen, showPage: root.showPage, composing: root.composing, + eventComposing: eventComposer.opened, + guestSuggestions: eventComposer.guestSuggestionsOpen, searchFocused: searchBar.fieldFocused, calendarVisible: root.calendarVisible, currentView: root.currentView, sendPending: !!root.service && root.service.sendPending })) - // The context owns the keyboard. Changing it moves the focus to whatever - // that context types into, or parks it when the context types into - // nothing β€” so a field that has been dismissed cannot go on eating keys. - // - // Keeping these as two things is the bug this replaces: the context came - // from the screen while the focus stayed wherever the last click left it, - // and a closed compose field kept swallowing j and k. One mechanism now, - // and there is nothing to keep in step. + // Context changes move or park focus so dismissed fields cannot eat keys. onKeyContextChanged: Qt.callLater(applyContextFocus) function focusWithin(container) { var item = focusScope.Window.activeFocusItem @@ -1554,6 +1549,9 @@ Item { if (composeAgent.opened && !composeAgent.activeFocus) composeAgent.takeFocus() else if (agentPrompt.opened && !agentPrompt.activeFocus) agentPrompt.takeFocus() } + else if (keyContext === "eventCompose" || keyContext === "eventGuests") { + if (!focusWithin(eventComposer)) eventComposer.takeFocus() + } else if (keyContext === "compose") { if (focusWithin(compose)) return if (eventComposer.opened) eventComposer.takeFocus() @@ -1585,46 +1583,23 @@ Item { anchors.top: parent.top anchors.left: parent.left anchors.right: parent.right - height: Style.space(48) + height: calendarHeaderSlot.visible && calendarHeaderSlot.stacked + ? Style.space(60) + calendarView.toolbarHeight : Math.max(Style.space(48), calendarHeaderSlot.visible ? calendarView.toolbarHeight + Style.space(12) : 0) visible: !root.composing - // Kept below the header controls so their own pointer handlers win. - // Empty title-bar space starts the platform's native move operation. - // A DragHandler with no target: a MouseArea keeps the grab and feeds - // moves into QML while the compositor is already dragging, which is - // the lag of a window that trails the pointer. - MouseArea { - id: windowMoveArea - objectName: "app-title-bar-drag-area" + WindowMoveArea { anchors.fill: parent enabled: root.standaloneWindowChrome - acceptedButtons: Qt.NoButton - hoverEnabled: false - // Exposed for tests: a target would fight the compositor drag. - readonly property bool dragsTheWindow: windowMoveHandler.target === null - - DragHandler { - id: windowMoveHandler - enabled: windowMoveArea.enabled - target: null - dragThreshold: 0 - acceptedButtons: Qt.LeftButton - onActiveChanged: { - if (!active) return - var nativeWindow = header.Window.window - if (nativeWindow) nativeWindow.startSystemMove() - } - } + nativeWindow: header.Window.window } - // Identity first, controls after, with a rule between them: the mark - // and the name say what this window is, and everything to their right - // does something. + // App identity precedes the current view's controls. Row { id: headerLeft anchors.left: parent.left anchors.leftMargin: Style.space(14) anchors.verticalCenter: parent.verticalCenter + anchors.verticalCenterOffset: calendarHeaderSlot.visible && calendarHeaderSlot.stacked ? (Style.space(48) - header.height) / 2 : 0 spacing: Style.space(8) ActionIcon { @@ -1712,20 +1687,29 @@ Item { } } + Item { + id: calendarHeaderSlot + objectName: "calendar-header-slot" + readonly property bool stacked: header.width < Style.space(1100) + visible: root.calendarVisible && !root.showPage && !root.composing && !calendarView.detailOpen + x: stacked ? Style.space(14) : headerLeft.x + headerLeft.width + Style.space(20) + y: stacked ? Style.space(48) : (header.height - height) / 2 + width: Math.max(0, (stacked ? header.width - Style.space(14) : headerRight.x - Style.space(20)) - x) + height: calendarView.toolbarHeight + } + Row { id: headerRight anchors.right: parent.right anchors.rightMargin: Style.space(14) anchors.verticalCenter: parent.verticalCenter + anchors.verticalCenterOffset: calendarHeaderSlot.visible && calendarHeaderSlot.stacked ? (Style.space(48) - header.height) / 2 : 0 spacing: Style.space(8) - // Checking for mail and writing one are both things you do to the - // mailbox as a whole, so they sit together. The menu is the window's - // own, and it stays on the left with the mark. IconButton { objectName: "refresh-button" anchors.verticalCenter: parent.verticalCenter - visible: !root.showPage && !root.composing + visible: !root.showPage && !root.composing && !root.calendarVisible iconName: "refresh" tooltipText: root.calendarVisible ? (root.service && root.service.calendarController.loading @@ -1747,21 +1731,6 @@ Item { } } - Button { - objectName: "create-event-button" - anchors.verticalCenter: parent.verticalCenter - visible: !root.showPage && !root.composing && root.calendarVisible - text: "Create event" - tooltipText: "Create event" - foreground: root.dim - bordered: true - accent: root.accent - fontFamily: root.fontFamily - fontSize: Style.font.caption - enabled: root.ready - onClicked: eventComposer.begin() - } - Button { id: headerComposeButton objectName: "compose-button" @@ -2205,6 +2174,7 @@ Item { z: 10 CalendarView { + toolbarHost: calendarHeaderSlot id: calendarView anchors.fill: parent controller: root.service ? root.service.calendarController : null @@ -2408,6 +2378,14 @@ Item { urgentColor: root.urgent panelFontFamily: root.fontFamily onClientSetupRequested: root.openClientSetup() + onCalendarSignInRequested: function(index) { + root.editAccount(index) + Qt.callLater(function() { if (root.service) root.service.signIn() }) + } + onOpenCalendarRequested: { + root.showCalendar() + calendarView.refresh() + } // Which kind first, then the form for it. onAddRequested: root.addMailbox() onEditRequested: function(index) { root.editAccount(index) } diff --git a/ui/Service.qml b/ui/Service.qml index 10faa33..5fc9662 100644 --- a/ui/Service.qml +++ b/ui/Service.qml @@ -110,6 +110,13 @@ Item { readonly property bool backendCanSuggestEvents: backend.ready && backend.apiVersion >= 2 readonly property bool backendCanCheckMicrosoftConnection: backend.ready && backend.apiVersion >= 5 readonly property bool backendCanDiscoverCalendars: backend.ready && backend.apiVersion >= 5 + readonly property bool backendCanGoogleCalendars: backend.ready && backend.apiVersion >= 6 + readonly property bool calendarRemindersEnabled: !settings || settings.calendarRemindersEnabled !== false + readonly property int calendarSnoozeMinutes: Math.max(1, Math.min(1440, + Math.floor(Number(settings && settings.calendarSnoozeMinutes) || 5))) + readonly property string calendarReminderError: calendarReminderLoader.item + ? calendarReminderLoader.item.lastError || calendarReminderLoader.item.inbox.lastError : "" + readonly property var calendarReminderInbox: calendarReminderLoader.item ? calendarReminderLoader.item.inbox : null readonly property string pluginId: manifest && manifest.id ? String(manifest.id) : "omamail" @@ -138,6 +145,8 @@ Item { oauthPort: 9481, undoSendSeconds: 10, unifiedCalendarView: false, + calendarRemindersEnabled: true, + calendarSnoozeMinutes: 5, showBarIcon: true, unifiedMailboxes: false, suggestEvents: false @@ -1932,6 +1941,8 @@ Item { readonly property string selectedResponse: reading ? reading.selectedResponse : "" readonly property bool canRespondToInvite: !!reading && reading.canRespondToInvite readonly property bool rsvpSending: !!reading && reading.rsvpSending + readonly property bool rsvpFallbackAvailable: !!reading && reading.rsvpFallbackAvailable === true + readonly property string rsvpCalendarUrl: reading ? Provider.calendarAttendanceUrl(reading.providerId, reading.accountId) : "" // Empty when this message offers no way off a list, which is the answer for // everything that is not a newsletter. readonly property string unsubscribeLabel: reading ? reading.unsubscribeLabel : "" @@ -2087,6 +2098,7 @@ Item { if (typeof callback === "function") callback("") } function rsvp(response) { if (reading) reading.rsvp(response) } + function rsvpMailOnly(response) { if (reading) reading.rsvpMailOnly(response) } function unsubscribe() { if (reading) reading.unsubscribe() } function cursorOffset(cursorId, delta) { if (unified) return Unified.cursorOffset(unifiedMessages, cursorId, delta) @@ -2555,6 +2567,19 @@ Item { Component.onCompleted: Qt.callLater(root.refreshCalendarPreview) } + Loader { + id: calendarReminderLoader + active: root.backendCanGoogleCalendars && root.calendarRemindersEnabled + sourceComponent: Component { + CalendarReminders { + service: root + pluginDir: root.pluginDir + notificationForeground: Color.foreground + notificationAccent: Color.accent + } + } + } + Timer { interval: 600000 repeat: true diff --git a/ui/account/Accounts.js b/ui/account/Accounts.js index 92d8c13..dc796f5 100644 --- a/ui/account/Accounts.js +++ b/ui/account/Accounts.js @@ -56,6 +56,7 @@ function isValidEmail(value) { function calendarProvider(raw) { var account = raw || {} var provider = trimmed(account.provider).toLowerCase() + if (provider === "gmail" || provider === "") return "google" if (provider === "outlook") return "microsoft" if (provider !== "imap") return "" var host = trimmed(account.imap && account.imap.imapHost).toLowerCase() diff --git a/ui/account/MailAccount.qml b/ui/account/MailAccount.qml index 756e3be..c9a6a39 100644 --- a/ui/account/MailAccount.qml +++ b/ui/account/MailAccount.qml @@ -2384,6 +2384,8 @@ Item { // See `Rsvp.qml`: the account file is at its size ceiling. function rsvp(response) { rsvpAction.run(response) } + readonly property bool rsvpFallbackAvailable: rsvpAction.fallbackAvailable + function rsvpMailOnly(response) { rsvpAction.run(response, true) } readonly property alias bodies: bodyCache Rsvp { diff --git a/ui/account/Rsvp.qml b/ui/account/Rsvp.qml index 559f783..4d636ff 100644 --- a/ui/account/Rsvp.qml +++ b/ui/account/Rsvp.qml @@ -1,32 +1,112 @@ import QtQuick import "../message/Message.js" as Mail import "../message/Calendar.js" as Calendar +import "../providers/Registry.js" as Provider +import "../calendar/Calendar.js" as Events -// Answering an invitation is sending a mail, which is the whole reason this -// needs no calendar API, no second OAuth scope, and works the same on IMAP -// as on Gmail: an RFC 5546 REPLY addressed to the organiser is what every -// calendar server is already listening for. Not routed through the account's -// `send`: that one is the compose window's, and finishing emits `replySent`, -// which closes it. This finishes with a card that has changed its mind. +// Native attendance is authoritative where the provider supports it. Other +// providers send an RFC 5546 reply through their mail transport. // Beside the account rather than in it, which is at its size ceiling; the // state the reader draws (`rsvpSending`, `selectedResponse`) stays there. QtObject { id: rsvpAction required property var account + property string reconciledKey: "" + property bool reconciling: false + property int attendanceRevision: 0 + property string fallbackMessageId: "" + readonly property bool fallbackAvailable: (fallbackMessageId !== "" && fallbackMessageId === account.selectedId) + || (!!account.selectedInvite && account.selectedId !== "" + && Provider.calendarAttendanceMethod(account.providerId) !== "" + && !!account.backend && account.backend.ready + && account.backend.apiVersion > 0 && account.backend.apiVersion < 6) + property Connections selection: Connections { + target: rsvpAction.account + function onSelectedIdChanged() { rsvpAction.reconciledKey = ""; rsvpAction.attendanceRevision++; rsvpAction.fallbackMessageId = "" } + function onSelectedInviteChanged() { Qt.callLater(rsvpAction.reconcile) } + } + property Timer reconcileTimer: Timer { + interval: 60000 + repeat: true + running: !!account.selectedInvite && account.ready + onTriggered: { rsvpAction.reconciledKey = ""; rsvpAction.reconcile() } + } + + // The organizer travels with the UID because a UID alone is not proof: any + // sender can reuse one, and the backend refuses a calendar copy whose + // organizer is not the one this invitation names. + function invitationParams(invited) { + var organizer = Calendar.replyRecipient(invited) + if (!organizer) return null + var params = { accountId: account.accountId, uid: invited.uid, organizer: organizer } + if (invited.recurrenceIdMs) { + params.originalStart = new Date(invited.recurrenceIdMs).toISOString() + var raw = String(invited.source && invited.source.recurrenceId || "") + var day = /(?:^|;)VALUE=DATE(?:;[^:]*)?:(\d{4})(\d{2})(\d{2})$/.exec(raw) + if (day) params.originalStart = day[1] + "-" + day[2] + "-" + day[3] + } + return params + } + + function reconcile() { + var method = Provider.calendarAttendanceMethod(account.providerId) + if (!method || !account.selectedInvite || !account.backend || !account.backend.ready + || account.backend.apiVersion < 6 || reconciling || account.rsvpSending) return + var invited = account.selectedInvite + var id = account.selectedId + var identity = account.accountId + var revision = attendanceRevision + var key = identity + "\n" + id + "\n" + invited.uid + if (key === reconciledKey) return + reconciledKey = key + var params = invitationParams(invited) + if (!params) return + reconciling = true + account.backend.call(method, params, function(result, error) { + rsvpAction.reconciling = false + if (identity !== account.accountId || id !== account.selectedId || account.rsvpSending + || revision !== rsvpAction.attendanceRevision) return + if (error || !result) return + var updated = {} + for (var field in invited) updated[field] = invited[field] + if (result.cancelled) { + updated.status = "CANCELLED" + updated.method = "CANCEL" + } else { + var normalized = Events.eventsFromGoogle({ items: [result.event] }, "") + if (!normalized.length) return + var current = normalized[0] + var keys = ["summary", "description", "location", "start", "end", "sequence", "status", "meetLink"] + for (var i = 0; i < keys.length; i++) updated[keys[i]] = current[keys[i]] + updated = Calendar.withResponse(updated, account.receivedAsAddress, String(result.response || "").toUpperCase()) + if (result.response === "needsAction") { + updated.attendees = (updated.attendees || []).map(function(attendee) { + if (String(attendee.email || "").toLowerCase() !== account.receivedAsAddress.toLowerCase()) return attendee + var next = {} + for (var key in attendee) next[key] = attendee[key] + next.partstat = "NEEDS-ACTION" + return next + }) + } + } + rsvpAction.cacheInvite(id, updated) + }) + } - // Answering an invitation is sending a mail, which is the whole reason this - // needs no calendar API, no second OAuth scope, and works the same on IMAP - // as on Gmail: an RFC 5546 REPLY addressed to the organiser is what every - // calendar server is already listening for. - // // Not routed through `send`: that one is the compose window's, and finishing // emits `replySent`, which closes it. This finishes with a card that has // changed its mind. - function run(response) { + function run(response, mailOnly) { if (!account.ready || account.rsvpSending || !account.canRespondToInvite) return var answer = String(response || "") + var method = Provider.calendarAttendanceMethod(account.providerId) + if (mailOnly === true && !fallbackAvailable) return + if (method !== "" && mailOnly !== true) { + nativeAnswer(method, answer) + return + } // The alias the invitation was addressed to, not the account's primary // address: the ATTENDEE line has to name the person who was invited. var answeringAs = account.receivedAsAddress @@ -70,12 +150,50 @@ QtObject { account.fail(error) return } - account.note("Answer sent to " + fields.to) + account.note(mailOnly === true ? "Reply email sent; Calendar attendance is not confirmed" : "Answer sent to " + fields.to) + if (mailOnly === true) return if (account.selectedId !== messageId) return rememberResponse(messageId, invited, answeringAs, answer) }) } + function nativeAnswer(method, answer) { + attendanceRevision++ + if (!account.backend || !account.backend.ready || account.backend.apiVersion < 6) { + account.fail("Update the backend to answer this invitation in Calendar") + return + } + var response = Calendar.normalizedResponse(answer) + if (!response) return + var invited = account.selectedInvite + var messageId = account.selectedId + var identity = account.accountId + var answeringAs = account.receivedAsAddress + var params = invitationParams(invited) + if (!params) { + account.fail("This invitation names no organiser to answer") + return + } + params.response = response + account.rsvpSending = true + account.clearNotice() + account.backend.call(method, params, function(result, error) { + account.rsvpSending = false + if (identity !== account.accountId) return + if (error || !result || result.response !== response) { + if (error && (error.message === "calendar_invitation_not_found" + || error.message === "calendar_organizer_mismatch") && account.selectedId === messageId) + rsvpAction.fallbackMessageId = messageId + account.fail("Calendar has not confirmed your answer. Refresh the invitation or open it in Calendar.") + return + } + account.note("Attendance confirmed in Calendar") + rsvpAction.fallbackMessageId = "" + if (account.selectedId === messageId) + rememberResponse(messageId, invited, answeringAs, answer) + }) + } + // The answer, written back into the copy of the invitation on disk. // // The `text/calendar` part is the organiser's document and this does not @@ -85,6 +203,10 @@ QtObject { // is what was cached a moment ago. function rememberResponse(messageId, invited, answeringAs, answer) { var updated = Calendar.withResponse(invited, answeringAs, answer) + cacheInvite(messageId, updated) + } + + function cacheInvite(messageId, updated) { account.selectedInvite = updated account.bodies.put(messageId, ({ text: account.selectedBody.text, diff --git a/ui/backend/Runtime.qml b/ui/backend/Runtime.qml index e642007..ebf1422 100644 --- a/ui/backend/Runtime.qml +++ b/ui/backend/Runtime.qml @@ -38,7 +38,11 @@ Item { if (bundled) { requiredVersion = bundledVersion requiredApiVersion = bundledApiVersion - latestApiVersion = bundledApiVersion + // The same one step past the pin the plugin accepts. A release bundle + // carries the released backend; `make app-run` builds this checkout's, + // which answers with the unreleased step and was refused as incompatible. + // Features still gate on the API the connected binary reports. + latestApiVersion = bundledApiVersion > 0 ? bundledApiVersion + 1 : 0 unreleasedMethods = [] installedVersion = bundledVersion executable = bundledExecutable diff --git a/ui/calendar/Cache.js b/ui/calendar/Cache.js index eb1c4ce..5fdc109 100644 --- a/ui/calendar/Cache.js +++ b/ui/calendar/Cache.js @@ -35,26 +35,45 @@ function rangeKey(scope, startMs, endMs) { function eventsFor(store, scope, startMs, endMs, enabledSourceIds) { var source = store && store.ranges ? store.ranges[rangeKey(scope, startMs, endMs)] : null + if (!source && store && store.ranges) { + var candidates = Object.keys(store.ranges).filter(function(key) { + var range = store.ranges[key] + return key.indexOf(String(scope || "") + "\n") === 0 + && Number(range.startMs) < Number(endMs) && Number(range.endMs) > Number(startMs) + }) + candidates.sort(function(a, b) { return Number(store.ranges[b].at) - Number(store.ranges[a].at) }) + if (candidates.length) source = store.ranges[candidates[0]] + } var values = source && Array.isArray(source.events) ? source.events : [] var enabled = {} var ids = Array.isArray(enabledSourceIds) ? enabledSourceIds : [] for (var i = 0; i < ids.length; i++) enabled[String(ids[i])] = true var out = [] for (var j = 0; j < values.length; j++) { - if (values[j] && enabled[String(values[j].sourceId || "")]) out.push(values[j]) + var event = values[j] + if (event && enabled[String(event.sourceId || "")] + && (!event.start || Number(event.start.ms) < Number(endMs)) + && (!event.end || Number(event.end.ms) > Number(startMs))) out.push(event) } return out } -function putRange(store, scope, startMs, endMs, events, nowMs) { +function putRange(store, scope, startMs, endMs, events, nowMs, refreshedSourceIds) { var source = store && isObject(store.ranges) ? store.ranges : {} var ranges = {} for (var key in source) ranges[key] = source[key] + var kept = Array.isArray(events) ? events.slice() : [] + var old = source[rangeKey(scope, startMs, endMs)] + if (Array.isArray(refreshedSourceIds) && old && Array.isArray(old.events)) { + kept = kept.concat(old.events.filter(function(event) { + return event && refreshedSourceIds.indexOf(String(event.sourceId || "")) < 0 + })) + } ranges[rangeKey(scope, startMs, endMs)] = { startMs: Number(startMs) || 0, endMs: Number(endMs) || 0, at: Number(nowMs) || 0, - events: (Array.isArray(events) ? events : []).slice(0, MAX_EVENTS) + events: kept.slice(0, MAX_EVENTS) } var keys = Object.keys(ranges) keys.sort(function(a, b) { return Number(ranges[b].at) - Number(ranges[a].at) }) diff --git a/ui/calendar/Calendar.js b/ui/calendar/Calendar.js index 790973c..2da6823 100644 --- a/ui/calendar/Calendar.js +++ b/ui/calendar/Calendar.js @@ -409,11 +409,22 @@ function eventsFromGoogle(payload, sourceId) { // patching or deleting it does exactly what Google Calendar does to one // occurrence of a series. googleId: String(item.id || ""), + etag: String(item.etag || ""), + recurringEventId: String(item.recurringEventId || ""), + originalStartTime: item.originalStartTime || null, + timeZone: String(item.start && item.start.timeZone || payload.timeZone || ""), + reminders: item.reminders || { useDefault: true }, + conferenceData: item.conferenceData || null, + eventType: String(item.eventType || "default"), + guestsCanModify: item.guestsCanModify === true, + transparency: String(item.transparency || "opaque"), + visibility: String(item.visibility || "default"), sequence: Math.max(0, Math.floor(Number(item.sequence) || 0)), summary: String(item.summary || "Untitled event"), description: String(item.description || ""), location: String(item.location || ""), status: String(item.status || "").toUpperCase(), organizer: item.organizer || null, attendees: Array.isArray(item.attendees) ? item.attendees : [], + recurrenceLines: Array.isArray(item.recurrence) ? item.recurrence.slice() : [], start: start, end: end, recurrence: Array.isArray(item.recurrence) ? item.recurrence.join("; ") : "", meetLink: String(item.hangoutLink || ""), sourceId: String(sourceId || ""), href: String(item.htmlLink || ""), source: null @@ -423,6 +434,12 @@ function eventsFromGoogle(payload, sourceId) { return out } +function eventKey(event) { + if (!event) return "" + return String(event.sourceId || "") + "\n" + String(event.googleId || event.graphId + || String(event.uid || "") + "\n" + String(event.recurrenceIdMs || event.start && event.start.ms || "")) +} + // ------------------------------------------------------------- Microsoft // // Graph's calendar view: the primary calendar's events between two moments, @@ -540,7 +557,7 @@ function nativeRequestError(kind) { if (kind === "microsoft") return "Microsoft calendar request failed. Check Graph permissions in Settings, then sign in again" if (kind === "google") - return "Google calendar request failed. Sign in again and check Calendar access" + return "Google could not complete this calendar request. Refresh the event and try again" if (kind === "caldav") return "CalDAV calendar request failed. Check its server address and password in Settings" // An iCloud calendar signs in with the mailbox's app-specific password, so @@ -598,6 +615,23 @@ function recurrenceIntervalUnit(frequency, interval) { return Number(interval) === 1 ? unit : unit + "s" } +function editorDateRange(firstDate, firstTime, lastDate, lastTime, allDay) { + function parse(dateText, timeText) { + if (!/^\d{4}-\d{2}-\d{2}$/.test(dateText) || !/^([01]\d|2[0-3]):[0-5]\d$/.test(timeText)) return null + var value = new Date(dateText + "T" + timeText + ":00") + if (!isFinite(value.getTime()) || isoDate(value) !== dateText + || two(value.getHours()) + ":" + two(value.getMinutes()) !== timeText) return null + return value + } + var start = parse(String(firstDate), allDay ? "00:00" : String(firstTime)) + var end = parse(String(lastDate), allDay ? "00:00" : String(lastTime)) + if (!start || !end) return {ok:false,error:allDay ? "Enter valid dates (YYYY-MM-DD)" : "Enter valid dates (YYYY-MM-DD) and times (HH:mm)"} + if (allDay) end.setDate(end.getDate() + 1) + if (end.getTime() <= start.getTime()) return {ok:false,error:allDay + ? "Last day must be on or after the first day" : "End date and time must be after the start"} + return {ok:true,error:"",startMs:start.getTime(),endMs:end.getTime()} +} + function validateEventFields(fields) { var value = fields || {} var title = String(value.title || "").trim() @@ -657,6 +691,190 @@ function googleEventBody(fields, allDay) { return body } +function googleEventPatch(fields, allDay, existingAllDay) { + var body = googleEventBody(fields, allDay) + if (existingAllDay === allDay) return body + // PATCH preserves omitted nested fields. Explicitly remove the other time + // representation so a conversion cannot leave both date and dateTime set. + if (allDay) { + body.start.dateTime = null + body.end.dateTime = null + body.start.timeZone = null + body.end.timeZone = null + } else { + body.start.date = null + body.end.date = null + } + return body +} + +function googleOptions(body, fields, source, existing) { + var next = JSON.parse(JSON.stringify(body)) + if (existing && fields.changeRecurrence === true) { + if (existing.recurringEventId) return { ok: false, error: "Open the entire series to change repetition" } + var recurrence = recurrenceRule(fields.recurrence) + if (!recurrence.ok) return recurrence + var lines = (existing.recurrenceLines || []).filter(function(line) { return String(line).indexOf("RRULE:") !== 0 }) + if (recurrence.rule !== "") lines.unshift("RRULE:" + recurrence.rule) + next.recurrence = lines + } + var zone = String(fields.timeZone || existing && existing.timeZone || source && source.timeZone || "") + if (zone !== "" && next.start && next.start.dateTime) { + next.start.timeZone = zone + next.end.timeZone = zone + } + if (fields.guestEmails !== undefined) { + var emails = String(fields.guestEmails).split(/[,;\n]/).map(function(email) { return email.trim() }).filter(function(email) { return email !== "" }) + if (emails.length > 200 || emails.some(function(email) { return !/^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/.test(email) })) + return { ok: false, error: "Enter valid guest email addresses separated by commas" } + var seen = {}, previous = existing && Array.isArray(existing.attendees) ? existing.attendees : [] + next.attendees = [] + for (var i = 0; i < emails.length; i++) { + var email = emails[i].toLowerCase() + if (seen[email]) continue + seen[email] = true + var matched = previous.filter(function(attendee) { return String(attendee.email || "").toLowerCase() === email }) + next.attendees.push(matched.length ? matched[0] : { email: emails[i] }) + } + } + if (fields.transparency === "opaque" || fields.transparency === "transparent") next.transparency = fields.transparency + if (["default", "public", "private"].indexOf(fields.visibility) >= 0) next.visibility = fields.visibility + if (fields.reminderMode === "default") next.reminders = { useDefault: true } + else if (fields.reminderMode === "none") next.reminders = { useDefault: false, overrides: [] } + else if (fields.reminderMode === "custom") { + var minutes = Number(fields.reminderMinutes) + if (!isFinite(minutes) || minutes < 0 || minutes > 40320 || Math.floor(minutes) !== minutes) + return { ok: false, error: "Reminder minutes must be a whole number from 0 to 40320" } + next.reminders = { useDefault: false, overrides: [{ method: "popup", minutes: minutes }] } + } + if (fields.createMeet === true) { + if (!source || source.canCreateMeet !== true) + return { ok: false, error: "This calendar cannot create Google Meet meetings" } + if (!(existing && existing.conferenceData)) { + next.conferenceData = { createRequest: { + requestId: String(fields.conferenceRequestId || ""), + conferenceSolutionKey: { type: "hangoutsMeet" } + } } + if (next.conferenceData.createRequest.requestId === "") + return { ok: false, error: "The meeting request has no identity" } + } + } + return { ok: true, body: next } +} + +function transferRefusal(source, destination, event) { + if (!source || !destination || source.kind !== "google" || destination.kind !== "google") + return "Calendar transfers are not available for this provider" + if (source.accountId !== destination.accountId) return "Choose a calendar in the same account" + if (source.readOnly) return "The original calendar is read-only" + if (destination.readOnly) return "The destination calendar is read-only" + if (!event || event.eventType !== "default" || !event.organizer || event.organizer.self !== true) + return "Only ordinary events you organize can change calendars" + if (event.recurringEventId) return "Open the entire series before changing its calendar" + return "" +} + +function rescheduleFields(event, startMs, endMs) { + return { title: String(event.summary || ""), description: String(event.description || ""), + location: String(event.location || ""), startMs: Number(startMs), endMs: Number(endMs), + allDay: !!(event.start && event.start.allDay), timeZone: String(event.timeZone || ""), sendUpdates: "none" } +} + +function gestureRange(event, dayOffset, minuteOffset, edge) { + if (!event || !event.start || !event.end) return null + var start = Number(event.start.ms), end = Number(event.end.ms) + var minutes = Math.round(Number(minuteOffset) / 15) * 15 + if (edge === "start") start = Math.min(end - 900000, Math.round((start + Number(minuteOffset) * 60000) / 900000) * 900000) + else if (edge === "end") end = Math.max(start + 900000, Math.round((end + Number(minuteOffset) * 60000) / 900000) * 900000) + else { + var date = new Date(start) + date.setDate(date.getDate() + Number(dayOffset)) + if (!event.start.allDay) date.setMinutes(date.getMinutes() + minutes) + var duration = end - start + start = date.getTime() + if (event.start.allDay) { + // All-day duration counts local dates, including 23/25-hour DST days. + var endDate = new Date(end) + endDate.setDate(endDate.getDate() + Number(dayOffset)) + end = endDate.getTime() + } else end = start + duration + } + return isFinite(start) && isFinite(end) && end > start ? { start: start, end: end } : null +} + +// Interval partitioning: every connected overlap group shares its lane count. +// Equal end/start boundaries do not overlap. Long meetings retain their lane +// while shorter neighbours come and go, so cards never cover each other. +function timedLayout(events, day) { + var rows = (events || []).filter(function(event) { return event && event.start && !displayInAllDayLane(event) }).map(function(event) { + return { event: event, start: Math.max(Number(event.start.ms), day.startMs), + end: Math.min(Number(event.end && event.end.ms || event.start.ms + 900000), day.endMs), column: 0, columns: 1 } + }).filter(function(row) { return row.end > row.start }) + rows.sort(function(a, b) { return a.start - b.start || b.end - a.end || eventKey(a.event).localeCompare(eventKey(b.event)) }) + var group = [], ends = [], groupEnd = 0 + function finish() { + for (var j = 0; j < group.length; j++) group[j].columns = ends.length + group = []; ends = []; groupEnd = 0 + } + for (var i = 0; i < rows.length; i++) { + var row = rows[i] + if (group.length && row.start >= groupEnd) finish() + var lane = 0 + while (lane < ends.length && ends[lane] > row.start) lane++ + ends[lane] = row.end + row.column = lane + group.push(row) + groupEnd = Math.max(groupEnd, row.end) + } + finish() + return rows +} + +function attendeeRows(event) { + return (event && Array.isArray(event.attendees) ? event.attendees : []).map(function(attendee) { + var status = String(attendee.responseStatus || attendee.partstat || attendee.status && attendee.status.response || "needsAction").toLowerCase() + var label = status === "accepted" ? "Accepted" : status === "declined" ? "Declined" + : status === "tentative" || status === "tentativelyaccepted" ? "Maybe" : "Awaiting reply" + var email = String(attendee.email || attendee.emailAddress && attendee.emailAddress.address || "") + var name = String(attendee.displayName || attendee.name || attendee.emailAddress && attendee.emailAddress.name || email || "Guest") + return { name: name, email: email, label: label, + symbol: label === "Accepted" ? "βœ“" : label === "Declined" ? "Γ—" : "?", + optional: attendee.optional === true, self: attendee.self === true } + }) +} + +function agendaEvents(events, nowMs) { + return (events || []).filter(function(event) { + if (!event || !event.start) return false + var end = event.end ? Number(event.end.ms) : Number(event.start.ms) + return end > Number(nowMs) + }).sort(compareEvents) +} + +function calendarChoiceRows(groups, editingSource, event) { + var rows = [] + for (var i = 0; i < (groups || []).length; i++) { + var group = groups[i] + var first = true + for (var j = 0; j < (group.calendars || []).length; j++) { + var source = group.calendars[j] + if (event && (!editingSource || String(source.id) !== String(editingSource.id)) + && transferRefusal(editingSource, source, event) !== "") continue + rows.push({ source: source, firstInGroup: first, + groupLabel: String(group.providerLabel || "") + " Β· " + String(group.accountLabel || "") }) + first = false + } + } + return rows +} + +function repeatChoice(event) { + var rules = (event && event.recurrenceLines || []).filter(function(line) { return String(line).indexOf("RRULE:") === 0 }) + if (!rules.length) return "none" + if (rules.length !== 1 || !/^RRULE:FREQ=(DAILY|WEEKLY|MONTHLY|YEARLY)(;(INTERVAL|COUNT)=\d+)*$/.test(rules[0])) return "custom" + return /FREQ=([A-Z]+)/.exec(rules[0])[1] +} + function createEvent(fields, nowMs) { var checked = validateEventFields(fields) if (!checked.ok) return checked @@ -665,9 +883,9 @@ function createEvent(fields, nowMs) { var uid = "omamail-" + Math.floor(Number(nowMs) || Date.now()) var result = { ok: true, uid: uid, - ics: veventLines(uid, 0, Number(nowMs) || Date.now(), checked, recurrence.rule).join("\r\n"), - google: googleEventBody(checked), - graph: graphEventBody(checked), + ics: veventLines(uid, 0, Number(nowMs) || Date.now(), checked, recurrence.rule, fields.allDay === true).join("\r\n"), + google: googleEventBody(checked, fields.allDay === true), + graph: graphEventBody(checked, fields.allDay === true), // Graph spells a series as a structured rule of its own rather than an // RRULE; one is refused there rather than sent wrong. recurring: recurrence.rule !== "" @@ -685,9 +903,51 @@ function createEvent(fields, nowMs) { // RECURRENCE-ID, but its href is still the series' shared file, so it answers // the same way. Creation asks with no event: only the source's own rules // apply. -function writeRefusal(source, event) { +// The confirmation a delete asks for: which event, what goes with it, and +// the answers that differ in consequence. Each choice is one button in the +// dialog, so a guest notification or a whole series is chosen there rather +// than on a row of destructive buttons beside the event. The last choice is +// the default. `value` is the event's `deleteSendUpdates`, or "series". +function deleteRequest(event, source, canReadSeries) { + var value = event || {} + var google = !!source && source.kind === "google" + var notifies = google && !!value.organizer && value.organizer.self === true + && (value.attendees || []).some(function(attendee) { return attendee.self !== true }) + var occurrence = String(value.recurringEventId || "") !== "" + var series = Array.isArray(value.recurrence) && value.recurrence.length > 0 + var choices = [] + var message = "This event will be permanently deleted." + if (occurrence) { + var offerSeries = google && canReadSeries === true + message = offerSeries ? "Delete this occurrence, or every occurrence in the series." + : "This occurrence will be deleted. The rest of the series stays." + if (offerSeries) choices.push({ value: "series", label: "Delete series" }) + if (notifies) { + choices.push({ value: "none", label: "Delete occurrence without email" }) + choices.push({ value: "all", label: "Delete occurrence and notify guests" }) + } else choices.push({ value: "all", label: "Delete occurrence" }) + } else if (notifies) { + message = (series ? "Every occurrence of this series will be deleted. " : "") + + "Guests get a cancellation email unless you delete without one." + choices.push({ value: "none", label: "Delete without email" }) + choices.push({ value: "all", label: "Delete and notify guests" }) + } else { + if (series) message = "Every occurrence of this series will be deleted." + choices.push({ value: "all", label: "Delete" }) + } + return { kind: "event", name: String(value.summary || "Untitled event"), message: message, choices: choices } +} + +function writeRefusal(source, event, operation) { if (!source) return "Choose a calendar" if (source.readOnly === true) return "This calendar is read-only" + if (operation === "reschedule" && source.kind !== "google") + return "Open the event editor to change its time" + if (source.kind === "google" && event && event.eventType === "fromGmail" && operation !== "delete") + return "Google does not allow changing the time or details of events created from Gmail" + if (source.kind === "google" && event && event.organizer && event.organizer.self === false + && event.guestsCanModify !== true && operation !== "delete") + return "Only the organizer can change this event" if (source.kind !== "caldav" && source.kind !== "icloud") return "" // A RECURRENCE-ID too malformed to parse leaves recurrenceIdMs at 0, but // the event's href still names the series' shared file β€” the raw line the @@ -704,9 +964,8 @@ function writeRefusal(source, event) { // bumped SEQUENCE tells every copy of it which write is newer. Recurrence is // not editable here β€” the Google patch omits the key so the server keeps the // rule, and a recurring CalDAV event is refused by writeRefusal before this -// runs. Which shape the event has is likewise not a question an edit answers: -// an all-day event stays VALUE=DATE and a Google date, a timed one stays a -// date-time, so a title-only change cannot turn one into the other. +// runs. An explicit allDay field can change its shape; otherwise preserve the +// original shape so a title-only change cannot turn one into the other. function updateEvent(fields, existing, nowMs) { var event = existing || {} var uid = String(event.uid || "") @@ -714,7 +973,7 @@ function updateEvent(fields, existing, nowMs) { var checked = validateEventFields(fields) if (!checked.ok) return checked var sequence = Math.max(0, Math.floor(Number(event.sequence) || 0)) + 1 - var allDay = !!(event.start && event.start.allDay) + var allDay = fields.allDay === undefined ? !!(event.start && event.start.allDay) : fields.allDay === true var stampMs = Number(nowMs) || Date.now() var original = String(event.calendarData || "") var rewritten = original === "" ? "" : Ics.rewriteEvent(original, uid, @@ -725,7 +984,7 @@ function updateEvent(fields, existing, nowMs) { ok: true, uid: uid, ics: rewritten !== "" ? rewritten : veventLines(uid, sequence, stampMs, checked, "", allDay).join("\r\n"), - google: googleEventBody(checked, allDay), + google: googleEventPatch(checked, allDay, !!(event.start && event.start.allDay)), graph: graphEventBody(checked, allDay) } } @@ -816,6 +1075,15 @@ function caldavEventUrl(sourceUrl, event) { return urlOrigin(resolved) === origin ? resolved : "" } +// Whether two event lists would draw the same. A refresh that brings back what +// is already shown must not hand the views a new array: every Repeater and +// ListView bound to one rebuilds its delegates and loses its scroll position. +function sameEvents(left, right) { + if (left === right) return true + if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false + return JSON.stringify(left) === JSON.stringify(right) +} + function compareEvents(left, right) { var leftMs = left && left.start ? left.start.ms : 0 var rightMs = right && right.start ? right.start.ms : 0 @@ -845,6 +1113,57 @@ function monthDays(year, monthIndex, weekStart) { return out } +function monthGridDays(year, monthIndex, weekStart) { + var days = monthDays(year, monthIndex, weekStart) + return days.slice(0, days.slice(35).some(function(day) { return day.inMonth }) ? 42 : 35) +} + +function monthEventLimit(availableHeight, rowHeight, spacing, overflowHeight, eventCount) { + var capacity = Math.max(0, Math.floor((availableHeight + spacing) / (rowHeight + spacing))) + if (eventCount <= capacity) return capacity + return Math.max(0, Math.floor((availableHeight - overflowHeight) / (rowHeight + spacing))) +} + +function spansMultipleDays(event) { + if (!event || !event.start || !event.end) return false + var start = Number(event.start.ms), end = Number(event.end.ms) + return isFinite(start) && isFinite(end) && end > start + && isoDate(new Date(start)) !== isoDate(new Date(end - 1)) +} + +// Each original event gets one segment per intersected week. Endpoints are +// exclusive, including midnight and all-day ends; titles never identify events. +function monthSpanLayout(events, days) { + return spanLayout((events || []).filter(spansMultipleDays), days) +} + +function spanLayout(events, days) { + var segments = [], laneCounts = [] + var values = (events || []).filter(function(event) { + return event && event.start && event.end && Number(event.end.ms) > Number(event.start.ms) + }).slice().sort(function(a, b) { + return Number(a.start.ms) - Number(b.start.ms) + || Number(b.end.ms) - Number(a.end.ms) || compareEvents(a, b) + }) + for (var week = 0; week < Math.ceil(days.length / 7); week++) { + var first = week * 7, last = Math.min(first + 6, days.length - 1), laneEnds = [] + for (var i = 0; i < values.length; i++) { + var event = values[i], start = Number(event.start.ms), end = Number(event.end.ms) + if (start >= days[last].endMs || end <= days[first].startMs) continue + var left = 0, right = last - first + while (left < last - first && start >= days[first + left].endMs) left++ + while (right > left && end <= days[first + right].startMs) right-- + var lane = 0 + while (lane < laneEnds.length && laneEnds[lane] >= left) lane++ + laneEnds[lane] = right + segments.push({event:event, week:week, startColumn:left, endColumn:right, lane:lane, + continuesBefore:start < days[first].startMs, continuesAfter:end > days[last].endMs}) + } + laneCounts.push(laneEnds.length) + } + return {segments:segments, laneCounts:laneCounts} +} + function weekDays(anchorMs, weekStart) { var anchor = new Date(Number(anchorMs) || Date.now()) var startDay = Math.floor(Number(weekStart)) @@ -901,7 +1220,7 @@ function eventHeight(event, day, hourHeight) { if (!event || !event.start || event.start.allDay) return 0 var start = Math.max(Number(event.start.ms), Number(day.startMs)) var end = event.end ? Math.min(Number(event.end.ms), Number(day.endMs)) : start + 1800000 - return Math.max(Number(hourHeight) * 0.42, + return Math.max(2, (dayMinutes(end, day) - dayMinutes(start, day)) / 60 * Number(hourHeight)) } @@ -953,11 +1272,23 @@ function eventsOnDay(events, day) { return out } +// Presentation only: retain timed endpoints for details, editing and writes. +// Compare local calendar days rather than 24 hours across daylight-saving changes. +function displayInAllDayLane(event) { + if (!event || !event.start) return false + if (event.start.allDay) return true + if (!event.end) return false + var start = new Date(Number(event.start.ms)) + var nextDay = new Date(start.getTime()) + nextDay.setDate(nextDay.getDate() + 1) + return Number(event.end.ms) >= nextDay.getTime() +} + function allDayEventsOnDay(events, day) { var values = eventsOnDay(events, day) var out = [] for (var i = 0; i < values.length; i++) { - if (values[i] && values[i].start && values[i].start.allDay) out.push(values[i]) + if (displayInAllDayLane(values[i])) out.push(values[i]) } return out } @@ -980,7 +1311,7 @@ function weekHourRange(events, days, defaultFirst, defaultLast) { var rangeEnd = Number(week[week.length - 1].endMs) for (var i = 0; i < values.length; i++) { var event = values[i] || {} - if (!event.start || event.start.allDay) continue + if (!event.start || displayInAllDayLane(event)) continue var startMs = Number(event.start.ms) var endMs = event.end ? Number(event.end.ms) : startMs + 1800000 if (startMs >= rangeEnd || endMs <= rangeStart) continue diff --git a/ui/calendar/CalendarCache.qml b/ui/calendar/CalendarCache.qml index 59052a9..55b2cc3 100644 --- a/ui/calendar/CalendarCache.qml +++ b/ui/calendar/CalendarCache.qml @@ -20,8 +20,8 @@ Item { return Cache.eventsFor(store, scope, startMs, endMs, sourceIds) } - function put(scope, startMs, endMs, events) { - store = Cache.putRange(store, scope, startMs, endMs, events, Date.now()) + function put(scope, startMs, endMs, events, refreshedSourceIds) { + store = Cache.putRange(store, scope, startMs, endMs, events, Date.now(), refreshedSourceIds) if (loaded) saveTimer.restart() } diff --git a/ui/calendar/CalendarController.qml b/ui/calendar/CalendarController.qml index b5f2b85..535cf13 100644 --- a/ui/calendar/CalendarController.qml +++ b/ui/calendar/CalendarController.qml @@ -11,6 +11,8 @@ Item { required property var service required property string pluginDir property string cacheName: "calendar" + property bool reminderMode: false + function sourceIncluded(source) { return !!source && (reminderMode ? Sources.nativeCalendarFeatures(source) && source.remindersEnabled === true : source.enabled !== false) } property string accountId: "" property var sourceList: Sources.emptyList() property bool sourcesLoaded: false @@ -18,6 +20,7 @@ Item { property bool loading: false property string lastError: "" property string lastErrorKind: "" + property var undoChange: null property double rangeStart: 0 property double rangeEnd: 0 property double pendingRangeStart: 0 @@ -49,6 +52,8 @@ Item { property int discoverySerial: 0 property bool discoverySaving: false property int discoveryPendingCount: 0 + property var discoveryChoices: null + property string discoveryChoiceAccount: "" property bool clockRunning: false property double nowMs: Date.now() property bool refreshAfterSourceWrite: false @@ -107,7 +112,7 @@ Item { // summaries twice a cycle with no calendar having come or gone, which a // string compares away where the array would not. readonly property string enabledSourceKey: contextSources.sources.filter(function(source) { - return source && source.enabled + return root.sourceIncluded(source) }).map(function(source) { return String(source.id || "") }).join("\n") onEnabledSourceKeyChanged: reloadVisibleRange() @@ -118,7 +123,7 @@ Item { // have been fetched before the cache loaded, because fetching needs it too. function reloadVisibleRange() { if (!rangeStart || !rangeEnd) return - events = cachedEventsFor(calendarScope, rangeStart, rangeEnd) + setEvents(cachedEventsFor(calendarScope, rangeStart, rangeEnd)) refresh(rangeStart, rangeEnd) } @@ -171,11 +176,11 @@ Item { refreshScope = calendarScope var effectiveSources = sourcesForAccount(refreshAccountId) queue = effectiveSources.sources.filter(function(source) { - return source && source.enabled + return root.sourceIncluded(source) }) var sourceIds = queue.map(function(source) { return String(source.id || "") }) - events = eventCache.get(refreshScope, rangeStart, rangeEnd, sourceIds) loading = true + setEvents(eventCache.get(refreshScope, rangeStart, rangeEnd, sourceIds)) processNext() } @@ -192,7 +197,8 @@ Item { var account = accounts[i] || {} if (String(account.id || "") !== String(accountId || "")) continue return account.signedIn === true - && (account.calendarProvider === "microsoft" || account.calendarProvider === "icloud") + && (account.calendarProvider === "microsoft" || account.calendarProvider === "icloud" + || (account.calendarProvider === "google" && service.backendCanGoogleCalendars === true)) } return false } @@ -216,7 +222,7 @@ Item { if (code === "auth_signed_out" || code === "calendar_auth_refused") return "Sign in to this mailbox again" if (code === "calendar_provider_unsupported") - return "This mailbox does not provide iCloud or Microsoft calendars" + return "This mailbox does not support calendar discovery" if (code === "calendar_timeout") return "Calendar discovery timed out" return "Calendars could not be discovered" } @@ -249,6 +255,12 @@ Item { return } var next = Sources.applyDiscovery(root.sourceList, result) + if (result.provider === "google") { + root.discoveryChoiceAccount = wanted + root.discoveryChoices = next + root.discoveryPendingCount = result.calendars.length + return + } root.discoveryPendingCount = result.calendars.length root.discoverySaving = true root.sourceBeingSaved = null @@ -261,18 +273,55 @@ Item { return true } + function chooseDiscovered(id, enabled) { + if (!discoveryChoices) return + var next = Sources.setEnabled(discoveryChoices, id, enabled) + var existing = sourceList.sources.some(function(source) { return source.id === id && source.discovered }) + if (!existing) next.sources = next.sources.map(function(source) { + if (source.id !== id) return source + var value = Sources.makeSource(source) + value.remindersEnabled = enabled === true + return value + }) + discoveryChoices = next + } + + function confirmDiscovery() { + if (!discoveryChoices || savingSource) return + if (!discoverableAccount(discoveryChoiceAccount)) { discoveryChoices = null; return } + var chosen = Sources.copyList(sourceList) + chosen.sources = chosen.sources.filter(function(source) { + return source.kind !== "google" || source.accountId !== root.discoveryChoiceAccount + }) + discoveryChoices.sources.forEach(function(source) { + if (source.kind === "google" && source.accountId === root.discoveryChoiceAccount) chosen = Sources.add(chosen, source) + }) + sourceWritePayload = Sources.serialize(chosen) + discoveryChoices = null + discoverySaving = true + sourceBeingSaved = null + sourceSecret = "" + refreshAfterSourceWrite = true + savingSource = true + writeSources() + } + // `scope` rather than an account id: in the unified view every mailbox reads // the same entry, and asking for it by account would find nothing. function cachedEventsFor(scope, startMs, endMs) { var values = sourcesForAccount(accountId).sources.filter(function(source) { - return source && source.enabled + return root.sourceIncluded(source) }) return eventCache.get(scope, startMs, endMs, values.map(function(source) { return String(source.id || "") })) } function findSource(sourceId) { - var values = contextSources.sources + return sourceById(contextSources, sourceId) + } + + function sourceById(list, sourceId) { + var values = list.sources for (var i = 0; i < values.length; i++) { if (values[i] && values[i].id === String(sourceId)) return values[i] } @@ -289,6 +338,16 @@ Item { if (refusal !== "") { eventCreated(false, refusal); return false } var built = Calendar.createEvent(fields, Date.now()) if (!built.ok) { eventCreated(false, built.error); return false } + if (source.kind === "google") { + var refusedOptions = googleOptionsRefusal(fields) + if (refusedOptions !== "") { eventCreated(false, refusedOptions); return false } + } + if (source.kind === "google" && service.backendCanGoogleCalendars === true) { + var options = Calendar.googleOptions(built.google, fields, source, null) + if (!options.ok) { eventCreated(false, options.error); return false } + built.google = options.body + built.sendUpdates = fields.sendUpdates === "none" ? "none" : "all" + } eventSource = source eventDraft = built creatingEvent = true @@ -313,16 +372,61 @@ Item { if (ok && rangeStart && rangeEnd) refresh(rangeStart, rangeEnd) } + // Guests, Meet and a changed repeat rule reach Google only through the API 6 + // backend, which also carries sendUpdates and If-Match. An older backend + // would save the event without them and report success, so they are + // refused rather than dropped. + function googleOptionsRefusal(fields) { + if (service.backendCanGoogleCalendars === true) return "" + if (fields.createMeet === true || fields.changeRecurrence === true + || String(fields.guestEmails || "").trim() !== "") + return "Update the backend to add guests, Meet or repetition changes" + return "" + } + + // Dragging writes without opening the editor, so it needs the revision + // check only the API 6 backend sends. + function rescheduleRefusal(event) { + var refusal = Calendar.writeRefusal(findSource(event && event.sourceId), event, "reschedule") + if (refusal === "" && service.backendCanGoogleCalendars !== true) + refusal = "Update the backend to move events by dragging" + return refusal + } + function updateEvent(sourceId, event, fields) { if (creatingEvent || eventWriting) { eventUpdated(false, "Another event change is still in progress") return false } var source = findSource(sourceId) + if (source && source.kind === "google" && service.backendCanGoogleCalendars === true && !event.etag) { + eventUpdated(false, "Refresh this event before editing it") + return false + } var refusal = Calendar.writeRefusal(source, event) if (refusal !== "") { eventUpdated(false, refusal); return false } var built = Calendar.updateEvent(fields, event, Date.now()) if (!built.ok) { eventUpdated(false, built.error); return false } + var destination = fields.destinationSourceId && fields.destinationSourceId !== sourceId + ? findSource(fields.destinationSourceId) : null + if (fields.destinationSourceId && fields.destinationSourceId !== sourceId) { + var transferError = Calendar.transferRefusal(source, destination, event) + if (transferError !== "") { eventUpdated(false, transferError); return false } + if (service.backendCanGoogleCalendars !== true) { + eventUpdated(false, "Update the backend to transfer events"); return false + } + built.destination = destination + } + if (source.kind === "google") { + var refusedChange = googleOptionsRefusal(fields) + if (refusedChange !== "") { eventUpdated(false, refusedChange); return false } + } + if (source.kind === "google" && service.backendCanGoogleCalendars === true) { + var options = Calendar.googleOptions(built.google, fields, source, event) + if (!options.ok) { eventUpdated(false, options.error); return false } + built.google = options.body + built.sendUpdates = fields.sendUpdates === "none" ? "none" : "all" + } writeOp = "update" writeSource = source writeEvent = event @@ -334,13 +438,50 @@ Item { return true } + // What the delete confirmation asks: named, with a button per consequence. + function deleteRequest(sourceId, event) { + var request = Calendar.deleteRequest(event, findSource(String(sourceId || "")), + service.backendCanGoogleCalendars === true) + request.sourceId = String(sourceId || "") + request.event = event + return request + } + + // The answer: the series, or this event with or without telling guests. + function confirmDelete(request) { + if (!request || !request.event) return false + if (request.choice === "series") return deleteSeries(request.sourceId, request.event) + var event = {} + for (var key in request.event) event[key] = request.event[key] + event.deleteSendUpdates = request.choice === "none" ? "none" : "all" + return deleteEvent(request.sourceId, event) + } + + // A series is deleted by its own identity: an occurrence carries only the + // parent's id, so the parent is read first and deleted as itself. + function deleteSeries(sourceId, occurrence) { + var owner = findSource(sourceId) + if (!owner || !occurrence || !occurrence.recurringEventId) return false + if (service.backendCanGoogleCalendars !== true) { lastError = "Update the backend to delete a series"; return false } + nativeRequest(owner, "get", { eventId: occurrence.recurringEventId }, function(result, error) { + if (error) { root.lastError = error; return } + var parent + try { parent = JSON.parse(result.body) } catch (e) { root.lastError = "Could not read the series"; return } + var events = Calendar.eventsFromGoogle({ items: [parent] }, owner.id) + if (events.length !== 1) { root.lastError = "Could not read the series"; return } + events[0].deleteSendUpdates = occurrence.deleteSendUpdates === "none" ? "none" : "all" + root.deleteEvent(owner.id, events[0]) + }) + return true + } + function deleteEvent(sourceId, event) { if (creatingEvent || eventWriting) { eventDeleted(false, "Another event change is still in progress") return false } var source = findSource(sourceId) - var refusal = Calendar.writeRefusal(source, event) + var refusal = Calendar.writeRefusal(source, event, "delete") if (refusal !== "") { eventDeleted(false, refusal); return false } writeOp = "delete" writeSource = source @@ -353,6 +494,29 @@ Item { return true } + function transferEvent(sourceId, destinationId, event, callback) { + var source = findSource(sourceId), destination = findSource(destinationId) + var refusal = Calendar.transferRefusal(source, destination, event) + if (creatingEvent || eventWriting) refusal = "Another event change is still in progress" + else if (service.backendCanGoogleCalendars !== true) refusal = "Update the backend to transfer events" + else if (!event || !event.etag) refusal = "Refresh this event before moving it" + if (refusal) { callback(null, refusal); return false } + eventWriting = true + nativeRequest(source, "move", {eventId:event.googleId, destination:destination.calendarId || "primary", + ifMatch:event.etag, sendUpdates:"none"}, function(result, error) { + root.eventWriting = false + if (error) { callback(null, error); return } + root.undoChange = null + var resource = null + try { resource = JSON.parse(result.body) } catch (e) {} + var moved = resource ? Calendar.eventsFromGoogle({items:[resource]}, destination.id) : [] + callback(moved.length === 1 ? moved[0] : null, + moved.length === 1 ? "" : "The calendar changed, but its updated details could not be read. Reopen the event before editing further.", true) + if (root.rangeStart && root.rangeEnd) root.refresh(root.rangeStart, root.rangeEnd) + }) + return true + } + function finishWrite(ok, error) { var op = writeOp eventWriting = false @@ -394,6 +558,13 @@ Item { function nativeRequest(source, operation, fields, callback) { if (!service || !service.backend) { callback(null, "Calendar backend is unavailable"); return } + if (source && source.kind === "google" + && (source.calendarId || ["get", "lookup", "instances", "move"].indexOf(operation) >= 0 + || fields && (fields.ifMatch || fields.sendUpdates !== undefined)) + && service.backendCanGoogleCalendars !== true) { + callback(null, "Update the backend to access Google calendars") + return + } if (source && service.backendCanDiscoverCalendars !== true) { if (source.kind === "microsoft" && String(source.calendarId || "") !== "" && isDefaultMicrosoftCalendar(source)) { @@ -412,7 +583,8 @@ Item { service.backend.call("calendar.request", params, function(result, error) { var reason = "" if (error) { - reason = Calendar.nativeRequestError(String(source && source.kind || "")) + reason = error.message === "calendar_conflict" ? "This event changed elsewhere. Refresh and try again." + : Calendar.nativeRequestError(String(source && source.kind || "")) } callback(result, reason) }) @@ -420,6 +592,8 @@ Item { function createNativeEvent() { var fields = {} + if (eventSource.kind === "google" && service.backendCanGoogleCalendars === true) + fields.sendUpdates = eventDraft.sendUpdates if (eventSource.kind === "caldav" || eventSource.kind === "icloud") { var base = String(eventSource.url || "") if (base.charAt(base.length - 1) !== "/") base += "/" @@ -431,15 +605,78 @@ Item { function startNativeWrite() { var fields = {} + // Undo belongs to the calendar the change was made in: a write that lands + // after the view moved to another account offers nothing to undo there. + var scope = calendarScope if (writeSource.kind === "caldav" || writeSource.kind === "icloud") { fields.href = String(writeEvent.href || Calendar.caldavEventUrl(writeSource.url, writeEvent)) if (!fields.href) { finishWrite(false, "The event's address is outside this calendar's server"); return } if (writeDraft) fields.body = writeDraft.ics } else { fields.eventId = String(writeSource.kind === "google" ? writeEvent.googleId : writeEvent.graphId) + if (writeSource.kind === "google" && writeEvent.etag && service.backendCanGoogleCalendars === true) + fields.ifMatch = writeEvent.etag + if (writeSource.kind === "google" && writeDraft && service.backendCanGoogleCalendars === true) + fields.sendUpdates = writeDraft.sendUpdates + if (writeSource.kind === "google" && writeOp === "delete" && service.backendCanGoogleCalendars === true) + fields.sendUpdates = writeEvent.deleteSendUpdates === "none" ? "none" : "all" if (writeDraft) fields.body = JSON.stringify(writeSource.kind === "google" ? writeDraft.google : writeDraft.graph) } - nativeRequest(writeSource, writeOp, fields, function(result, error) { root.finishWrite(!error, error) }) + nativeRequest(writeSource, writeOp, fields, function(result, error) { + if (!error) root.undoChange = null + if (!error && root.writeOp === "update" && root.writeSource.kind === "google" + && root.service.backendCanGoogleCalendars === true + && root.writeEvent.start && root.writeEvent.end + && !root.writeDraft.destination && !(root.writeEvent.attendees || []).some(function(a) { return a.self !== true }) + && !(root.writeDraft.google.attendees || []).some(function(a) { return a.self !== true })) { + var saved = null + try { saved = JSON.parse(result.body) } catch (e) {} + if (saved && saved.etag) { + var previous = root.writeEvent + var inverse = Calendar.googleEventPatch({ title: previous.summary, description: previous.description, + location: previous.location, start: previous.start.ms, end: previous.end.ms }, previous.start.allDay) + if (root.writeDraft.google.conferenceData) inverse.conferenceData = previous.conferenceData || null + if (root.writeDraft.google.recurrence !== undefined) inverse.recurrence = previous.recurrenceLines || [] + var preserved = ["reminders", "transparency", "visibility", "attendees"] + var completeUndo = true + for (var p = 0; p < preserved.length; p++) { + var field = preserved[p] + if (root.writeDraft.google[field] !== undefined && previous[field] !== undefined) + inverse[field] = previous[field] + else if (root.writeDraft.google[field] !== undefined) completeUndo = false + } + if (!previous.start.allDay && previous.timeZone) { + inverse.start.timeZone = previous.timeZone + inverse.end.timeZone = previous.timeZone + } + if (completeUndo && scope === root.calendarScope) + root.undoChange = { source: root.writeSource, eventId: fields.eventId, ifMatch: saved.etag, + body: JSON.stringify(inverse), sendUpdates: "none", scope: scope } + } + } + if (error || !root.writeDraft || !root.writeDraft.destination) { root.finishWrite(!error, error); return } + var move = { eventId: fields.eventId, destination: root.writeDraft.destination.calendarId || "primary", + sendUpdates: root.writeDraft.sendUpdates } + root.nativeRequest(root.writeSource, "move", move, function(moved, moveError) { + root.finishWrite(!moveError, moveError ? "Changes were saved, but the calendar transfer failed. Refresh before trying again." : "") + if (moveError && root.rangeStart && root.rangeEnd) root.refresh(root.rangeStart, root.rangeEnd) + }) + }) + } + + function undoLastChange() { + if (!undoChange || creatingEvent || eventWriting) return + if (undoChange.scope !== calendarScope) { undoChange = null; return } + if (service.backendCanGoogleCalendars !== true) { lastError = "Update the backend to undo calendar changes"; return } + var change = undoChange + undoChange = null + eventWriting = true + nativeRequest(change.source, "update", { eventId: change.eventId, ifMatch: change.ifMatch, + body: change.body, sendUpdates: change.sendUpdates }, function(result, error) { + root.eventWriting = false + if (root.rangeStart && root.rangeEnd) root.refresh(root.rangeStart, root.rangeEnd) + if (error) root.lastError = error + }) } function saveCalDavPassword(secret) { @@ -516,6 +753,40 @@ Item { return Sources.defaultColorKey(sourceId) } + function setDefaultCalendar(sourceId) { + if (savingSource || discoveringCalendars) return + var chosen = sourceById(availableSources, sourceId) + if (!chosen || chosen.readOnly) return + var next = Sources.add(sourceList, chosen) + next.sources = next.sources.map(function(source) { + var value = Sources.makeSource(source) + if (value.accountId === chosen.accountId) value.preferred = value.id === chosen.id + return value + }) + sourceBeingSaved = null + sourceSecret = "" + sourceWritePayload = Sources.serialize(next) + refreshAfterSourceWrite = false + savingSource = true + writeSources() + } + + function setReminderPolicy(sourceId, enabled, minutes) { + if (savingSource || discoveringCalendars) return + var source = sourceById(availableSources, sourceId) + if (!Sources.nativeCalendarFeatures(source)) return + var value = Sources.makeSource(source) + value.remindersEnabled = enabled === true + value.reminderMinutes = Math.max(-1, Math.min(40320, Math.floor(Number(minutes)))) + if (!isFinite(value.reminderMinutes)) return + sourceWritePayload = Sources.serialize(Sources.add(sourceList, value)) + sourceBeingSaved = null + sourceSecret = "" + refreshAfterSourceWrite = false + savingSource = true + writeSources() + } + function setSourceColor(sourceId, colorKey) { if (savingSource || discoveringCalendars) return var values = availableSources && Array.isArray(availableSources.sources) @@ -656,7 +927,11 @@ Item { next.push(additions[i]) } next.sort(Calendar.compareEvents) - events = next + setEvents(next) + } + + function setEvents(next) { + if (!Calendar.sameEvents(events, next)) events = next } function failSource(reason, kind) { @@ -672,15 +947,16 @@ Item { activeSource = null loading = false var enabled = sourcesForAccount(refreshAccountId).sources.filter(function(source) { - return source && source.enabled + return root.sourceIncluded(source) }).map(function(source) { return String(source.id || "") }) var allowed = {} for (var i = 0; i < enabled.length; i++) allowed[enabled[i]] = true - if (refreshScope === calendarScope) events = events.filter(function(event) { + if (refreshScope === calendarScope) setEvents(events.filter(function(event) { return allowed[String(event && event.sourceId || "")] === true - }) + })) if (rangeStart && rangeEnd && refreshScope === calendarScope) - eventCache.put(refreshScope, rangeStart, rangeEnd, events) + eventCache.put(refreshScope, rangeStart, rangeEnd, events, + contextSources.sources.filter(function(source) { return root.sourceIncluded(source) }).map(function(source) { return String(source.id) })) var nextStart = pendingRangeStart var nextEnd = pendingRangeEnd pendingRangeStart = 0 diff --git a/ui/calendar/CalendarReminderInbox.qml b/ui/calendar/CalendarReminderInbox.qml new file mode 100644 index 0000000..9b8eb9b --- /dev/null +++ b/ui/calendar/CalendarReminderInbox.qml @@ -0,0 +1,53 @@ +import QtQuick + +// The desktop notification is an entry point, not the only action surface. +// Keep delivered reminders actionable until acknowledged or the event ends. +QtObject { + id: root + required property var service + property var records: [] + property var pendingKeys: [] + property string lastError: "" + property int serial: 0 + + function prune(now) { + records = records.filter(function(record) { return Number(record.end) > now }) + } + + function receive(record) { + var next = {} + for (var key in record) next[key] = record[key] + next.noticeId = ++serial + records = records.filter(function(value) { return value.key !== next.key }).concat([next]) + return next + } + + function current(key, noticeId) { + return records.some(function(record) { return record.key === key && record.noticeId === noticeId }) + } + + function action(key, operation, noticeId) { + if (operation !== "snooze" && operation !== "dismiss" && operation !== "failed") return false + if (noticeId !== undefined && !current(key, noticeId)) return false + if (pendingKeys.indexOf(key) >= 0) return false + pendingKeys = pendingKeys.concat([key]) + lastError = "" + service.backend.call("calendar.reminders", { operation: operation, key: key, + now: Date.now(), minutes: service.calendarSnoozeMinutes }, function(result, error) { + root.pendingKeys = root.pendingKeys.filter(function(value) { return value !== key }) + if (error) { root.lastError = "Could not save the reminder action. Try again."; return } + root.records = root.records.filter(function(record) { + return record.key !== key || (noticeId !== undefined && record.noticeId !== noticeId) + }) + }) + return true + } + + function open(record) { + if (!record || !current(record.key, record.noticeId)) return + if (service.shell && typeof service.shell.summon === "function") + service.shell.summon("omamail", JSON.stringify({ view: "calendar", + accountId: record.accountId, eventId: record.sourceId + "\n" + record.eventId, + eventStart: record.start })) + } +} diff --git a/ui/calendar/CalendarReminders.qml b/ui/calendar/CalendarReminders.qml new file mode 100644 index 0000000..cfba82a --- /dev/null +++ b/ui/calendar/CalendarReminders.qml @@ -0,0 +1,108 @@ +import QtQuick +import Quickshell.Io +import "Reminders.js" as Reminders + +Item { + id: root + required property var service + required property string pluginDir + required property string notificationForeground + required property string notificationAccent + property double lastCheck: 0 + property bool polling: false + property int waiters: 0 + property string lastError: "" + property alias inbox: reminderInbox + visible: false + + CalendarReminderInbox { id: reminderInbox; service: root.service } + + function refresh() { + if (!calendars.sourcesLoaded || calendars.loading) return + var today = new Date() + var midnight = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime() + calendars.refresh(midnight - 86400000, midnight + 30 * 86400000) + } + + function action(key, operation) { + reminderInbox.action(key, operation) + } + + function poll() { + if (polling || !calendars.sourcesLoaded || calendars.loading) return + var now = Date.now() + reminderInbox.prune(now) + polling = true + service.backend.call("calendar.reminders", { operation: "poll", now: now, lastCheck: lastCheck, + candidates: Reminders.candidates(calendars.events, calendars.availableSources) }, function(result, error) { + root.polling = false + if (error) { root.lastError = "Desktop reminders could not read their saved state"; return } + if (result && result.retry === true) return + root.lastError = "" + root.lastCheck = now + var notifications = result && Array.isArray(result.notifications) ? result.notifications : [] + for (var i = 0; i < notifications.length; i++) root.deliver(notifications[i]) + }) + } + + function deliver(record) { + var notice = reminderInbox.receive(record) + // The process budget limits desktop waiters, never the actionable inbox. + if (waiters >= 16) return + var body = Qt.formatDateTime(new Date(record.start), "ddd, MMM d Β· hh:mm") + var process = notification.createObject(root, { record: notice, + command: ["python3", pluginDir + "/scripts/notify-mail.py", "--calendar", + notificationForeground, notificationAccent, "--", record.title, body] }) + if (!process) { action(record.key, "failed"); return } + waiters++ + process.running = true + } + + CalendarController { + id: calendars + service: root.service + pluginDir: root.pluginDir + cacheName: "calendar-reminders" + reminderMode: true + onSourcesLoadedChanged: if (sourcesLoaded) Qt.callLater(root.refresh) + onLoadingChanged: if (!loading) Qt.callLater(root.poll) + } + Connections { + target: root.service.calendarController + function onSourceListChanged() { + calendars.sourceList = root.service.calendarController.sourceList + Qt.callLater(root.refresh) + } + } + Timer { interval: 60000; running: true; repeat: true; onTriggered: root.refresh() } + Timer { interval: 30000; running: true; repeat: true; onTriggered: root.poll() } + + Component { + id: notification + Process { + id: delivery + property var record + property Timer deadline: Timer { + interval: 3600000 + running: delivery.running + onTriggered: delivery.running = false + } + stdout: StdioCollector { + onStreamFinished: { + var choice = text.trim() + if (choice === "default") reminderInbox.open(delivery.record) + else if (choice === "snooze" || choice === "dismiss") + reminderInbox.action(delivery.record.key, choice, delivery.record.noticeId) + } + } + onExited: function(code, status) { + root.waiters-- + if (code !== 0) { + root.lastError = "Desktop reminder delivery failed" + reminderInbox.action(record.key, "failed", record.noticeId) + } + destroy() + } + } + } +} diff --git a/ui/calendar/Reminders.js b/ui/calendar/Reminders.js new file mode 100644 index 0000000..2cedbe2 --- /dev/null +++ b/ui/calendar/Reminders.js @@ -0,0 +1,45 @@ +.pragma library + +.import "Sources.js" as Sources + +// Reminder eligibility is independent of whether a calendar is drawn. Inputs +// are normalized calendar resources, not mail's potentially stale invitation. +function candidates(events, sources) { + var byId = {} + var values = sources && Array.isArray(sources.sources) ? sources.sources : [] + for (var i = 0; i < values.length; i++) byId[values[i].id] = values[i] + var out = [], seen = {} + var items = Array.isArray(events) ? events : [] + for (var e = 0; e < items.length; e++) { + var event = items[e], source = event && byId[event.sourceId] + if (!Sources.nativeCalendarFeatures(source) || source.remindersEnabled !== true || !event.start || !event.end + || event.status === "CANCELLED") continue + var accountAddress = String(source.accountId || source.username || "").replace(/^[^:@]+:/, "").toLowerCase() + if ((event.attendees || []).some(function(attendee) { + var own = attendee.self === true || (accountAddress !== "" && String(attendee.email || "").toLowerCase() === accountAddress) + return own && (attendee.responseStatus === "declined" || attendee.partstat === "DECLINED" + || (attendee.status && attendee.status.response === "declined")) + })) continue + var policy = event.reminders || { useDefault: true } + if (policy.useDefault === false && (!Array.isArray(policy.overrides) || policy.overrides.length === 0)) continue + var reminders = policy.useDefault === true ? source.defaultReminders : policy.overrides + if (Number(source.reminderMinutes) >= 0) reminders = [{method:"popup",minutes:Number(source.reminderMinutes)}] + if (!Array.isArray(reminders)) continue + var original = event.originalStartTime || {} + var originalTime = original.dateTime ? Date.parse(String(original.dateTime)) : NaN + var occurrence = String(event.uid || event.googleId || "") + "\n" + + String(event.organizer && event.organizer.email || "").toLowerCase() + "\n" + + String(isFinite(originalTime) ? originalTime : original.date || event.start.ms) + for (var r = 0; r < reminders.length; r++) { + var reminder = reminders[r], minutes = Number(reminder.minutes) + if (reminder.method !== "popup" || !isFinite(minutes) || minutes < 0 || minutes > 40320) continue + var key = occurrence + "\n" + minutes + if (seen[key]) continue + seen[key] = true + out.push({ key: key, occurrence: occurrence, due: Number(event.start.ms) - minutes * 60000, + start: Number(event.start.ms), end: Number(event.end.ms), eventId: String(event.googleId || event.uid || ""), + sourceId: String(source.id), title: String(event.summary || "Event"), accountId: String(source.accountId || "") }) + } + } + return out +} diff --git a/ui/calendar/Sources.js b/ui/calendar/Sources.js index acf3f91..2039cd1 100644 --- a/ui/calendar/Sources.js +++ b/ui/calendar/Sources.js @@ -45,7 +45,14 @@ function makeSource(raw) { accountId: trimmed(value.accountId), enabled: value.enabled !== false, calendarId: trimmed(value.calendarId), readOnly: value.readOnly === true, discovered: value.discovered === true, - colorKey: colorKey + colorKey: colorKey, + accessRole: trimmed(value.accessRole), timeZone: trimmed(value.timeZone), + canCreateMeet: value.canCreateMeet === true, + defaultReminders: Array.isArray(value.defaultReminders) ? value.defaultReminders.slice() : [], + remindersEnabled: value.remindersEnabled === undefined ? value.enabled !== false : value.remindersEnabled === true, + reminderMinutes: isFinite(Number(value.reminderMinutes)) && value.reminderMinutes !== undefined + ? Math.max(-1, Math.min(40320, Math.floor(Number(value.reminderMinutes)))) : -1, + preferred: value.preferred === true } } @@ -166,6 +173,12 @@ function withGoogleAccounts(list, accountSummaries) { break } } + // Discovery's primary entry carries permissions, identity and reminder + // defaults. Never replace it with a synthetic writable primary. + var hasDiscovery = next.sources.some(function(source) { + return source && source.kind === "google" && source.accountId === accountId && source.discovered + }) + if (hasDiscovery) continue next = add(next, { id: "google:" + accountId, kind: "google", @@ -180,7 +193,10 @@ function withGoogleAccounts(list, accountSummaries) { // inherited: keeping the stamp would hide Edit and Delete after an // upgrade. Hand-configured CalDAV sources still keep their own flag. readOnly: false, - colorKey: saved ? saved.colorKey : Palette.defaultKey("google:" + accountId) + colorKey: saved ? saved.colorKey : Palette.defaultKey("google:" + accountId), + remindersEnabled: saved ? saved.remindersEnabled : true, + reminderMinutes: saved ? saved.reminderMinutes : -1, + preferred: saved ? saved.preferred : false }) } return next @@ -220,7 +236,10 @@ function withMicrosoftAccounts(list, accountSummaries) { calendarId: saved ? trimmed(saved.calendarId) : "", readOnly: saved && saved.discovered === true ? saved.readOnly === true : false, discovered: saved ? saved.discovered === true : false, - colorKey: saved ? saved.colorKey : Palette.defaultKey("microsoft:" + accountId) + colorKey: saved ? saved.colorKey : Palette.defaultKey("microsoft:" + accountId), + remindersEnabled: saved ? saved.remindersEnabled : true, + reminderMinutes: saved ? saved.reminderMinutes : -1, + preferred: saved ? saved.preferred : false }) } return next @@ -285,7 +304,7 @@ function applyDiscovery(list, result) { var provider = trimmed(value.provider).toLowerCase() var accountId = trimmed(value.accountId) var kind = provider === "microsoft" ? "microsoft" - : (provider === "icloud" ? "icloud" : "") + : (provider === "icloud" ? "icloud" : (provider === "google" ? "google" : "")) if (kind === "" || accountId === "" || !Array.isArray(value.calendars)) return copyList(list) var current = list && Array.isArray(list.sources) ? list.sources : [] @@ -304,13 +323,19 @@ function applyDiscovery(list, result) { break } } + var initial = kind === "google" ? remote.selected !== false && remote.hidden !== true : true discovered.push(makeSource({ id: id, kind: kind, name: remote.name, accountId: accountId, calendarId: remote.calendarId, url: remote.url, username: remote.username, - enabled: saved ? saved.enabled !== false : true, + enabled: saved ? saved.enabled !== false : initial, readOnly: remote.readOnly === true, discovered: true, - colorKey: saved ? saved.colorKey : Palette.defaultKey(id) + colorKey: saved ? saved.colorKey : Palette.defaultKey(id), + accessRole: remote.accessRole, timeZone: remote.timeZone, + canCreateMeet: remote.canCreateMeet, defaultReminders: remote.defaultReminders, + remindersEnabled: saved ? saved.remindersEnabled : initial, + reminderMinutes: saved ? saved.reminderMinutes : -1, + preferred: saved ? saved.preferred : remote.isDefault === true })) } var next = emptyList() @@ -409,6 +434,12 @@ function writable(source) { return !!source && source.readOnly !== true } +// The redesigned views are shared; deep integration is currently Google-only. +// Other providers retain their existing basic create/edit/delete paths. +function nativeCalendarFeatures(source) { + return !!source && source.kind === "google" +} + // The picker groups with the read-only calendars left out, and a group left // empty by that left out too. function writableGroups(groups) { diff --git a/ui/components/CalendarEventComposer.qml b/ui/components/CalendarEventComposer.qml index 7fbf216..5052991 100644 --- a/ui/components/CalendarEventComposer.qml +++ b/ui/components/CalendarEventComposer.qml @@ -1,8 +1,10 @@ import QtQuick +import QtQuick.Window import QtQuick.Controls as QQC import qs.Commons import qs.Ui import "../calendar/Calendar.js" as Calendar +import "../compose/Recipients.js" as Recipients Rectangle { id: root @@ -18,19 +20,64 @@ Rectangle { property bool opened: false property string selectedSourceId: "" property bool recurring: false + property bool changeRecurrence: false + property bool createMeet: false + property string conferenceRequestId: "" + property string originalGuestText: "" + property bool advancedOptionsOpen: false + readonly property var contactService: controller && controller.service ? controller.service : null + readonly property var contactBook: contactService && Array.isArray(contactService.recipientContacts) + ? contactService.recipientContacts : [] + property bool guestSuggestionsDismissed: false + readonly property var guestSuggestions: opened && guestsField.visible && guestsField.activeFocus && !guestSuggestionsDismissed + ? Recipients.suggest(contactBook, guestsField.text, 5) : [] + readonly property bool guestSuggestionsOpen: guestSuggestions.length > 0 + onGuestSuggestionsChanged: if (guestSuggestionsOpen) Qt.callLater(root.revealField, guestsField) + + function moveGuestSuggestion(delta) { guestSuggestionsList.moveSelection(delta) } + function chooseGuestSuggestion() { guestSuggestionsList.acceptSelection() } + function dismissGuestSuggestions() { guestSuggestionsDismissed = true } + function acceptGuest(contact) { + // Calendar's guest payload accepts addresses, not mail's display-name syntax. + guestsField.text = Recipients.accept(guestsField.text, { email: contact.email }) + ", " + guestsField.forceActiveFocus() + } + property string reminderMode: "default" + property string availability: "opaque" + property string eventVisibility: "default" + property bool visibilityChanged: false + property bool availabilityChanged: false + readonly property var chosenSource: controller && typeof controller.findSource === "function" + ? controller.findSource(selectedSourceId) : null property string recurrenceFrequency: "WEEKLY" // Set while an existing event is being changed rather than a new one made. - // The calendar picker and the recurrence section stand down then: the event - // stays on the calendar that owns it, and the rule is the server's to keep. + // Calendar changes select a transfer destination; they are committed on Save. property var editingEvent: null + property bool loadingSeries: false + property bool transferring: false + property bool transferNeedsRefresh: false + property int editGeneration: 0 + // Google's options travel only through the API 6 backend; an older one + // would save the event without them, so the controls are not offered. + readonly property bool googleWrites: !!chosenSource && chosenSource.kind === "google" + && !!controller && !!controller.service && controller.service.backendCanGoogleCalendars === true + readonly property bool guestUpdate: editing && googleWrites + && !!editingEvent.organizer && editingEvent.organizer.self === true + && ((Array.isArray(editingEvent.attendees) && editingEvent.attendees.some(function(attendee) { return attendee.self !== true })) + || guestsField.text.trim() !== "") property string editingSourceId: "" readonly property bool editing: editingEvent !== null // Nothing typed and nothing being edited: a form that can be replaced // without losing anyone anything. readonly property bool pristine: !editing && !writePending && String(titleField.text || "") === "" && String(locationField.text || "") === "" - && String(notesField.text || "") === "" - onOpenedChanged: if (!opened && controller) controller.composeEnded() + && String(notesField.text || "") === "" && String(guestsField.text || "").trim() === "" + onOpenedChanged: { + guestSuggestionsDismissed = false + if (!opened && controller) controller.composeEnded() + if (opened && contactService && typeof contactService.refreshRecipientContacts === "function") + contactService.refreshRecipientContacts() + } Binding { target: root.controller property: "composerHeld" @@ -43,10 +90,127 @@ Rectangle { property bool writePending: false // An all-day event is edited as the dates it spans; the time fields stand // down, because writing them back would turn the event into a timed one. - readonly property bool editingAllDay: editing - && !!(editingEvent.start && editingEvent.start.allDay) + property bool allDay: false + readonly property bool editingAllDay: allDay + readonly property var dateRange: Calendar.editorDateRange(dateField.text, startField.text, + endDateField.text, endField.text, allDay) color: root.backgroundColor + component FieldLabel: Text { + width: parent.width + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.bodySmall + textFormat: Text.PlainText + wrapMode: Text.Wrap + } + + function revealField(field) { + if (!field.activeFocus) return + var top = field.mapToItem(composerFlick.contentItem, 0, 0).y + var bottom = field === guestsField && guestSuggestionsOpen + ? guestSuggestionsList.mapToItem(composerFlick.contentItem, 0, guestSuggestionsList.height).y + : top + field.height + if (top < composerFlick.contentY) composerFlick.contentY = top + else if (bottom > composerFlick.contentY + composerFlick.height) + composerFlick.contentY = Math.max(0, Math.min(top, bottom - composerFlick.height)) + } + + component EditorField: TextField { + id: input + font.pixelSize: Style.font.bodySmall + onActiveFocusChanged: if (activeFocus) Qt.callLater(root.revealField, input) + } + + component EventOption: QQC.ComboBox { + id: option + property string value: "" + signal chosen(string value) + width: parent.width + implicitHeight: Style.spacing.controlHeight + textRole: "label" + valueRole: "value" + currentIndex: { + for (var i = 0; i < model.length; i++) if (model[i].value === value) return i + return -1 + } + onActivated: function(index) { chosen(String(model[index].value)) } + leftPadding: Style.space(10) + rightPadding: Style.space(30) + contentItem: Text { + text: option.displayText + textFormat: Text.PlainText + elide: Text.ElideRight + verticalAlignment: Text.AlignVCenter + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.body + } + indicator: ActionIcon { + name: "chevronDown" + x: option.width - width - Style.space(10) + y: (option.height - height) / 2 + color: root.dimColor + iconSize: Style.font.iconSmall + } + background: Rectangle { + color: option.popup.opened ? Style.selectedFillFor(root.textColor, root.accentColor) + : Style.normalFillFor(root.textColor, root.accentColor) + border.width: Style.normalBorderWidth + border.color: option.popup.opened ? root.accentColor : Style.normalBorderFor(root.textColor, root.accentColor) + radius: Style.cornerRadius + } + delegate: QQC.ItemDelegate { + id: optionRow + required property var modelData + required property int index + width: option.width + implicitHeight: Style.spacing.controlHeight + highlighted: option.highlightedIndex === index + contentItem: Text { + text: optionRow.modelData.label + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.body + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } + background: Rectangle { + color: optionRow.highlighted ? Style.hoverFillFor(root.textColor, root.accentColor) : "transparent" + } + } + popup: QQC.Popup { + width: option.width + padding: Style.space(4) + implicitHeight: Math.min(optionList.contentHeight + padding * 2, Style.space(280)) + function place() { + var window = option.Window.window + if (!window) return + var point = option.mapToItem(window.contentItem, 0, 0) + var top = point.y + option.height + if (top + height > window.height) top = point.y - height + y = Math.max(0, Math.min(top, window.height - height)) - point.y + x = Math.max(0, Math.min(point.x, window.width - width)) - point.x + } + onOpened: place() + onHeightChanged: if (opened) place() + contentItem: ListView { + id: optionList + clip: true + model: option.popup.visible ? option.delegateModel : null + currentIndex: option.highlightedIndex + QQC.ScrollBar.vertical: QQC.ScrollBar {} + } + background: Rectangle { + color: root.backgroundColor + border.color: Style.normalBorderFor(root.textColor, root.accentColor) + border.width: Style.normalBorderWidth + radius: Style.cornerRadius + } + } + } + function localDate(date) { function two(value) { return value < 10 ? "0" + value : String(value) } return date.getFullYear() + "-" + two(date.getMonth() + 1) + "-" + two(date.getDate()) @@ -58,6 +222,14 @@ Rectangle { } function beginAt(startMs) { + advancedOptionsOpen = false + changeRecurrence = false + visibilityChanged = false + availabilityChanged = false + editGeneration++ + loadingSeries = false + transferring = false + transferNeedsRefresh = false var requested = Number(startMs) var start = isFinite(requested) && requested > 0 ? new Date(requested) : new Date(Date.now() + 3600000) @@ -65,12 +237,22 @@ Rectangle { start.setMinutes(Math.ceil(start.getMinutes() / 30) * 30, 0, 0) var end = new Date(start.getTime() + 3600000) editingEvent = null + allDay = false + createMeet = false + originalGuestText = "" + guestsField.text = "" + reminderMode = "default" + reminderField.text = "10" + availability = "opaque" + eventVisibility = "default" + conferenceRequestId = "omamail-" + Date.now().toString(36) + "-" + Math.random().toString(36).substring(2) editingSourceId = "" writePending = false titleField.text = "" dateField.text = localDate(start) startField.text = localTime(start) endField.text = localTime(end) + endDateField.text = localDate(end) locationField.text = "" notesField.text = "" intervalField.text = "1" @@ -84,6 +266,7 @@ Rectangle { // B would otherwise open with A's calendar chosen and write there unless // the user noticed the picker. selectedSourceId = preferredCalendarId() + timeZoneField.text = chosenSource ? String(chosenSource.timeZone || "") : "" opened = true Qt.callLater(titleField.forceActiveFocus) } @@ -97,6 +280,9 @@ Rectangle { if (wanted !== "") { for (var i = 0; i < groups.length; i++) { if (String(groups[i].id || "") !== "account:" + wanted) continue + for (var c = 0; c < groups[i].calendars.length; c++) { + if (groups[i].calendars[c].preferred) return String(groups[i].calendars[c].id) + } if (groups[i].calendars && groups[i].calendars.length) return String(groups[i].calendars[0].id) } @@ -105,10 +291,29 @@ Rectangle { } function beginEdit(sourceId, event) { + advancedOptionsOpen = !!event && (event.transparency === "transparent" + || event.visibility === "private" || event.visibility === "public") + changeRecurrence = false + visibilityChanged = false + availabilityChanged = false + editGeneration++ + loadingSeries = false + transferring = false + transferNeedsRefresh = false if (!event || !event.start) return var start = new Date(Number(event.start.ms)) var end = event.end ? new Date(Number(event.end.ms)) : new Date(start.getTime() + 3600000) editingEvent = event + allDay = !!(event.start && event.start.allDay) + createMeet = false + originalGuestText = (event.attendees || []).map(function(attendee) { return String(attendee.email || "") }).filter(function(email) { return email !== "" }).join(", ") + guestsField.text = originalGuestText + reminderMode = "preserve" + reminderField.text = "10" + availability = event.transparency || "opaque" + eventVisibility = event.visibility || "default" + timeZoneField.text = String(event.timeZone || "") + conferenceRequestId = "omamail-" + Date.now().toString(36) + "-" + Math.random().toString(36).substring(2) editingSourceId = String(sourceId || "") writePending = false titleField.text = String(event.summary || "") @@ -132,6 +337,16 @@ Rectangle { function begin() { beginAt(0) } + function beginReschedule(event, startMs, endMs) { + beginEdit(event.sourceId, event) + var start = new Date(startMs), end = new Date(endMs) + dateField.text = localDate(start) + startField.text = localTime(start) + endDateField.text = localDate(new Date(allDay ? endMs - 1 : endMs)) + endField.text = localTime(end) + } + + // What the form holds, for a test to read without reaching into fields. function titleText() { return String(titleField.text || "") } function whenText() { return dateField.text + " " + startField.text + " " + endField.text } @@ -145,10 +360,18 @@ Rectangle { var fields = prefill || {} // A form the owner is in the middle of is not replaced. if (opened && !pristine) return false + if (fields.editingEvent) { + beginReschedule(fields.editingEvent, Number(fields.startMs), Number(fields.endMs)) + return true + } beginAt(Number(fields.startMs) || 0) + allDay = fields.allDay === true var start = Number(fields.startMs) || 0 var end = Number(fields.endMs) || 0 - if (start > 0 && end > start) endField.text = localTime(new Date(end)) + if (start > 0 && end > start) { + endField.text = localTime(new Date(end)) + endDateField.text = localDate(new Date(allDay ? end - 1 : end)) + } titleField.text = String(fields.title || "") locationField.text = String(fields.location || "") notesField.text = String(fields.description || "") @@ -164,6 +387,9 @@ Rectangle { if (!accountId || !groups) return "" for (var i = 0; i < groups.length; i++) { if (String(groups[i].id || "") !== "account:" + accountId) continue + for (var c = 0; c < groups[i].calendars.length; c++) { + if (groups[i].calendars[c].preferred) return String(groups[i].calendars[c].id) + } if (groups[i].calendars && groups[i].calendars.length) return String(groups[i].calendars[0].id) } return "" @@ -176,29 +402,89 @@ Rectangle { } function takeFocus() { titleField.forceActiveFocus() } - function submit() { + function editSeries() { + if (!editingEvent || !editingEvent.recurringEventId || loadingSeries || transferring || transferNeedsRefresh || !chosenSource) return + var serial = ++editGeneration + var source = chosenSource + loadingSeries = true + controller.nativeRequest(source, "get", { eventId: editingEvent.recurringEventId }, function(result, error) { + if (serial !== root.editGeneration || !root.opened) return + root.loadingSeries = false + if (error) { resultText.text = error; return } + var payload + try { payload = JSON.parse(result.body) } catch (e) { resultText.text = "Could not read the series"; return } + var events = Calendar.eventsFromGoogle({ items: [payload] }, source.id) + if (events.length !== 1) { resultText.text = "The series is no longer available"; return } + root.beginEdit(source.id, events[0]) + }) + } + + function changeRepeat() { + var lines = editingEvent.recurrenceLines || [] + var rules = lines.filter(function(line) { return String(line).indexOf("RRULE:") === 0 }) + if (rules.length > 1 || (rules.length && !/^RRULE:FREQ=(DAILY|WEEKLY|MONTHLY|YEARLY)(;(INTERVAL|COUNT)=\d+)*$/.test(rules[0]))) { + resultText.text = "This series has an advanced repeat rule. Change its repetition in Google Calendar. Other edits preserve it." + return + } + var rule = rules.length ? rules[0] : "" + var frequency = /FREQ=([A-Z]+)/.exec(rule), interval = /INTERVAL=(\d+)/.exec(rule), count = /COUNT=(\d+)/.exec(rule) + recurring = rule !== "" + recurrenceFrequency = frequency ? frequency[1] : "WEEKLY" + intervalField.text = interval ? interval[1] : "1" + countField.text = count ? count[1] : "" + changeRecurrence = true + } + + function chooseCalendar(sourceId) { + if (transferring || transferNeedsRefresh || writePending || sourceId === selectedSourceId) return + if (!editing) { selectedSourceId = sourceId; return } + var original = editingSourceId + var generation = editGeneration + selectedSourceId = sourceId + transferring = true + resultText.text = "Moving event" + controller.transferEvent(original, sourceId, editingEvent, function(event, error, moved) { + if (generation !== root.editGeneration || !root.opened) return + root.transferring = false + if (error) { + root.transferNeedsRefresh = moved === true + root.selectedSourceId = moved === true ? sourceId : original + resultText.text = error + return + } + root.editingEvent = event + root.editingSourceId = sourceId + resultText.text = "Calendar changed" + }) + } + + function submit(sendUpdates) { if (!controller) return // Create, update and delete share one controller write slot. Do not mark // this form pending unless that slot is free: otherwise an older write's // completion could be mistaken for this form's and close it. - if (controller.creatingEvent || controller.eventWriting) return - var start = new Date(dateField.text + "T" + startField.text + ":00") - var end = new Date(dateField.text + "T" + endField.text + ":00") - if (editingAllDay) { - start = new Date(dateField.text + "T00:00:00") - var lastDay = new Date(endDateField.text + "T00:00:00") - // The written end is exclusive: the midnight after the last shown day, - // reached by date fields so a daylight-saving boundary cannot shift it. - end = new Date(lastDay.getFullYear(), lastDay.getMonth(), lastDay.getDate() + 1) - } + if (controller.creatingEvent || controller.eventWriting || loadingSeries || transferring || transferNeedsRefresh) return + if (!dateRange.ok) return var fields = { title: titleField.text, - startMs: start.getTime(), - endMs: end.getTime(), + allDay: allDay, + startMs: dateRange.startMs, + endMs: dateRange.endMs, location: locationField.text, description: notesField.text, + createMeet: createMeet, + conferenceRequestId: conferenceRequestId, + destinationSourceId: selectedSourceId, + sendUpdates: sendUpdates === "none" ? "none" : "all", + timeZone: timeZoneField.text.trim(), + guestEmails: !editing || guestsField.text !== originalGuestText ? guestsField.text : undefined, + transparency: !editing || availabilityChanged ? availability : undefined, + visibility: !editing || visibilityChanged ? eventVisibility : undefined, + reminderMode: reminderMode, + reminderMinutes: reminderField.text, + changeRecurrence: changeRecurrence, recurrence: { - enabled: recurring, + enabled: recurring && !!chosenSource && chosenSource.kind !== "microsoft", frequency: recurrenceFrequency, interval: intervalField.text, count: countField.text @@ -221,10 +507,14 @@ Rectangle { Flickable { id: composerFlick + objectName: "event-composer-scroll" WheelScroller { view: composerFlick } - anchors.fill: parent + anchors.top: parent.top + anchors.left: parent.left + anchors.right: parent.right + anchors.bottom: editorFooter.top anchors.margins: Style.space(18) contentWidth: width contentHeight: form.implicitHeight @@ -247,7 +537,8 @@ Rectangle { } Text { - text: root.editingAllDay ? "Edit event Β· All day" + text: root.editing && root.editingEvent.recurringEventId ? "Edit this occurrence" + : root.editing && root.editingEvent.recurrence ? "Edit entire series" : root.editing ? "Edit event" : "Create event" color: root.textColor font.family: root.panelFontFamily @@ -256,173 +547,434 @@ Rectangle { textFormat: Text.PlainText } - Text { - visible: !root.editing - text: "CALENDAR" - color: root.dimColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.caption - font.letterSpacing: 1 - textFormat: Text.PlainText - } - - Repeater { - model: root.editing ? [] : (root.controller ? root.controller.writableSourceGroups : []) + FieldLabel { text: "Calendar" } - delegate: Column { - id: sourceGroup + QQC.ComboBox { + id: calendarSelector + objectName: "event-calendar-selector" + width: parent.width + implicitHeight: Style.spacing.controlHeight + enabled: count > 0 && !root.writePending && !root.transferring && !root.transferNeedsRefresh + model: Calendar.calendarChoiceRows(root.controller ? root.controller.writableSourceGroups : [], + root.editing && root.controller && typeof root.controller.findSource === "function" + ? root.controller.findSource(root.editingSourceId) : null, root.editingEvent) + currentIndex: { + for (var i = 0; i < model.length; i++) + if (String(model[i].source.id) === root.selectedSourceId) return i + return -1 + } + onActivated: function(index) { root.chooseCalendar(String(model[index].source.id)) } + readonly property var choice: currentIndex >= 0 && currentIndex < model.length ? model[currentIndex] : null + Accessible.name: "Calendar" + leftPadding: Style.space(30) + rightPadding: Style.space(32) + contentItem: Text { + text: calendarSelector.choice ? String(calendarSelector.choice.source.name || calendarSelector.choice.source.id) : "Choose a calendar" + textFormat: Text.PlainText + elide: Text.ElideMiddle + verticalAlignment: Text.AlignVCenter + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.body + } + Rectangle { + x: Style.space(12) + anchors.verticalCenter: parent.verticalCenter + width: Style.space(8) + height: width + radius: width / 2 + color: calendarPalette.colorFor(calendarSelector.choice ? calendarSelector.choice.source.colorKey : "accent") + } + indicator: ActionIcon { + name: "chevronDown" + x: calendarSelector.width - width - Style.space(10) + y: (calendarSelector.height - height) / 2 + color: root.dimColor + iconSize: Style.font.iconSmall + } + background: Rectangle { + color: calendarSelector.popup.opened ? Style.selectedFillFor(root.textColor, root.accentColor) + : calendarSelector.hovered ? Style.hoverFillFor(root.textColor, root.accentColor) + : Style.normalFillFor(root.textColor, root.accentColor) + border.width: Style.normalBorderWidth + border.color: calendarSelector.popup.opened ? root.accentColor : Style.normalBorderFor(root.textColor, root.accentColor) + radius: Style.cornerRadius + } + delegate: QQC.ItemDelegate { + id: calendarOption + objectName: "event-calendar-option-" + index required property var modelData - width: form.width - spacing: Style.space(4) - - Text { - width: parent.width - text: sourceGroup.modelData.providerLabel + " Β· " - + sourceGroup.modelData.accountLabel - color: root.dimColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.caption - elide: Text.ElideMiddle - textFormat: Text.PlainText - } - - Flow { - width: parent.width - height: childrenRect.height - spacing: Style.space(5) - - Repeater { - model: sourceGroup.modelData.calendars - - IconTextButton { - required property var modelData - text: String(modelData.name || modelData.id || "Calendar") - selected: root.selectedSourceId === String(modelData.id) - foreground: root.textColor - accent: calendarPalette.colorFor(modelData.colorKey) - fontFamily: root.panelFontFamily - onClicked: root.selectedSourceId = String(modelData.id) + required property int index + width: calendarSelector.popup.availableWidth + implicitHeight: optionContent.implicitHeight + Style.space(12) + highlighted: calendarSelector.highlightedIndex === index + padding: Style.space(6) + contentItem: Column { + id: optionContent + spacing: Style.space(8) + Text { + width: parent.width + visible: calendarOption.modelData.firstInGroup + text: calendarOption.modelData.groupLabel + textFormat: Text.PlainText + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.Wrap + MouseArea { anchors.fill: parent } + } + Row { + width: parent.width + spacing: Style.space(8) + Rectangle { + anchors.verticalCenter: parent.verticalCenter + width: Style.space(8) + height: width + radius: width / 2 + color: calendarPalette.colorFor(calendarOption.modelData.source.colorKey) + } + Text { + width: parent.width - Style.space(40) + text: String(calendarOption.modelData.source.name || calendarOption.modelData.source.id) + textFormat: Text.PlainText + elide: Text.ElideMiddle + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.body + } + Text { + text: root.selectedSourceId === String(calendarOption.modelData.source.id) ? "βœ“" : "" + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily } } } + background: Rectangle { + color: calendarOption.highlighted ? Style.hoverFillFor(root.textColor, root.accentColor) : "transparent" + radius: Style.cornerRadius + } + } + popup: QQC.Popup { + width: calendarSelector.width + padding: Style.space(6) + implicitHeight: Math.min(calendarOptions.contentHeight + padding * 2, Style.space(320)) + function place() { + var window = calendarSelector.Window.window + if (!window) return + var point = calendarSelector.mapToItem(window.contentItem, 0, 0) + var top = point.y + calendarSelector.height + if (top + height > window.height) top = point.y - height + y = Math.max(0, Math.min(top, window.height - height)) - point.y + x = Math.max(0, Math.min(point.x, window.width - width)) - point.x + } + onOpened: place() + onHeightChanged: if (opened) place() + contentItem: ListView { + id: calendarOptions + clip: true + model: calendarSelector.popup.visible ? calendarSelector.delegateModel : null + currentIndex: calendarSelector.highlightedIndex + boundsBehavior: Flickable.StopAtBounds + QQC.ScrollBar.vertical: QQC.ScrollBar {} + } + background: Rectangle { + color: root.backgroundColor + border.width: Style.normalBorderWidth + border.color: Style.normalBorderFor(root.textColor, root.accentColor) + radius: Style.cornerRadius + } } } - TextField { + FieldLabel { text: "Title" } + EditorField { id: titleField + objectName: "event-title-field" width: parent.width foreground: root.textColor accent: root.accentColor font.family: root.panelFontFamily placeholderText: "Event title" + Accessible.name: "Event title" } - Row { + Column { width: parent.width - spacing: Style.space(8) - - TextField { - id: dateField - width: root.editingAllDay ? (parent.width - parent.spacing) * 0.5 - : (parent.width - parent.spacing * 2) * 0.5 + spacing: Style.space(6) + FieldLabel { text: "Description" } + EditorField { + id: notesField + objectName: "event-description-field" + width: parent.width foreground: root.textColor + accent: root.accentColor font.family: root.panelFontFamily - placeholderText: root.editingAllDay ? "First day (YYYY-MM-DD)" : "YYYY-MM-DD" + placeholderText: "Add event details" + Accessible.name: "Description" } + } - TextField { - id: endDateField - visible: root.editingAllDay - width: (parent.width - parent.spacing) * 0.5 + IconTextButton { + visible: root.editing && !!root.editingEvent.recurringEventId + && root.googleWrites + text: root.loadingSeries ? "Loading series" : "Edit entire series..." + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + enabled: !root.loadingSeries && !root.writePending + onClicked: root.editSeries() + } + + IconTextButton { + text: root.allDay ? "βœ“ All day" : "All day" + selected: root.allDay + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + onClicked: root.allDay = !root.allDay + } + + // Labelled above like every other field, so the form has one left edge. + FieldLabel { text: "Starts" } + Row { + width: parent.width + spacing: Style.space(8) + EditorField { + id: dateField + objectName: "event-start-date-field" + width: parent.width - (startField.visible ? startField.width + parent.spacing : 0) foreground: root.textColor font.family: root.panelFontFamily - placeholderText: "Last day (YYYY-MM-DD)" + placeholderText: root.editingAllDay ? "First day (YYYY-MM-DD)" : "YYYY-MM-DD" } - TextField { + EditorField { id: startField + objectName: "event-start-time-field" visible: !root.editingAllDay - width: (parent.width - parent.spacing * 2) * 0.25 + width: Style.space(120) foreground: root.textColor font.family: root.panelFontFamily placeholderText: "Start" } - - TextField { + } + FieldLabel { text: root.allDay ? "Last day" : "Ends" } + Row { + width: parent.width + spacing: Style.space(8) + EditorField { + id: endDateField + objectName: "event-end-date-field" + width: parent.width - (endField.visible ? endField.width + parent.spacing : 0) + foreground: root.textColor + font.family: root.panelFontFamily + placeholderText: "YYYY-MM-DD" + } + EditorField { id: endField + objectName: "event-end-time-field" visible: !root.editingAllDay - width: (parent.width - parent.spacing * 2) * 0.25 + width: Style.space(120) foreground: root.textColor font.family: root.panelFontFamily placeholderText: "End" } } - TextField { - id: locationField + Text { + objectName: "event-date-range-error" width: parent.width - foreground: root.textColor + visible: !root.dateRange.ok + text: root.dateRange.error + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.urgentColor font.family: root.panelFontFamily - placeholderText: "Location or meeting link" + font.pixelSize: Style.font.caption + } + + Text { + visible: !root.allDay && root.dateRange.ok + text: "Times shown in " + Qt.formatDateTime(new Date(root.dateRange.startMs || Date.now()), "t") + " (local time)" + textFormat: Text.PlainText + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption } - TextField { - id: notesField + FieldLabel { text: "Location or meeting link" } + EditorField { + id: locationField + objectName: "event-location-field" width: parent.width foreground: root.textColor font.family: root.panelFontFamily - placeholderText: "Notes" + placeholderText: "Room, address or link" + Accessible.name: "Location or meeting link" } IconTextButton { - visible: !root.editing - text: "Make recurring" - iconName: root.recurring ? "check" : "" - selected: root.recurring - foreground: root.recurring ? root.textColor : root.dimColor + objectName: "event-add-meet" + visible: root.googleWrites && root.chosenSource.canCreateMeet === true + && !(root.editingEvent && root.editingEvent.conferenceData) + text: root.createMeet ? "βœ“ Add Google Meet" : "Add Google Meet" + selected: root.createMeet + foreground: root.textColor accent: root.accentColor fontFamily: root.panelFontFamily - onClicked: root.recurring = !root.recurring + onClicked: root.createMeet = !root.createMeet } Column { width: parent.width - visible: root.recurring && !root.editing - spacing: Style.space(8) - - Text { - text: "REPEATS" - color: root.dimColor + spacing: Style.space(6) + visible: root.googleWrites + FieldLabel { text: "Guests"; visible: guestsField.visible } + EditorField { + id: guestsField + objectName: "event-guests-field" + width: parent.width + visible: !root.editing || (!!root.editingEvent.organizer && root.editingEvent.organizer.self === true) + placeholderText: "Guest email addresses, separated by commas" + foreground: root.textColor + accent: root.accentColor font.family: root.panelFontFamily - font.pixelSize: Style.font.caption - font.letterSpacing: 1 - textFormat: Text.PlainText + Accessible.name: "Guest email addresses" + onTextChanged: root.guestSuggestionsDismissed = false + onActiveFocusChanged: { + root.guestSuggestionsDismissed = false + if (activeFocus) Qt.callLater(root.revealField, guestsField) + } } - + RecipientSuggestions { + id: guestSuggestionsList + onHeightChanged: if (root.guestSuggestionsOpen) Qt.callLater(root.revealField, guestsField) + onYChanged: if (root.guestSuggestionsOpen) Qt.callLater(root.revealField, guestsField) + objectName: "event-guest-suggestions" + width: parent.width + contacts: root.guestSuggestions + textColor: root.textColor + dimColor: root.dimColor + accentColor: root.accentColor + popupBackgroundColor: root.backgroundColor + popupBorderColor: Style.normalBorderFor(root.textColor, root.accentColor) + panelFontFamily: root.panelFontFamily + onChosen: function(contact) { root.acceptGuest(contact) } + } + IconTextButton { + objectName: "event-more-options" + text: "More options..." + selected: root.advancedOptionsOpen + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + onClicked: root.advancedOptionsOpen = !root.advancedOptionsOpen + } + Column { + width: parent.width + spacing: Style.space(6) + visible: root.advancedOptionsOpen + FieldLabel { text: "Time zone for repeating events" } + EditorField { + id: timeZoneField + width: parent.width + placeholderText: "e.g. Europe/Paris" + foreground: root.textColor + accent: root.accentColor + font.family: root.panelFontFamily + Accessible.name: "Time zone for repeating events" + } + Text { + width: parent.width + text: "Repeating events follow this time zone. Dates and times above use your computer's local time." + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + FieldLabel { text: "Availability" } + EventOption { + objectName: "event-availability-selector" + value: root.availability + model: [{value:"opaque",label:"Busy β€” blocks this time"},{value:"transparent",label:"Free β€” keeps this time available"}] + onChosen: function(value) { root.availability = value; root.availabilityChanged = true } + } + FieldLabel { text: "Visibility" } + EventOption { + objectName: "event-visibility-selector" + value: root.eventVisibility + model: [{value:"default",label:"Calendar default"},{value:"public",label:"Public"},{value:"private",label:"Private"}] + onChosen: function(value) { root.eventVisibility = value; root.visibilityChanged = true } + } + } + FieldLabel { text: "Event reminders" } Flow { width: parent.width - height: childrenRect.height - spacing: Style.space(5) - + spacing: Style.space(6) Repeater { - model: [ - { label: "Daily", value: "DAILY" }, - { label: "Weekly", value: "WEEKLY" }, - { label: "Monthly", value: "MONTHLY" }, - { label: "Yearly", value: "YEARLY" } - ] - + model: root.editing ? ["preserve", "default", "none", "custom"] : ["default", "none", "custom"] IconTextButton { - required property var modelData - text: modelData.label - selected: root.recurrenceFrequency === modelData.value - foreground: selected ? root.textColor : root.dimColor + required property string modelData + text: modelData === "preserve" ? "Keep existing" : modelData === "default" ? "Calendar default" + : modelData === "none" ? "None" : "Custom reminder" + selected: root.reminderMode === modelData + foreground: root.textColor accent: root.accentColor fontFamily: root.panelFontFamily - onClicked: root.recurrenceFrequency = modelData.value + onClicked: root.reminderMode = modelData } } } + Row { + visible: root.reminderMode === "custom" + width: parent.width + spacing: Style.space(8) + EditorField { + id: reminderField + width: Style.space(80) + placeholderText: "Minutes" + foreground: root.textColor + accent: root.accentColor + font.family: root.panelFontFamily + inputMethodHints: Qt.ImhDigitsOnly + Accessible.name: "Reminder minutes before the event" + } + FieldLabel { + width: parent.width - reminderField.width - parent.spacing + anchors.verticalCenter: parent.verticalCenter + text: "minutes before the event" + } + } + } + + Column { + width: parent.width + spacing: Style.space(6) + visible: (!root.editing && !!root.chosenSource && root.chosenSource.kind !== "microsoft") + || (root.editing && !root.editingEvent.recurringEventId && root.googleWrites) + FieldLabel { text: "Repeat" } + EventOption { + objectName: "event-repeat-selector" + value: root.editing && !root.changeRecurrence ? Calendar.repeatChoice(root.editingEvent) + : root.recurring ? root.recurrenceFrequency : "none" + model: [{value:"none",label:"Does not repeat"},{value:"DAILY",label:"Daily"}, + {value:"WEEKLY",label:"Weekly"},{value:"MONTHLY",label:"Monthly"},{value:"YEARLY",label:"Yearly"}] + .concat(root.editing && Calendar.repeatChoice(root.editingEvent) === "custom" ? [{value:"custom",label:"Custom schedule (edit in Google Calendar)"}] : []) + onChosen: function(value) { + if (root.editing && !root.changeRecurrence) root.changeRepeat() + if (value === "custom" || (root.editing && !root.changeRecurrence)) return + root.recurring = value !== "none" + if (root.recurring) root.recurrenceFrequency = value + } + } + } + + Column { + width: parent.width + visible: root.recurring && !!root.chosenSource && root.chosenSource.kind !== "microsoft" && (!root.editing || root.changeRecurrence) + spacing: Style.space(8) Row { width: parent.width @@ -444,7 +996,7 @@ Rectangle { width: parent.width spacing: Style.space(8) - TextField { + EditorField { id: intervalField width: Math.min(Style.space(96), parent.width * 0.5) foreground: root.textColor @@ -476,7 +1028,7 @@ Rectangle { textFormat: Text.PlainText } - TextField { + EditorField { id: countField width: parent.width foreground: root.textColor @@ -488,43 +1040,70 @@ Rectangle { } } - Row { - spacing: Style.space(6) + } + } - IconTextButton { - text: { - var busy = root.controller - && (root.controller.creatingEvent || root.controller.eventWriting) - if (root.editing) return busy ? "Saving" : "Save changes" - return busy ? "Creating" : "Create event" - } - iconName: root.editing ? "check" : "plus" - foreground: root.textColor - accent: root.accentColor - fontFamily: root.panelFontFamily - enabled: root.controller && !root.controller.creatingEvent - && !root.controller.eventWriting - onClicked: root.submit() - } + Column { + id: editorFooter + objectName: "event-editor-footer" + anchors.horizontalCenter: parent.horizontalCenter + anchors.bottom: parent.bottom + anchors.bottomMargin: Style.space(18) + width: Math.min(parent.width - Style.space(36), Style.space(620)) + spacing: Style.space(10) - IconTextButton { - text: "Cancel" - bordered: false - foreground: root.dimColor - fontFamily: root.panelFontFamily - onClicked: root.close() + PanelSeparator { width: parent.width; foreground: root.textColor } + + Text { + id: resultText + objectName: "event-save-error" + width: parent.width + visible: text !== "" + color: root.urgentColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.Wrap + textFormat: Text.PlainText + } + + Flow { + width: parent.width + spacing: Style.space(6) + + IconTextButton { + objectName: "event-save-button" + text: { + var busy = root.controller + && (root.controller.creatingEvent || root.controller.eventWriting) + if (root.editing) return busy ? "Saving" : root.guestUpdate ? "Send update" : "Save changes" + return busy ? "Creating" : "Create event" } + iconName: root.editing ? "check" : "plus" + // The Enter action: accent edge and text, not a solid fill. + foreground: root.accentColor + accent: root.accentColor + fontFamily: root.panelFontFamily + enabled: root.controller && !root.controller.creatingEvent + && !root.controller.eventWriting && !root.loadingSeries && root.dateRange.ok + onClicked: root.submit("all") } - Text { - id: resultText - width: parent.width - visible: text !== "" - color: root.accentColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.caption - wrapMode: Text.WordWrap - textFormat: Text.PlainText + IconTextButton { + visible: root.guestUpdate + text: "Save without email" + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + enabled: !root.writePending && !root.loadingSeries && root.dateRange.ok + onClicked: root.submit("none") + } + + IconTextButton { + text: "Cancel" + bordered: false + foreground: root.dimColor + fontFamily: root.panelFontFamily + onClicked: root.close() } } } diff --git a/ui/components/CalendarEventDetail.qml b/ui/components/CalendarEventDetail.qml index 8f1c050..20a22c5 100644 --- a/ui/components/CalendarEventDetail.qml +++ b/ui/components/CalendarEventDetail.qml @@ -21,7 +21,15 @@ Rectangle { signal closed() signal editRequested(string sourceId, var event) signal deleteRequested(string sourceId, var event) - + property bool refreshing: false + property string refreshError: "" + property bool meetingLinkCopied: false + onMeetingLinkChanged: { meetingLinkCopied = false; copiedFeedback.stop() } + Timer { + id: copiedFeedback + interval: 2000 + onTriggered: root.meetingLinkCopied = false + } readonly property var source: { var sources = controller && controller.availableSources ? controller.availableSources.sources : [] @@ -38,7 +46,7 @@ Rectangle { // carries only a RECURRENCE-ID, but its href is the series' shared file β€” // and an href that resolves outside the source's own origin is refused by // the same rule the controller applies before any credential is read. - readonly property bool canWrite: !!root.source && !!event + readonly property bool canDelete: !!root.source && !!event && root.source.readOnly !== true && (root.source.kind === "google" ? String(event.googleId || "") !== "" : root.source.kind === "microsoft" ? String(event.graphId || "") !== "" @@ -46,9 +54,13 @@ Rectangle { && Number(event.recurrenceIdMs || 0) <= 0 && String(event.source && event.source.recurrenceId || "") === "" && Calendar.caldavEventUrl(root.source.url, event) !== "") + readonly property bool canWrite: canDelete && Calendar.writeRefusal(source, event) === "" readonly property color eventColor: calendarPalette.colorFor( source ? source.colorKey : "accent") readonly property string meetingLink: httpLink(event ? event.meetLink : "") + readonly property string conferenceStatus: String(event && event.conferenceData + && event.conferenceData.createRequest && event.conferenceData.createRequest.status + ? event.conferenceData.createRequest.status.statusCode || "" : "") readonly property string locationLink: httpLink(event ? event.location : "") // The location as written. One that is not a link is a place, and a place // is something to copy into a message or to look up on a map. @@ -120,11 +132,15 @@ Rectangle { onActivated: root.closed() } - Rectangle { + CalendarReminderPanel { width: parent.width - height: Style.space(4) - radius: height / 2 - color: root.eventColor + service: root.controller ? root.controller.service : null + eventKey: root.event ? String(root.event.sourceId || "") + "\n" + String(root.event.googleId || root.event.uid || "") : "" + textColor: root.textColor + dimColor: root.dimColor + accentColor: root.accentColor + urgentColor: root.urgentColor + panelFontFamily: root.panelFontFamily } Text { @@ -171,6 +187,29 @@ Rectangle { } } + Flow { + width: parent.width + spacing: Style.space(8) + IconTextButton { + visible: root.meetingLink !== "" + text: "Join meeting..." + iconName: "video" + foreground: root.textColor + accent: root.eventColor + fontFamily: root.panelFontFamily + onClicked: if (root.controller) root.controller.openExternal(root.meetingLink) + } + IconTextButton { + visible: root.canWrite + text: "Edit..." + iconName: "edit" + foreground: root.textColor + accent: root.eventColor + fontFamily: root.panelFontFamily + onClicked: root.editRequested(String(root.event.sourceId || ""), root.event) + } + } + Row { visible: String(root.event && root.event.location || "") !== "" width: parent.width @@ -194,41 +233,182 @@ Rectangle { } } - Flow { - visible: root.meetingLink !== "" || root.locationLink !== "" - || root.providerLink !== "" || root.canWrite || root.locationText !== "" + Text { width: parent.width - spacing: Style.space(7) + visible: root.refreshing || root.refreshError !== "" + text: root.refreshing ? "Refreshing event details..." : root.refreshError + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.refreshError !== "" ? root.urgentColor : root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } - IconTextButton { - visible: root.canWrite - text: "Edit..." - iconName: "edit" - foreground: root.textColor - accent: root.eventColor - fontFamily: root.panelFontFamily - onClicked: root.editRequested(String(root.event.sourceId || ""), root.event) + Column { + width: parent.width + spacing: Style.space(6) + visible: root.meetingLink !== "" + Text { + text: "Meeting link" + textFormat: Text.PlainText + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption } - - IconTextButton { - visible: root.canWrite - text: "Delete..." - iconName: "trash" - foreground: root.urgentColor - accent: root.urgentColor - fontFamily: root.panelFontFamily - onClicked: root.deleteRequested(String(root.event.sourceId || ""), root.event) + Row { + width: parent.width + spacing: Style.space(10) + AbstractButton { + objectName: "event-meeting-link" + width: Math.max(0, Math.min(contentItem.implicitWidth, + parent.width - copyMeetingLink.width - copiedLabel.width - parent.spacing * 2)) + implicitHeight: Math.max(contentItem.implicitHeight, copyMeetingLink.height) + text: root.meetingLink + Accessible.role: Accessible.Link + Accessible.name: root.meetingLink + contentItem: Text { + text: root.meetingLink + textFormat: Text.PlainText + wrapMode: Text.WrapAnywhere + verticalAlignment: Text.AlignVCenter + color: root.accentColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.body + font.underline: true + } + onClicked: if (root.controller) root.controller.openExternal(root.meetingLink) + HoverHandler { cursorShape: Qt.PointingHandCursor } + } + IconButton { + id: copyMeetingLink + objectName: "event-copy-meeting-link" + iconName: root.meetingLinkCopied ? "check" : "copy" + tooltipText: root.meetingLinkCopied ? "Copied" : "Copy meeting link" + foreground: root.meetingLinkCopied ? root.accentColor : root.dimColor + hoverColor: root.textColor + fontFamily: root.panelFontFamily + onClicked: { + if (root.controller && root.controller.copyText(root.meetingLink)) { + root.meetingLinkCopied = true + copiedFeedback.restart() + } + } + } + Text { + id: copiedLabel + anchors.verticalCenter: parent.verticalCenter + text: "Copied" + opacity: root.meetingLinkCopied ? 1 : 0 + textFormat: Text.PlainText + color: root.accentColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } } + } - IconTextButton { - visible: root.meetingLink !== "" - text: "Join call" - iconName: "video" - foreground: root.textColor - accent: root.eventColor - fontFamily: root.panelFontFamily - onClicked: if (root.controller) root.controller.openExternal(root.meetingLink) + Text { + width: parent.width + visible: !!root.event && root.event.eventType === "fromGmail" + text: "Created automatically from Gmail. Google does not allow apps to change its time or event details." + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.body + } + + Text { + visible: String(root.event && root.event.description || "") !== "" + width: parent.width + text: String(root.event && root.event.description || "") + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.body + lineHeight: 1.35 + wrapMode: Text.Wrap + textFormat: Text.PlainText + } + + Column { + width: parent.width + spacing: Style.space(8) + visible: attendeeList.count > 0 + Text { + text: "Guests Β· " + attendeeList.count + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.bold: true + font.pixelSize: Style.font.body } + Repeater { + id: attendeeList + model: Calendar.attendeeRows(root.event) + delegate: Rectangle { + required property var modelData + width: parent.width + height: guestInfo.implicitHeight + Style.space(16) + radius: Style.cornerRadius + color: Qt.alpha(root.textColor, 0.04) + Row { + id: guestInfo + x: Style.space(10) + y: Style.space(8) + width: parent.width - Style.space(20) + spacing: Style.space(10) + Text { + width: Style.space(20) + text: modelData.symbol + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.body + } + Column { + width: parent.width - Style.space(30) + spacing: Style.space(3) + Text { + width: parent.width + text: modelData.name + (modelData.self ? " (you)" : "") + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.bodySmall + } + Text { + width: parent.width + text: modelData.label + (modelData.optional ? " Β· Optional" : "") + + (modelData.email && modelData.email !== modelData.name ? " Β· " + modelData.email : "") + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + } + } + } + } + } + + Text { + width: parent.width + visible: root.conferenceStatus === "pending" || root.conferenceStatus === "failure" + text: root.conferenceStatus === "pending" ? "Google Meet is being created. Refresh to check its status." + : "The event was saved, but Google Meet could not be created." + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.dimColor + font.family: root.panelFontFamily + } + + Flow { + visible: root.meetingLink !== "" || root.locationLink !== "" + || root.providerLink !== "" || root.canDelete || root.locationText !== "" + width: parent.width + spacing: Style.space(7) IconTextButton { visible: root.locationLink !== "" && root.locationLink !== root.meetingLink @@ -255,7 +435,7 @@ Rectangle { objectName: "event-copy-location" visible: root.locationText !== "" text: "Copy location" - iconName: "pin" + iconName: "copy" foreground: root.textColor accent: root.eventColor fontFamily: root.panelFontFamily @@ -272,24 +452,20 @@ Rectangle { fontFamily: root.panelFontFamily onClicked: if (root.controller) root.controller.openExternal(root.providerLink) } - } - - PanelSeparator { - visible: String(root.event && root.event.description || "") !== "" - width: parent.width - foreground: root.textColor - } - Text { - visible: String(root.event && root.event.description || "") !== "" - width: parent.width - text: String(root.event && root.event.description || "") - color: root.textColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.body - lineHeight: 1.35 - wrapMode: Text.Wrap - textFormat: Text.PlainText + // One quiet trigger; which delete β€” telling guests or not, one + // occurrence or the series β€” is chosen in the confirmation, where the + // event is named. + IconTextButton { + visible: root.canDelete + objectName: "event-delete" + text: "Delete..." + iconName: "trash" + foreground: root.textColor + accent: root.urgentColor + fontFamily: root.panelFontFamily + onClicked: root.deleteRequested(String(root.event.sourceId || ""), root.event) + } } } } diff --git a/ui/components/CalendarReminderPanel.qml b/ui/components/CalendarReminderPanel.qml new file mode 100644 index 0000000..49a1c1e --- /dev/null +++ b/ui/components/CalendarReminderPanel.qml @@ -0,0 +1,114 @@ +import QtQuick +import QtQuick.Controls +import qs.Commons + +Column { + id: root + required property var service + required property color textColor + required property color dimColor + required property color accentColor + required property color urgentColor + required property string panelFontFamily + property string eventKey: "" + readonly property var reminders: service && service.calendarReminderInbox + ? service.calendarReminderInbox : null + readonly property var records: reminders ? reminders.records.filter(function(record) { + return root.eventKey === "" || record.sourceId + "\n" + record.eventId === root.eventKey + }) : [] + visible: records.length > 0 + spacing: Style.space(6) + + Text { + text: "Reminders" + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.bold: true + font.pixelSize: Style.font.bodySmall + } + Flickable { + id: reminderScroll + width: parent.width + height: Math.min(entries.implicitHeight, Style.space(180)) + contentHeight: entries.implicitHeight + contentWidth: width + clip: true + boundsBehavior: Flickable.StopAtBounds + ScrollBar.vertical: ScrollBar {} + WheelScroller { view: reminderScroll } + Column { + id: entries + width: parent.width + spacing: Style.space(6) + Repeater { + model: root.records + delegate: Rectangle { + id: entry + required property var modelData + width: parent.width + height: entryContent.implicitHeight + Style.space(16) + color: Qt.alpha(root.accentColor, 0.08) + readonly property bool pending: root.reminders.pendingKeys.indexOf(modelData.key) >= 0 + Column { + id: entryContent + x: Style.space(8) + y: Style.space(8) + width: parent.width - Style.space(16) + spacing: Style.space(6) + Text { + width: parent.width + text: String(entry.modelData.title || "Event") + " Β· " + + Qt.formatDateTime(new Date(entry.modelData.start), "ddd HH:mm") + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.bodySmall + } + Flow { + width: parent.width + spacing: Style.space(6) + IconTextButton { + visible: root.eventKey === "" + text: "Open event..." + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + onClicked: root.reminders.open(entry.modelData) + } + IconTextButton { + objectName: "calendar-reminder-snooze" + text: "Snooze " + root.service.calendarSnoozeMinutes + " min" + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + enabled: !entry.pending + onClicked: root.reminders.action(entry.modelData.key, "snooze", entry.modelData.noticeId) + } + IconTextButton { + objectName: "calendar-reminder-dismiss" + text: "Dismiss" + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + enabled: !entry.pending + onClicked: root.reminders.action(entry.modelData.key, "dismiss", entry.modelData.noticeId) + } + } + } + } + } + } + } + Text { + width: parent.width + visible: text !== "" + text: root.reminders ? root.reminders.lastError : "" + color: root.urgentColor + textFormat: Text.PlainText + wrapMode: Text.Wrap + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } +} diff --git a/ui/components/CalendarSettings.qml b/ui/components/CalendarSettings.qml index fc2eed7..54c16ac 100644 --- a/ui/components/CalendarSettings.qml +++ b/ui/components/CalendarSettings.qml @@ -16,19 +16,44 @@ Column { property bool adding: false property string passwordEditingId: "" property string colorEditingId: "" + property string setupAccountId: "" + property string setupError: "" + property bool setupComplete: false + signal accountSetupRequested(int index) + signal clientSetupRequested() + signal addAccountRequested() + signal openCalendarRequested() + readonly property var settingsSources: { + var groups = Sources.groupByAccount(controller ? controller.availableSources : null, + service ? service.accountSummaries : []) + var values = [] + for (var i = 0; i < groups.length; i++) values = values.concat(groups[i].calendars) + return values + } + readonly property var writableSources: settingsSources.filter(function(source) { + return Sources.writable(source) && !root.orphaned(source) + }) + + function accountIndex(id) { + var accounts = root.service ? root.service.accountSummaries : [] + for (var i = 0; i < accounts.length; i++) if (accounts[i].id === id) return i + return -1 + } function discoverableAccounts() { if (!root.service || root.service.backendCanDiscoverCalendars !== true) return [] var accounts = root.service && Array.isArray(root.service.accountSummaries) ? root.service.accountSummaries : [] return accounts.filter(function(account) { - return account && account.signedIn === true - && (account.calendarProvider === "microsoft" || account.calendarProvider === "icloud") + return account + && (account.calendarProvider === "microsoft" || account.calendarProvider === "icloud" + || (account.calendarProvider === "google" && root.service.backendCanGoogleCalendars === true)) }) } function providerName(account) { - return account && account.calendarProvider === "icloud" ? "iCloud" : "Microsoft" + return account && account.calendarProvider === "icloud" ? "iCloud" + : account && account.calendarProvider === "google" ? "Google" : "Microsoft" } function accountLabel(source) { @@ -55,6 +80,54 @@ Column { return (value.kind === "caldav" && value.discovered !== true) || root.orphaned(value) } + // Calendars listed under their mailbox's row: the provider and the address + // are on that row already, so only what sets this calendar apart is left. + function nestedDetail(source) { + var value = source || {} + var parts = [] + if (value.preferred === true) parts.push("Default for new events") + if (value.readOnly === true) parts.push("Read-only") + return parts.join(" Β· ") + } + + // Google names a mailbox's own calendar after its address, which the row + // above already shows; beside it the calendar is simply the primary one. + function displayName(source) { + var value = source || {} + var name = String(value.name || value.id || "Calendar") + var account = root.accountLabel(value) + return account !== "" && name.toLowerCase() === account.toLowerCase() ? "Primary" : name + } + + function accountCalendars(accountId) { + return root.settingsSources.filter(function(source) { + return String(source.accountId || "") === String(accountId || "") && !root.orphaned(source) + }) + } + + // Hand-added CalDAV calendars and ones whose mailbox is gone or cannot be + // discovered here: nothing above lists them, so they are listed on their own. + readonly property var otherSources: settingsSources.filter(function(source) { + var account = String(source.accountId || "") + return account === "" || root.orphaned(source) + || !root.discoverableAccounts().some(function(value) { return String(value.id) === account }) + }) + + // One default per account, asked only where the account has more than one + // calendar to put a new event in. + readonly property var defaultChoices: Sources.writableGroups(Sources.groupByAccount( + { sources: writableSources }, service ? service.accountSummaries : [])) + .filter(function(group) { return group.calendars.length > 1 }) + + readonly property var reminderSources: settingsSources.filter(function(source) { + return Sources.nativeCalendarFeatures(source) && !root.orphaned(source) + }) + + function reminderMode(source) { + return source.remindersEnabled !== true ? "off" + : Number(source.reminderMinutes) >= 0 ? "custom" : "google" + } + function sourceDetail(source) { var value = source || {} if (value.kind === "caldav") return String(value.url || "CalDAV") @@ -76,227 +149,152 @@ Column { } width: parent ? parent.width : implicitWidth - spacing: Style.space(8) - - Text { - text: "CALENDARS" - color: root.dimColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.caption - font.letterSpacing: 1 - } - - Text { - width: parent.width - text: "Google and Microsoft calendars follow their signed-in mailboxes. Find every Microsoft or iCloud calendar below, or connect another CalDAV calendar manually." - color: root.dimColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.caption - wrapMode: Text.WordWrap - textFormat: Text.PlainText - } - - Rectangle { - width: parent.width - implicitHeight: Math.max(unifiedText.implicitHeight, unifiedSwitch.implicitHeight) - + Style.space(16) + spacing: Style.space(16) + + // One settings row, the shape every other row on this page has: a title and + // a caption on the left, the control that changes it on the right. + component SettingRow: Rectangle { + id: settingRow + property string title: "" + property string detail: "" + default property alias controls: rowControls.data + width: parent ? parent.width : 0 + implicitHeight: Math.max(settingText.implicitHeight, rowControls.implicitHeight) + Style.space(16) radius: Style.cornerRadius color: Style.normalFillFor(root.textColor, root.accentColor) - Column { - id: unifiedText + id: settingText anchors.left: parent.left anchors.leftMargin: Style.space(12) - anchors.right: unifiedSwitch.left + anchors.right: rowControls.left anchors.rightMargin: Style.space(10) anchors.verticalCenter: parent.verticalCenter spacing: Style.space(2) - Text { width: parent.width - text: "Unified calendar view" + text: settingRow.title + textFormat: Text.PlainText + elide: Text.ElideMiddle color: root.textColor font.family: root.panelFontFamily font.pixelSize: Style.font.bodySmall } - Text { width: parent.width - text: "Show calendars from every connected account instead of following the current mailbox" + visible: text !== "" + text: settingRow.detail + textFormat: Text.PlainText + wrapMode: Text.WordWrap color: root.dimColor font.family: root.panelFontFamily font.pixelSize: Style.font.caption - wrapMode: Text.WordWrap - textFormat: Text.PlainText } } - - ToggleSwitch { - id: unifiedSwitch - objectName: "unifiedCalendarSwitch" + Row { + id: rowControls anchors.right: parent.right anchors.rightMargin: Style.space(10) anchors.verticalCenter: parent.verticalCenter - checked: !!root.service && root.service.unifiedCalendarView === true - foreground: root.textColor - accent: root.accentColor - onToggled: if (root.service) - root.service.setUnifiedCalendarView(!root.service.unifiedCalendarView) + spacing: Style.space(6) } } - Repeater { - model: root.discoverableAccounts() + component SectionHeading: Text { + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + font.letterSpacing: 1 + } - Rectangle { - id: discoveryRow - required property var modelData + // A calendar: its colour, its name and whether it is shown. The colour and + // password editors open beneath the row they belong to. + component CalendarRow: Column { + id: calendarRow + property var source: ({}) + property string detail: "" + width: parent ? parent.width : 0 + spacing: Style.space(2) - width: root.width - implicitHeight: Math.max(discoveryText.implicitHeight, discoveryButton.implicitHeight) - + Style.space(16) + Rectangle { + width: parent.width + implicitHeight: Math.max(calendarText.implicitHeight, calendarActions.implicitHeight) + Style.space(16) radius: Style.cornerRadius color: Style.normalFillFor(root.textColor, root.accentColor) - Column { - id: discoveryText - anchors.left: parent.left - anchors.leftMargin: Style.space(12) - anchors.right: discoveryButton.left - anchors.rightMargin: Style.space(10) - anchors.verticalCenter: parent.verticalCenter - spacing: Style.space(2) - - Text { - width: parent.width - text: root.providerName(discoveryRow.modelData) + " calendars" - color: root.textColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.bodySmall - } - Text { - width: parent.width - text: String(discoveryRow.modelData.email || discoveryRow.modelData.label || "") - color: root.dimColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.caption - elide: Text.ElideMiddle - textFormat: Text.PlainText - } - } - Button { - id: discoveryButton - objectName: "calendar-discover-" + String(discoveryRow.modelData.calendarProvider || "account") + id: colorButton + objectName: "calendar-source-color" focusable: true - anchors.right: parent.right - anchors.rightMargin: Style.space(10) + // The dot's left edge sits on the same line as the titles above it. + anchors.left: parent.left + anchors.leftMargin: Style.space(12) - (width - Style.space(10)) / 2 anchors.verticalCenter: parent.verticalCenter - bordered: true + width: Style.space(24) + height: width + horizontalPadding: 0 + verticalPadding: 0 + background: "transparent" + selected: root.colorEditingId === String(calendarRow.source.id) foreground: root.textColor - fontFamily: root.panelFontFamily - fontSize: Style.font.caption - enabled: !!root.controller && !root.controller.discoveringCalendars - && !root.controller.savingSource - text: root.controller && root.controller.discoveringCalendars - && root.controller.discoveringAccountId === String(discoveryRow.modelData.id || "") - ? "Finding..." - : (root.controller && root.controller.discoveredCount(discoveryRow.modelData.id) > 0 - ? "Refresh calendars" : "Find calendars") + accent: root.accentColor + tooltipText: "Change calendar color" + Accessible.name: "Change color for " + String(calendarRow.source.name || calendarRow.source.id) + enabled: !!root.controller && !root.controller.savingSource + && !root.controller.discoveringCalendars onClicked: { - resultText.text = "" - root.colorEditingId = "" root.passwordEditingId = "" - if (root.controller) - root.controller.discoverAccountCalendars(discoveryRow.modelData.id) + root.colorEditingId = root.colorEditingId === String(calendarRow.source.id) + ? "" : String(calendarRow.source.id) + } + Rectangle { + objectName: "calendar-source-color-swatch" + anchors.centerIn: parent + width: Style.space(10) + height: width + radius: width / 2 + color: calendarPalette.colorFor(calendarRow.source.colorKey) } } - } - } - - Repeater { - model: root.controller && root.controller.availableSources - ? root.controller.availableSources.sources : [] - - Item { - width: root.width - implicitHeight: sourceRow.height - + (colorRow.visible ? colorRow.implicitHeight + Style.space(6) : 0) - + (passwordRow.visible ? passwordRow.implicitHeight + Style.space(6) : 0) - - Item { - id: sourceRow - width: parent.width - height: Math.max(sourceText.implicitHeight, sourceActions.implicitHeight) Column { - id: sourceText + id: calendarText anchors.left: parent.left - anchors.right: sourceActions.left - anchors.rightMargin: Style.space(8) + anchors.leftMargin: Style.space(30) + anchors.right: calendarActions.left + anchors.rightMargin: Style.space(10) anchors.verticalCenter: parent.verticalCenter spacing: Style.space(2) - Text { width: parent.width - text: String(modelData.name || modelData.id || "Calendar") + text: root.displayName(calendarRow.source) + textFormat: Text.PlainText + elide: Text.ElideRight color: root.textColor font.family: root.panelFontFamily font.pixelSize: Style.font.bodySmall - elide: Text.ElideRight } Text { objectName: "calendar-source-detail" width: parent.width - text: root.sourceDetail(modelData) + visible: text !== "" + text: calendarRow.detail + textFormat: Text.PlainText + elide: Text.ElideMiddle color: root.dimColor font.family: root.panelFontFamily font.pixelSize: Style.font.caption - elide: Text.ElideMiddle } } Row { - id: sourceActions + id: calendarActions anchors.right: parent.right + anchors.rightMargin: Style.space(10) anchors.verticalCenter: parent.verticalCenter - spacing: Style.space(4) - Button { - id: colorButton - objectName: "calendar-source-color" - focusable: true - width: Style.space(24) - height: width - // The switch reserves a taller cursor target than this compact - // button. A Row top-aligns children of different heights, so bind - // their centres explicitly instead of leaving the dot too high. - anchors.verticalCenter: sourceToggle.verticalCenter - horizontalPadding: 0 - verticalPadding: 0 - selected: root.colorEditingId === String(modelData.id) - foreground: root.textColor - accent: root.accentColor - tooltipText: "Change calendar color" - Accessible.name: "Change color for " + String(modelData.name || modelData.id) - enabled: !!root.controller && !root.controller.savingSource - && !root.controller.discoveringCalendars - onClicked: { - root.passwordEditingId = "" - root.colorEditingId = root.colorEditingId === String(modelData.id) - ? "" : String(modelData.id) - } - - Rectangle { - objectName: "calendar-source-color-swatch" - anchors.centerIn: parent - width: Style.space(10) - height: width - radius: width / 2 - color: calendarPalette.colorFor(modelData.colorKey) - } - } + spacing: Style.space(6) IconTextButton { - visible: modelData.kind === "caldav" && modelData.discovered !== true + anchors.verticalCenter: parent.verticalCenter + visible: calendarRow.source.kind === "caldav" && calendarRow.source.discovered !== true text: "Set password" bordered: false foreground: root.textColor @@ -305,166 +303,366 @@ Column { && !root.controller.discoveringCalendars onClicked: { root.colorEditingId = "" - root.passwordEditingId = String(modelData.id) + root.passwordEditingId = String(calendarRow.source.id) } } IconTextButton { objectName: "calendar-source-remove" - visible: root.removable(modelData) + anchors.verticalCenter: parent.verticalCenter + visible: root.removable(calendarRow.source) text: "Remove" bordered: false foreground: root.urgentColor fontFamily: root.panelFontFamily enabled: !!root.controller && !root.controller.savingSource && !root.controller.discoveringCalendars - onClicked: root.controller.removeCalendar(modelData.id) + onClicked: root.controller.removeCalendar(calendarRow.source.id) } - Button { - id: sourceToggle + ToggleSwitch { objectName: "calendar-source-toggle" - property bool checked: modelData.enabled !== false - signal toggled() + anchors.verticalCenter: parent.verticalCenter + checked: calendarRow.source.enabled !== false + interactive: !!root.controller && !root.controller.savingSource + && !root.controller.discoveringCalendars + foreground: root.textColor + accent: root.accentColor + onToggled: if (root.controller) + root.controller.setSourceEnabled(calendarRow.source.id, calendarRow.source.enabled === false) + } + } + } + + Row { + id: colorRow + objectName: "calendar-color-picker" + x: Style.space(12) + visible: root.colorEditingId === String(calendarRow.source.id) + height: visible ? implicitHeight : 0 + spacing: Style.space(6) + Text { + anchors.verticalCenter: parent.verticalCenter + text: "Color" + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + textFormat: Text.PlainText + } + Repeater { + model: calendarPalette.slots + Button { + id: paletteOption + required property string modelData + objectName: "calendar-color-" + modelData focusable: true + width: Style.space(24) + height: width horizontalPadding: 0 verticalPadding: 0 - implicitWidth: switchGraphic.implicitWidth - implicitHeight: switchGraphic.implicitHeight - Accessible.role: Accessible.CheckBox - Accessible.name: "Show " + String(modelData.name || modelData.id) - Accessible.checked: checked + selected: String(modelData) === String(calendarRow.source.colorKey || "") foreground: root.textColor accent: root.accentColor + tooltipText: "Use " + modelData + Accessible.name: "Use " + modelData + " for " + + String(calendarRow.source.name || calendarRow.source.id) enabled: !!root.controller && !root.controller.savingSource && !root.controller.discoveringCalendars - onClicked: toggled() - onToggled: if (root.controller) - root.controller.setSourceEnabled(modelData.id, modelData.enabled === false) - ToggleSwitch { - id: switchGraphic + onClicked: { + root.controller.setSourceColor(calendarRow.source.id, modelData) + root.colorEditingId = "" + } + Rectangle { anchors.centerIn: parent - checked: sourceToggle.checked - interactive: false - cursorRing: true - hasCursor: sourceToggle.hot || sourceToggle.activeFocus - foreground: root.textColor - accent: root.accentColor + width: Style.space(14) + height: width + radius: width / 2 + color: "transparent" + border.width: parent.selected ? Math.max(1, Style.normalBorderWidth) : 0 + border.color: root.textColor + Rectangle { + objectName: "calendar-color-swatch-" + paletteOption.modelData + anchors.centerIn: parent + width: Style.space(8) + height: width + radius: width / 2 + color: calendarPalette.colorFor(paletteOption.modelData) + } } } } + } + + Row { + id: passwordRow + x: Style.space(12) + width: parent.width - x + visible: calendarRow.source.kind === "caldav" && calendarRow.source.discovered !== true + && root.passwordEditingId === String(calendarRow.source.id) + height: visible ? implicitHeight : 0 + spacing: Style.space(6) + TextField { + id: existingPassword + width: Math.max(80, parent.width - saveExisting.implicitWidth + - cancelExisting.implicitWidth - parent.spacing * 2) + password: true + foreground: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.bodySmall + placeholderText: "Password or app password" + onAccepted: saveExisting.clicked() + } + IconTextButton { + id: saveExisting + text: "Save" + foreground: root.textColor + fontFamily: root.panelFontFamily + enabled: !!root.controller && existingPassword.text !== "" + && !root.controller.savingSource && !root.controller.discoveringCalendars + onClicked: root.controller.updateCalendarPassword(calendarRow.source, existingPassword.text) } + IconTextButton { + id: cancelExisting + text: "Cancel" + bordered: false + foreground: root.dimColor + fontFamily: root.panelFontFamily + onClicked: root.passwordEditingId = "" + } + } + } - Row { - id: colorRow - objectName: "calendar-color-picker" - anchors.top: sourceRow.bottom - anchors.topMargin: visible ? Style.space(6) : 0 - width: parent.width - visible: root.colorEditingId === String(modelData.id) - spacing: Style.space(6) + // --------------------------------------------------------------- calendars - Text { - anchors.verticalCenter: parent.verticalCenter - text: "Color" - color: root.dimColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.caption - textFormat: Text.PlainText - } + Column { + width: parent.width + spacing: Style.space(4) + SectionHeading { text: "CALENDARS" } + Text { + width: parent.width + text: "Choose which calendars appear and their colors. New events and reminders are set below." + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + textFormat: Text.PlainText + } + } - Repeater { - model: calendarPalette.slots + Text { + width: parent.width + visible: root.discoverableAccounts().length === 0 + text: root.service && root.service.backendCanDiscoverCalendars !== true + ? "Update the mail backend to connect account calendars." + : "Add a Google, Microsoft or iCloud mailbox to connect its calendars." + textFormat: Text.PlainText + wrapMode: Text.WordWrap + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } - Button { - id: paletteOption - required property string modelData - objectName: "calendar-color-" + modelData - focusable: true - width: Style.space(24) - height: width - horizontalPadding: 0 - verticalPadding: 0 - selected: String(modelData) === String(colorRow.modelDataForSource.colorKey || "") - foreground: root.textColor - accent: root.accentColor - tooltipText: "Use " + modelData - Accessible.name: "Use " + modelData + " for " - + String(colorRow.modelDataForSource.name || colorRow.modelDataForSource.id) - enabled: !!root.controller && !root.controller.savingSource - && !root.controller.discoveringCalendars - onClicked: { - root.controller.setSourceColor(colorRow.modelDataForSource.id, modelData) - root.colorEditingId = "" - } + Button { + visible: root.discoverableAccounts().length === 0 + text: "Add an account..." + foreground: root.textColor + fontFamily: root.panelFontFamily + onClicked: root.addAccountRequested() + } - Rectangle { - anchors.centerIn: parent - width: Style.space(14) - height: width - radius: width / 2 - color: "transparent" - border.width: parent.selected ? Math.max(1, Style.normalBorderWidth) : 0 - border.color: root.textColor - - Rectangle { - objectName: "calendar-color-swatch-" + paletteOption.modelData - anchors.centerIn: parent - width: Style.space(8) - height: width - radius: width / 2 - color: calendarPalette.colorFor(paletteOption.modelData) - } + Repeater { + model: root.discoverableAccounts() + + Column { + id: accountBlock + required property var modelData + readonly property var calendars: root.accountCalendars(modelData.id) + width: root.width + spacing: Style.space(2) + + SettingRow { + title: String(accountBlock.modelData.email || accountBlock.modelData.label || "") + detail: root.providerName(accountBlock.modelData) + " Β· " + + (accountBlock.modelData.signedIn !== true ? "Sign in to connect calendars" + : accountBlock.calendars.length > 0 + ? accountBlock.calendars.length + (accountBlock.calendars.length === 1 ? " calendar" : " calendars") + : "Uses this mailbox's sign-in") + Button { + id: discoveryButton + objectName: "calendar-discover-" + String(accountBlock.modelData.calendarProvider || "account") + focusable: true + bordered: true + foreground: root.textColor + fontFamily: root.panelFontFamily + fontSize: Style.font.caption + enabled: !!root.controller && !root.controller.discoveringCalendars + && !root.controller.savingSource + text: accountBlock.modelData.signedIn !== true ? "Sign in..." + : root.controller && root.controller.discoveringCalendars + && root.controller.discoveringAccountId === String(accountBlock.modelData.id || "") + ? "Finding..." + : (accountBlock.calendars.length > 0 + ? "Refresh calendars" : accountBlock.modelData.calendarProvider === "google" ? "Enable Google Calendar" : "Find calendars") + + (accountBlock.modelData.calendarProvider === "google" ? "..." : "") + onClicked: { + resultText.text = "" + root.colorEditingId = "" + root.passwordEditingId = "" + root.setupAccountId = String(accountBlock.modelData.id || "") + root.setupError = "" + root.setupComplete = false + if (accountBlock.modelData.signedIn !== true) { + root.accountSetupRequested(root.accountIndex(root.setupAccountId)) + return } + if (root.controller) + root.controller.discoverAccountCalendars(accountBlock.modelData.id) } } + } - property var modelDataForSource: modelData + Repeater { + model: accountBlock.calendars + CalendarRow { + required property var modelData + source: modelData + detail: root.nestedDetail(modelData) + } } + } + } - Row { - id: passwordRow - anchors.top: colorRow.visible ? colorRow.bottom : sourceRow.bottom - anchors.topMargin: visible ? Style.space(6) : 0 - width: parent.width - visible: modelData.kind === "caldav" && modelData.discovered !== true - && root.passwordEditingId === String(modelData.id) - spacing: Style.space(6) + Column { + objectName: "calendar-setup-recovery" + width: root.width + visible: root.setupError !== "" + spacing: Style.space(6) + Text { + width: parent.width + text: root.accountLabel({ accountId: root.setupAccountId }) + ": " + root.setupError + color: root.urgentColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + textFormat: Text.PlainText + } + Text { + width: parent.width + text: "For Google, enable the Google Calendar API in the same Cloud project as your Gmail client. If access was refused, sign in again and allow calendar access. Your saved calendar choices are kept." + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + textFormat: Text.PlainText + visible: root.setupAccountId !== "" && root.discoverableAccounts().some(function(account) { + return account.id === root.setupAccountId && account.calendarProvider === "google" + }) + } + Flow { + width: parent.width + spacing: Style.space(6) + Button { + text: "Check again" + foreground: root.textColor + fontFamily: root.panelFontFamily + enabled: !!root.controller && !root.controller.discoveringCalendars && !root.controller.savingSource + onClicked: root.controller.discoverAccountCalendars(root.setupAccountId) + } + Button { + text: "Sign in again..." + foreground: root.textColor + fontFamily: root.panelFontFamily + enabled: root.accountIndex(root.setupAccountId) >= 0 + onClicked: root.accountSetupRequested(root.accountIndex(root.setupAccountId)) + } + Button { + text: "Google Calendar API setup..." + visible: root.setupAccountId !== "" && root.discoverableAccounts().some(function(account) { + return account.id === root.setupAccountId && account.calendarProvider === "google" + }) + foreground: root.textColor + fontFamily: root.panelFontFamily + onClicked: Qt.openUrlExternally("https://console.cloud.google.com/apis/library/calendar-json.googleapis.com") + } + } + } - TextField { - id: existingPassword - width: Math.max(80, parent.width - saveExisting.implicitWidth - - cancelExisting.implicitWidth - parent.spacing * 2) - password: true - foreground: root.textColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.bodySmall - placeholderText: "Password or app password" - onAccepted: saveExisting.clicked() - } - IconTextButton { - id: saveExisting - text: "Save" + Column { + width: root.width + visible: !!root.controller && root.controller.discoveryChoices !== null + spacing: Style.space(8) + Text { + text: "Choose calendars to show" + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.bodySmall + textFormat: Text.PlainText + } + Text { + width: parent.width + text: "Start with your Google selection. You can change visibility and reminders independently below. Your primary writable calendar is selected for new events by default." + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.WordWrap + textFormat: Text.PlainText + } + Repeater { + model: root.controller && root.controller.discoveryChoices ? root.controller.discoveryChoices.sources.filter(function(source) { + return source.accountId === root.controller.discoveryChoiceAccount && source.kind === "google" + }) : [] + delegate: SettingRow { + required property var modelData + title: String(modelData.name || modelData.id) + detail: modelData.readOnly === true ? "Read-only" : "" + ToggleSwitch { + objectName: "calendar-discovered-toggle" + checked: modelData.enabled === true foreground: root.textColor - fontFamily: root.panelFontFamily - enabled: !!root.controller && existingPassword.text !== "" - && !root.controller.savingSource && !root.controller.discoveringCalendars - onClicked: root.controller.updateCalendarPassword(modelData, existingPassword.text) - } - IconTextButton { - id: cancelExisting - text: "Cancel" - bordered: false - foreground: root.dimColor - fontFamily: root.panelFontFamily - onClicked: root.passwordEditingId = "" + accent: root.accentColor + onToggled: root.controller.chooseDiscovered(modelData.id, !modelData.enabled) } } } + Row { + spacing: Style.space(8) + Button { + text: root.controller && root.controller.savingSource ? "Saving..." : "Save calendar selection" + foreground: root.textColor + enabled: !!root.controller && !root.controller.savingSource + onClicked: root.controller.confirmDiscovery() + } + Button { + text: "Cancel" + foreground: root.textColor + onClicked: root.controller.discoveryChoices = null + } + } + } + + Column { + width: root.width + visible: root.otherSources.length > 0 + spacing: Style.space(2) + Text { + text: "Other calendars" + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + bottomPadding: Style.space(4) + } + Repeater { + model: root.otherSources + CalendarRow { + required property var modelData + source: modelData + detail: root.sourceDetail(modelData) + } + } } IconTextButton { visible: !root.adding iconName: "plus" - text: "Add a calendar" + text: "Connect a CalDAV calendar..." foreground: root.textColor fontFamily: root.panelFontFamily enabled: !!root.controller && !root.controller.savingSource @@ -551,6 +749,167 @@ Column { textFormat: Text.PlainText } + SettingRow { + title: "Unified calendar view" + detail: "Show every account together instead of following the current mailbox." + ToggleSwitch { + id: unifiedSwitch + objectName: "unifiedCalendarSwitch" + checked: !!root.service && root.service.unifiedCalendarView === true + foreground: root.textColor + accent: root.accentColor + onToggled: if (root.service) root.service.setUnifiedCalendarView(!root.service.unifiedCalendarView) + } + } + + Button { + objectName: "calendar-open-after-setup" + visible: root.setupComplete + text: "Open calendar" + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + onClicked: root.openCalendarRequested() + } + + // -------------------------------------------------------------- new events + + Column { + width: parent.width + visible: root.defaultChoices.length > 0 + spacing: Style.space(2) + SectionHeading { text: "NEW EVENTS"; bottomPadding: Style.space(2) } + Repeater { + id: defaultGroups + model: root.defaultChoices + SettingRow { + id: defaultGroup + required property var modelData + title: "Default calendar" + detail: defaultGroup.modelData.accountLabel + Dropdown { + objectName: "calendar-default-picker" + width: Style.space(200) + showLabel: false + options: defaultGroup.modelData.calendars.map(function(source) { + return { value: source.id, label: root.displayName(source) } + }) + value: { + var values = defaultGroup.modelData.calendars + for (var i = 0; i < values.length; i++) if (values[i].preferred) return values[i].id + return values.length ? values[0].id : "" + } + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + enabled: !!root.controller && !root.controller.savingSource && !root.controller.discoveringCalendars + onChanged: function(next) { root.controller.setDefaultCalendar(next) } + } + } + } + } + + // --------------------------------------------------------------- reminders + + Column { + width: parent.width + spacing: Style.space(2) + visible: !!root.service && root.service.backendCanGoogleCalendars === true + && root.reminderSources.length > 0 + SectionHeading { text: "REMINDERS"; bottomPadding: Style.space(2) } + SettingRow { + title: "Desktop reminders" + detail: "Shown while Omamail is running, even with its window closed. Google calendars only." + ToggleSwitch { + objectName: "calendar-reminders-enabled" + checked: !!root.service && root.service.calendarRemindersEnabled === true + foreground: root.textColor + accent: root.accentColor + onToggled: root.service.persistSetting("calendarRemindersEnabled", !root.service.calendarRemindersEnabled) + } + } + SettingRow { + visible: !!root.service && root.service.calendarRemindersEnabled === true + title: "Snooze" + detail: "How long Snooze puts a reminder off." + NumberField { + objectName: "calendar-snooze-minutes" + label: "Minutes" + from: 1 + to: 1440 + stepSize: 1 + value: root.service ? root.service.calendarSnoozeMinutes : 5 + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + fontSize: Style.font.bodySmall + onModified: function(next) { root.service.persistSetting("calendarSnoozeMinutes", next) } + } + } + Repeater { + model: !!root.service && root.service.calendarRemindersEnabled === true ? root.reminderSources : [] + SettingRow { + id: reminderRow + required property var modelData + title: root.displayName(modelData) + detail: root.accountLabel(modelData) + (modelData.enabled === false ? " Β· Hidden, still reminds" : "") + NumberField { + objectName: "calendar-reminder-minutes" + anchors.verticalCenter: parent.verticalCenter + visible: root.reminderMode(reminderRow.modelData) === "custom" + label: "Minutes before" + from: 0 + to: 40320 + stepSize: 5 + value: Math.max(0, Number(reminderRow.modelData.reminderMinutes)) + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + fontSize: Style.font.bodySmall + enabled: !!root.controller && !root.controller.savingSource + onModified: function(next) { root.controller.setReminderPolicy(reminderRow.modelData.id, true, next) } + } + Dropdown { + objectName: "calendar-reminder-mode" + anchors.verticalCenter: parent.verticalCenter + width: Style.space(200) + showLabel: false + value: root.reminderMode(reminderRow.modelData) + options: [{ value: "off", label: "Off" }, { value: "google", label: "Google event reminders" }, + { value: "custom", label: "Custom timing" }] + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + enabled: !!root.controller && !root.controller.savingSource + onChanged: function(next) { + root.controller.setReminderPolicy(reminderRow.modelData.id, next !== "off", + next === "google" ? -1 : Number(reminderRow.modelData.reminderMinutes) >= 0 + ? Number(reminderRow.modelData.reminderMinutes) : 10) + } + } + } + } + Text { + width: parent.width + visible: text !== "" + topPadding: Style.space(4) + text: String(root.service && root.service.calendarReminderError || "") + textFormat: Text.PlainText + wrapMode: Text.WordWrap + color: root.urgentColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + } + + Button { + text: "Advanced Google setup..." + foreground: root.dimColor + fontFamily: root.panelFontFamily + fontSize: Style.font.caption + onClicked: root.clientSetupRequested() + } + function saveCalendar() { resultText.text = "" root.controller.addCalDavCalendar({ @@ -576,7 +935,9 @@ Column { } function onDiscoveryFinished(ok, error, count) { resultText.ok = ok - resultText.text = ok ? "Found " + count + (count === 1 ? " calendar" : " calendars") : error + root.setupError = ok ? "" : error + root.setupComplete = ok + resultText.text = ok ? "Saved " + count + (count === 1 ? " calendar. Choose reminders below, then open your calendar." : " calendars. Choose reminders below, then open your calendar.") : "" } } } diff --git a/ui/components/CalendarView.qml b/ui/components/CalendarView.qml index 35438ca..fe7b921 100644 --- a/ui/components/CalendarView.qml +++ b/ui/components/CalendarView.qml @@ -1,7 +1,10 @@ import QtQuick import QtQuick.Controls +import QtQuick.Layouts +import QtQuick.Window import qs.Commons import "../calendar/Calendar.js" as Calendar +import "../keys/Keymap.js" as Keymap Item { id: root @@ -20,16 +23,89 @@ Item { property date visibleMonth: new Date(new Date().getFullYear(), new Date().getMonth(), 1) property date visibleWeek: new Date() property string viewMode: "month" + property Item toolbarHost: null + readonly property real toolbarHeight: calendarToolbar.height property string selectedEventId: "" + property bool monthPointerDown: false + property Item hoveredMonthDay: null + function updateMonthHover() { + if (overflowHover.hovered) return + if (!monthHover.hovered || monthPointerDown || viewMode !== "month" || detailOpen) { + hoveredMonthDay = null + monthHoverDelay.stop() + monthHoverClose.restart() + return + } + var point = monthHover.point.position + var index = Math.floor(point.y / monthGrid.weekHeight) * 7 + Math.floor(point.x / (monthGrid.width / 7)) + var cell = monthDaysRepeater.itemAt(index) + if (!cell || cell.overflowCount === 0) cell = null + if (hoveredMonthDay === cell) return + hoveredMonthDay = cell + monthHoverDelay.stop() + if (cell) { monthHoverClose.stop(); monthHoverDelay.restart() } + else monthHoverClose.restart() + } + function beginMonthGesture() { + monthPointerDown = true + monthHoverDelay.stop() + monthOverflow.close() + } + onViewModeChanged: { monthOverflow.close(); monthHoverDelay.stop(); hoveredMonthDay = null; syncAgenda() } + onDaysChanged: syncAgenda() + // The agenda's clock ticks every minute to drop finished events. Its model + // changes only when the list does, so a tick leaves the scroll where it was. + property var agendaEvents: [] + function syncAgenda() { + var next = viewMode === "agenda" ? visibleEvents() : [] + if (!Calendar.sameEvents(agendaEvents, next)) agendaEvents = next + } + Connections { + target: root.controller + function onEventsChanged() { root.syncAgenda() } + function onNowMsChanged() { root.syncAgenda() } + } + onVisibleMonthChanged: { monthOverflow.close(); monthHoverDelay.stop(); hoveredMonthDay = null } + onDetailOpenChanged: if (detailOpen) { monthOverflow.close(); monthHoverDelay.stop() } + Timer { + id: monthHoverDelay + interval: 400 + onTriggered: { + if (!root.hoveredMonthDay || root.monthPointerDown || root.detailOpen || root.viewMode !== "month") return + monthOverflow.dayCell = root.hoveredMonthDay + monthOverflow.open() + monthOverflow.place() + } + } + Timer { + id: monthHoverClose + interval: 220 + onTriggered: if (!overflowHover.hovered) monthOverflow.close() + } property var detailEvent: null + property int detailReadSerial: 0 + property bool detailLoading: false + property string detailError: "" + property double requestedEventStart: 0 + property bool waitingForEvent: false readonly property bool detailOpen: detailEvent !== null - readonly property var days: Calendar.monthDays( + readonly property real toolbarFontSize: Style.font.body + readonly property real toolbarControlHeight: Style.spacing.controlHeight + readonly property var monthSpans: Calendar.monthSpanLayout(controller ? controller.events : [], days) + readonly property var days: Calendar.monthGridDays( visibleMonth.getFullYear(), visibleMonth.getMonth(), 1) readonly property var weekDays: Calendar.weekDays(visibleWeek.getTime(), 1) + readonly property var displayDays: viewMode === "day" ? weekDays.filter(function(day) { + return day.isoDate === Calendar.isoDate(visibleWeek) + }) : weekDays readonly property var monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] readonly property var weekdayNames: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] readonly property string todayIso: Calendar.isoDate(new Date()) + readonly property var viewOptions: ["Day", "Week", "Month", "Agenda"].map(function(label) { + var binding = Keymap.bindingsFor("calendar").filter(function(row) { return row.id === "calendar" + label })[0] + return { mode: label.toLowerCase(), label: label + " (" + Keymap.displayFor(binding) + ")" } + }) signal createAt(double startMs) signal copyRequested(string text) signal openRequested(string url) @@ -39,7 +115,7 @@ Item { Binding { target: root.controller property: "clockRunning" - value: root.visible && root.viewMode === "week" + value: root.visible && root.viewMode !== "month" when: root.controller !== null } @@ -55,6 +131,25 @@ Item { onControllerChanged: if (controller && controller.sourcesLoaded) Qt.callLater(root.refresh) + onVisibleChanged: { + if (!visible) { monthOverflow.close(); monthHoverDelay.stop(); hoveredMonthDay = null } + else if (controller && controller.sourcesLoaded) Qt.callLater(root.refresh) + } + + Timer { + interval: 60000 + repeat: true + running: root.visible && !!root.controller && root.controller.sourcesLoaded + onTriggered: if (!root.controller.loading) root.refresh() + } + + Connections { + target: root.Window.window + function onActiveChanged() { + if (root.visible && root.Window.window.active && root.controller && root.controller.sourcesLoaded) + root.refresh() + } + } Connections { target: root.controller @@ -62,18 +157,39 @@ Item { function onSourcesLoadedChanged() { if (root.controller && root.controller.sourcesLoaded) root.refresh() } + function onEventsChanged() { + if (root.waitingForEvent) root.resolveRequestedEvent() + if (!root.detailEvent) return + var key = Calendar.eventKey(root.detailEvent) + var matches = root.controller.events.filter(function(event) { return Calendar.eventKey(event) === key }) + if (matches.length === 1) { + if (String(matches[0].etag || "") !== String(root.detailEvent.etag || "")) root.activateEvent(matches[0]) + } + else if (!root.controller.loading) { + var source = root.controller.findSource(root.detailEvent.sourceId) + if (!source || source.enabled !== false) root.closeDetail() + } + } + function onLoadingChanged() { + if (root.controller.loading || !root.detailEvent || root.controller.lastError !== "") return + var source = root.controller.findSource(root.detailEvent.sourceId) + if (source && source.enabled === false) return + var key = Calendar.eventKey(root.detailEvent) + if (!root.controller.events.some(function(event) { return Calendar.eventKey(event) === key })) root.closeDetail() + } } function visibleEvents() { - var range = viewMode === "week" ? weekDays : days + var range = viewMode === "day" || viewMode === "week" ? displayDays : days var values = controller && Array.isArray(controller.events) ? controller.events : [] + if (viewMode === "agenda") values = Calendar.agendaEvents(values, controller ? controller.nowMs : Date.now()) if (range.length === 0) return [] var start = range[0].startMs, end = range[range.length - 1].endMs return values.filter(function(event) { if (!event || !event.start) return false var eventEnd = event.end ? Number(event.end.ms) : Number(event.start.ms) + 1 return Number(event.start.ms) < end && eventEnd > start - }) + }).sort(Calendar.compareEvents) } function moveSelection(offset) { @@ -81,25 +197,64 @@ Item { if (values.length === 0) { selectedEventId = ""; return } var index = -1 for (var i = 0; i < values.length; i++) { - if (String(values[i].uid || "") === selectedEventId) { index = i; break } + if (Calendar.eventKey(values[i]) === selectedEventId) { index = i; break } } if (index < 0) index = Number(offset) < 0 ? values.length : -1 index = Math.max(0, Math.min(values.length - 1, index + Number(offset))) - selectedEventId = String(values[index].uid || "") + selectedEventId = Calendar.eventKey(values[index]) } - function activateEvent(event) { + function activateEvent(event, alreadyDetailed) { + monthOverflow.close() if (!event) return - selectedEventId = String(event.uid || "") + var serial = ++detailReadSerial + selectedEventId = Calendar.eventKey(event) detailEvent = event + detailLoading = false + detailError = "" + var source = controller && typeof controller.findSource === "function" ? controller.findSource(event.sourceId) : null + if (alreadyDetailed || !source || source.kind !== "google" || !controller.service + || controller.service.backendCanGoogleCalendars !== true) return + detailLoading = true + controller.nativeRequest(source, "get", {eventId:event.googleId}, function(result, error) { + if (serial !== root.detailReadSerial || !root.detailEvent + || Calendar.eventKey(root.detailEvent) !== Calendar.eventKey(event)) return + root.detailLoading = false + if (error) { root.detailError = error; return } + var resource + try { resource = JSON.parse(result.body) } catch (e) { root.detailError = "Could not read the event details"; return } + var values = Calendar.eventsFromGoogle({items:[resource]}, source.id) + if (values.length === 1 && Calendar.eventKey(values[0]) === Calendar.eventKey(event)) root.detailEvent = values[0] + else root.detailError = "This event is no longer available" + }) } - function closeDetail() { detailEvent = null } + // Escape's first answer while the busy-day preview is up. + function dismissPreview() { + if (!monthOverflow.opened) return false + monthOverflow.close() + monthHoverDelay.stop() + hoveredMonthDay = null + return true + } + + function closeDetail() { detailReadSerial++; detailLoading = false; detailError = ""; waitingForEvent = false; detailEvent = null } + + function reschedule(event, startMs, endMs) { + if (!controller || !event || !event.start || !event.end) return + var refusal = controller.rescheduleRefusal(event) + if (refusal !== "") { controller.lastError = refusal; return } + if ((event.attendees || []).some(function(attendee) { return attendee.self !== true })) { + controller.composeRequested({ editingEvent: event, startMs: startMs, endMs: endMs }) + return + } + controller.updateEvent(event.sourceId, event, Calendar.rescheduleFields(event, startMs, endMs)) + } function activateSelection() { var values = visibleEvents() for (var i = 0; i < values.length; i++) { - if (String(values[i].uid || "") === selectedEventId) { + if (Calendar.eventKey(values[i]) === selectedEventId) { activateEvent(values[i]) return } @@ -108,13 +263,15 @@ Item { } function refresh() { - var range = viewMode === "week" ? weekDays : days + var range = viewMode === "day" || viewMode === "week" ? displayDays : days if (!controller || range.length === 0) return controller.refresh(range[0].startMs, range[range.length - 1].endMs) } function moveMonth(offset) { visibleMonth = new Date(visibleMonth.getFullYear(), visibleMonth.getMonth() + offset, 1) + visibleWeek = new Date(visibleMonth.getFullYear(), visibleMonth.getMonth(), + Math.min(visibleWeek.getDate(), new Date(visibleMonth.getFullYear(), visibleMonth.getMonth() + 1, 0).getDate())) refresh() } @@ -126,20 +283,23 @@ Item { } function movePeriod(offset) { - if (viewMode === "week") { + if (viewMode === "day" || viewMode === "week") { visibleWeek = new Date(visibleWeek.getFullYear(), visibleWeek.getMonth(), - visibleWeek.getDate() + offset * 7) + visibleWeek.getDate() + offset * (viewMode === "day" ? 1 : 7)) + visibleMonth = new Date(visibleWeek.getFullYear(), visibleWeek.getMonth(), 1) refresh() } else moveMonth(offset) } function setView(mode) { - viewMode = mode === "week" ? "week" : "month" + viewMode = ["day", "week", "month", "agenda"].indexOf(mode) >= 0 ? mode : "month" refresh() } function showEvent(eventId, startMs) { selectedEventId = String(eventId || "") + requestedEventStart = Number(startMs) || 0 + waitingForEvent = selectedEventId !== "" viewMode = "month" if (Number(startMs) > 0) { var date = new Date(Number(startMs)) @@ -147,52 +307,141 @@ Item { visibleWeek = date } refresh() + resolveRequestedEvent() + if (!waitingForEvent) return + var separator = selectedEventId.indexOf("\n") + var requested = selectedEventId + var source = separator >= 0 && controller ? controller.findSource(requested.substring(0, separator)) : null + if (source && source.kind === "google" && controller.service.backendCanGoogleCalendars === true) { + controller.nativeRequest(source, "get", { eventId: requested.substring(separator + 1) }, function(result, error) { + if (!root.waitingForEvent || root.selectedEventId !== requested || error) return + var resource + try { resource = JSON.parse(result.body) } catch (e) { return } + var events = Calendar.eventsFromGoogle({ items: [resource] }, source.id) + if (events.length === 1) { root.waitingForEvent = false; root.activateEvent(events[0], true) } + }) + } + } + + function resolveRequestedEvent() { + if (!waitingForEvent || !controller) return + var found = controller.events.filter(function(event) { + return Calendar.eventKey(event) === root.selectedEventId + || (String(event.uid || "") === root.selectedEventId && event.start + && (!root.requestedEventStart || Number(event.start.ms) === root.requestedEventStart)) + }) + if (found.length === 1) { waitingForEvent = false; activateEvent(found[0]) } } Component.onCompleted: refresh() + TextMetrics { + id: monthLabelMetrics + font.family: root.panelFontFamily + font.pixelSize: root.toolbarFontSize + text: "September " + root.visibleMonth.getFullYear() + " β–Ύ" + } + + FontMetrics { + id: monthFontMetrics + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + + TextMetrics { + id: viewLabelMetrics + font.family: root.panelFontFamily + font.pixelSize: root.toolbarFontSize + text: viewSelector.displayText + } + Column { + id: mainColumn anchors.fill: parent anchors.margins: Style.space(14) spacing: Style.space(10) Item { + id: calendarToolbar + objectName: "calendar-toolbar" + parent: root.toolbarHost || mainColumn + visible: root.visible && !root.detailOpen width: parent.width - height: Style.space(34) + readonly property bool stacked: width < dateControls.implicitWidth + viewControls.implicitWidth + Style.space(24) + height: stacked ? dateControls.implicitHeight + viewControls.implicitHeight + Style.space(12) + : Math.max(dateControls.implicitHeight, viewControls.implicitHeight) - Row { + RowLayout { + id: dateControls anchors.left: parent.left - anchors.verticalCenter: parent.verticalCenter - spacing: Style.space(10) + anchors.verticalCenter: !calendarToolbar.stacked ? parent.verticalCenter : undefined + anchors.top: calendarToolbar.stacked ? parent.top : undefined + spacing: Style.space(2) - Text { - anchors.verticalCenter: parent.verticalCenter - text: root.viewMode === "week" ? Calendar.weekTitle(root.weekDays) - : root.monthNames[root.visibleMonth.getMonth()] + " " + root.visibleMonth.getFullYear() - color: root.textColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.heading - font.bold: true - textFormat: Text.PlainText + IconTextButton { + text: "β€Ή" + implicitHeight: root.toolbarControlHeight + tooltipText: "Previous period" + ghost: true + foreground: root.textColor + fontFamily: root.panelFontFamily + fontSize: root.toolbarFontSize + onClicked: root.movePeriod(-1) } IconTextButton { - anchors.verticalCenter: parent.verticalCenter - text: "Go to today" + id: dateButton + objectName: "calendar-date-picker" + text: (root.viewMode === "day" ? Qt.formatDate(root.visibleWeek, "d MMMM yyyy") + : root.viewMode === "week" ? Calendar.weekTitle(root.weekDays) + : root.monthNames[root.visibleMonth.getMonth()] + " " + root.visibleMonth.getFullYear()) + " β–Ύ" + implicitHeight: root.toolbarControlHeight + Layout.minimumWidth: root.viewMode === "month" || root.viewMode === "agenda" + ? monthLabelMetrics.advanceWidth + Style.spacing.controlPaddingX * 2 : implicitWidth + tooltipText: "Choose date..." + ghost: true + selected: datePopup.opened + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + fontSize: root.toolbarFontSize + onClicked: { + datePopup.shownMonth = new Date(root.visibleWeek.getFullYear(), root.visibleWeek.getMonth(), 1) + datePopup.open() + } + } + + IconTextButton { + text: "β€Ί" + implicitHeight: root.toolbarControlHeight + tooltipText: "Next period" + ghost: true + foreground: root.textColor + fontFamily: root.panelFontFamily + fontSize: root.toolbarFontSize + onClicked: root.movePeriod(1) + } + + IconTextButton { + text: "Today" + implicitHeight: root.toolbarControlHeight tooltipText: "Show the current date" - foreground: root.accentColor + Layout.leftMargin: Style.space(10) + foreground: root.textColor accent: root.accentColor - // A ghost at the icon buttons' size, like Compose in the header. ghost: true fontFamily: root.panelFontFamily - fontSize: Style.font.caption + fontSize: root.toolbarFontSize onClicked: root.goToday() } + } - Row { + RowLayout { + id: viewControls anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter + anchors.verticalCenter: !calendarToolbar.stacked ? parent.verticalCenter : undefined + anchors.bottom: calendarToolbar.stacked ? parent.bottom : undefined spacing: Style.space(4) Item { @@ -218,40 +467,83 @@ Item { } } - IconTextButton { - text: "Week" - foreground: root.viewMode === "week" ? root.textColor : root.dimColor - fontFamily: root.panelFontFamily - fontSize: Style.font.caption - selected: root.viewMode === "week" - onClicked: root.setView("week") - } - - IconTextButton { - text: "Month" - foreground: root.viewMode === "month" ? root.textColor : root.dimColor - fontFamily: root.panelFontFamily - fontSize: Style.font.caption - selected: root.viewMode === "month" - onClicked: root.setView("month") - } - - IconButton { - iconName: "chevronLeft" - tooltipText: root.viewMode === "week" ? "Previous week" : "Previous month" - foreground: root.dimColor - hoverColor: root.textColor - fontFamily: root.panelFontFamily - onClicked: root.movePeriod(-1) - } - - IconButton { - iconName: "chevronRight" - tooltipText: root.viewMode === "week" ? "Next week" : "Next month" - foreground: root.dimColor - hoverColor: root.textColor - fontFamily: root.panelFontFamily - onClicked: root.movePeriod(1) + ComboBox { + id: viewSelector + objectName: "calendar-view-selector" + implicitWidth: viewLabelMetrics.advanceWidth + leftPadding + rightPadding + implicitHeight: root.toolbarControlHeight + model: root.viewOptions + textRole: "label" + currentIndex: ["day", "week", "month", "agenda"].indexOf(root.viewMode) + onActivated: function(index) { root.setView(root.viewOptions[index].mode) } + leftPadding: Style.space(10) + rightPadding: Style.space(28) + contentItem: Text { + text: viewSelector.displayText + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: root.toolbarFontSize + verticalAlignment: Text.AlignVCenter + } + indicator: ActionIcon { + name: "chevronDown" + x: viewSelector.width - width - Style.space(8) + y: (viewSelector.height - height) / 2 + iconSize: Style.font.iconSmall + color: root.textColor + } + background: Rectangle { + color: viewSelector.popup.opened ? Qt.alpha(root.accentColor, 0.16) + : viewSelector.hovered ? Qt.alpha(root.textColor, 0.08) : "transparent" + radius: Style.cornerRadius + } + delegate: ItemDelegate { + id: viewOption + required property var modelData + required property int index + width: viewSelector.popup.width - Style.space(8) + implicitHeight: Style.spacing.controlHeight + highlighted: viewSelector.highlightedIndex === index + contentItem: Text { + text: viewOption.modelData.label + (viewSelector.currentIndex === viewOption.index ? " βœ“" : "") + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: root.toolbarFontSize + verticalAlignment: Text.AlignVCenter + } + background: Rectangle { + color: viewOption.highlighted ? Qt.alpha(root.accentColor, 0.12) : "transparent" + } + } + popup: Popup { + width: Math.max(viewSelector.width, Style.space(170)) + padding: Style.space(4) + implicitHeight: viewList.contentHeight + padding * 2 + function place() { + var window = viewSelector.Window.window + if (!window) return + var point = viewSelector.mapToItem(window.contentItem, 0, 0) + var top = point.y + viewSelector.height + if (top + height > window.height) top = point.y - height + y = Math.max(0, Math.min(top, window.height - height)) - point.y + x = Math.max(0, Math.min(point.x, window.width - width)) - point.x + } + onOpened: place() + onHeightChanged: if (opened) place() + contentItem: ListView { + id: viewList + clip: true + model: viewSelector.popup.visible ? viewSelector.delegateModel : null + currentIndex: viewSelector.highlightedIndex + } + background: Rectangle { + color: root.backgroundColor + border.color: Style.normalBorderFor(root.textColor, root.accentColor) + radius: Style.cornerRadius + } + } } } @@ -318,6 +610,27 @@ Item { } } + Text { + width: parent.width + visible: !!root.controller && root.controller.lastError !== "" && root.controller.events.length > 0 + text: "Showing available events. Some calendar data may be out of date." + textFormat: Text.PlainText + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + wrapMode: Text.Wrap + } + + CalendarReminderPanel { + width: parent.width + service: root.controller ? root.controller.service : null + textColor: root.textColor + dimColor: root.dimColor + accentColor: root.accentColor + urgentColor: root.urgentColor + panelFontFamily: root.panelFontFamily + } + Row { id: calendarBody width: parent.width @@ -360,45 +673,110 @@ Item { } } - Grid { + Item { id: monthGrid visible: root.viewMode === "month" width: parent.width height: parent.height - y - columns: 7 - rowSpacing: 0 - columnSpacing: 0 + readonly property real weekHeight: height / (root.days.length / 7) + readonly property real eventTop: Style.space(10) + monthFontMetrics.height + readonly property real eventPitch: Style.space(25) + // Leave space for an overflow link even when spanning events fill a week. + readonly property int spanLimit: Math.max(0, Math.floor( + (weekHeight - eventTop - Style.space(5) - monthFontMetrics.height) / eventPitch)) + function visibleLanes(week) { return Math.min(spanLimit, root.monthSpans.laneCounts[week] || 0) } + + HoverHandler { + id: monthHover + onHoveredChanged: root.updateMonthHover() + onPointChanged: root.updateMonthHover() + } Repeater { + id: monthDaysRepeater model: root.days delegate: Rectangle { id: dayCell + objectName: "calendar-month-day-" + modelData.isoDate required property var modelData + required property int index readonly property var dayEvents: Calendar.eventsOnDay( - root.controller ? root.controller.events : [], modelData) + root.controller ? root.controller.events : [], modelData).filter(function(event) { + return !Calendar.spansMultipleDays(event) + }) + readonly property int week: Math.floor(index / 7) + readonly property int hiddenSpans: root.monthSpans.segments.filter(function(segment) { + return segment.week === dayCell.week && segment.lane >= monthGrid.visibleLanes(dayCell.week) + && segment.startColumn <= dayCell.index % 7 && segment.endColumn >= dayCell.index % 7 + }).length + readonly property int overflowCount: hiddenSpans + Math.max(0, dayEvents.length - eventLimit) + readonly property int eventLimit: Calendar.monthEventLimit( + height - eventRows.y - Style.space(5), Style.space(23), eventRows.spacing, + overflowLabel.implicitHeight, hiddenSpans > 0 ? Number.MAX_VALUE : dayEvents.length) + x: index % 7 * width + y: week * height width: monthGrid.width / 7 - height: monthGrid.height / 6 - color: modelData.isoDate === root.todayIso + height: monthGrid.height / (root.days.length / 7) + color: monthOverflow.opened && monthOverflow.dayCell === dayCell + ? Qt.alpha(root.accentColor, 0.08) + : modelData.isoDate === root.todayIso ? root.calendarTodayBackgroundColor : "transparent" - border.width: root.calendarBorderWidth - border.color: root.calendarBorderColor radius: 0 + Rectangle { + width: root.calendarBorderWidth + height: parent.height + color: Qt.alpha(root.calendarBorderColor, 0.25) + } + Rectangle { + width: parent.width + height: root.calendarBorderWidth + color: Qt.alpha(root.calendarBorderColor, 0.25) + } + Rectangle { + visible: dayCell.index % 7 === 6 + anchors.right: parent.right + width: root.calendarBorderWidth + height: parent.height + color: Qt.alpha(root.calendarBorderColor, 0.25) + } + Rectangle { + visible: dayCell.index >= root.days.length - 7 + anchors.bottom: parent.bottom + width: parent.width + height: root.calendarBorderWidth + color: Qt.alpha(root.calendarBorderColor, 0.25) + } + MouseArea { anchors.fill: parent cursorShape: Qt.PointingHandCursor + onPressed: root.beginMonthGesture() + onReleased: root.monthPointerDown = false + onCanceled: root.monthPointerDown = false onClicked: root.createAt(dayCell.modelData.startMs + 9 * 3600000) } + Rectangle { + anchors.centerIn: dayNumber + width: Math.max(dayNumber.implicitWidth + Style.space(8), dayNumber.implicitHeight + Style.space(4)) + height: dayNumber.implicitHeight + Style.space(4) + radius: height / 2 + color: root.accentColor + visible: dayCell.modelData.isoDate === root.todayIso + } + Text { id: dayNumber + height: monthFontMetrics.height anchors.top: parent.top anchors.left: parent.left anchors.margins: Style.space(6) text: dayCell.modelData.day - color: dayCell.modelData.inMonth ? root.textColor : root.dimColor + color: dayCell.modelData.isoDate === root.todayIso ? root.backgroundColor + : dayCell.modelData.inMonth ? root.textColor : root.dimColor opacity: dayCell.modelData.inMonth ? 1 : 0.55 font.family: root.panelFontFamily font.pixelSize: Style.font.caption @@ -407,8 +785,9 @@ Item { } Column { + id: eventRows anchors.top: dayNumber.bottom - anchors.topMargin: Style.space(4) + anchors.topMargin: Style.space(4) + monthGrid.visibleLanes(dayCell.week) * monthGrid.eventPitch anchors.left: parent.left anchors.right: parent.right anchors.leftMargin: Style.space(4) @@ -416,7 +795,7 @@ Item { spacing: Style.space(2) Repeater { - model: Math.min(dayCell.dayEvents.length, 3) + model: Math.min(dayCell.dayEvents.length, dayCell.eventLimit) delegate: Rectangle { id: monthEvent required property int index @@ -424,11 +803,11 @@ Item { readonly property color eventColor: calendarPalette.colorFor( root.controller ? root.controller.colorKeyFor(eventData.sourceId) : "") width: parent.width - height: Style.space(18) - radius: 0 + height: Style.space(23) + radius: Style.space(3) color: Qt.rgba(eventColor.r, eventColor.g, eventColor.b, - eventData && String(eventData.uid || "") === root.selectedEventId ? 0.28 : 0.15) - border.width: eventData && String(eventData.uid || "") === root.selectedEventId ? 2 : 1 + eventData && Calendar.eventKey(eventData) === root.selectedEventId ? 0.28 : 0.15) + border.width: eventData && Calendar.eventKey(eventData) === root.selectedEventId ? 2 : 0 border.color: eventColor Rectangle { @@ -450,7 +829,8 @@ Item { var time = event.start && !event.start.allDay ? Calendar.two(new Date(event.start.ms).getHours()) + ":" + Calendar.two(new Date(event.start.ms).getMinutes()) + " " : "" - return time + (event.summary || "Untitled event") + var title = String(event.summary || "Untitled event") + return monthEvent.width < Style.space(140) ? title + (time ? " Β· " + time.trim() : "") : time + title } color: root.textColor font.family: root.panelFontFamily @@ -462,19 +842,125 @@ Item { MouseArea { anchors.fill: parent cursorShape: Qt.PointingHandCursor - onClicked: root.activateEvent(monthEvent.eventData) + preventStealing: true + property point initial: Qt.point(0, 0) + onPressed: function(mouse) { root.beginMonthGesture(); initial = mapToItem(monthGrid, mouse.x, mouse.y) } + onCanceled: root.monthPointerDown = false + onReleased: function(mouse) { + root.monthPointerDown = false + var point = mapToItem(monthGrid, mouse.x, mouse.y) + if (Math.abs(point.x - initial.x) + Math.abs(point.y - initial.y) < 6) { + root.activateEvent(monthEvent.eventData) + return + } + if (!root.controller || root.controller.rescheduleRefusal(monthEvent.eventData) !== "") return + if (point.x < 0 || point.y < 0 || point.x >= monthGrid.width || point.y >= monthGrid.height) return + var rows = root.days.length / 7 + var from = Math.floor(initial.y / (monthGrid.height / rows)) * 7 + Math.floor(initial.x / (monthGrid.width / 7)) + var to = Math.floor(point.y / (monthGrid.height / rows)) * 7 + Math.floor(point.x / (monthGrid.width / 7)) + var range = Calendar.gestureRange(monthEvent.eventData, to - from, 0, "") + if (range) root.reschedule(monthEvent.eventData, range.start, range.end) + } } } } Text { - visible: dayCell.dayEvents.length > 3 + id: overflowLabel + visible: dayCell.overflowCount > 0 width: parent.width - text: "+" + (dayCell.dayEvents.length - 3) + " more" + text: "+" + dayCell.overflowCount + " more..." color: root.dimColor font.family: root.panelFontFamily font.pixelSize: Style.font.caption textFormat: Text.PlainText + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: { root.visibleWeek = new Date(dayCell.modelData.startMs); root.setView("day") } + } + } + } + } + } + + Repeater { + model: root.monthSpans.segments + delegate: Rectangle { + id: spanBar + required property var modelData + objectName: "calendar-month-span-" + String(modelData.event.googleId || modelData.event.uid) + "-" + modelData.week + readonly property var eventData: modelData.event + readonly property color eventColor: calendarPalette.colorFor( + root.controller ? root.controller.colorKeyFor(eventData.sourceId) : "") + visible: modelData.lane < monthGrid.visibleLanes(modelData.week) + x: modelData.startColumn * monthGrid.width / 7 + Style.space(4) + y: modelData.week * monthGrid.weekHeight + monthGrid.eventTop + modelData.lane * monthGrid.eventPitch + width: (modelData.endColumn - modelData.startColumn + 1) * monthGrid.width / 7 - Style.space(8) + height: Style.space(23) + radius: Style.space(3) + color: Qt.alpha(eventColor, Calendar.eventKey(eventData) === root.selectedEventId ? 0.28 : 0.15) + border.color: eventColor + border.width: Calendar.eventKey(eventData) === root.selectedEventId ? 1 : 0 + Rectangle { + anchors.left: parent.left + height: parent.height + width: Style.space(3) + color: spanBar.eventColor + } + Text { + anchors.left: parent.left + anchors.leftMargin: Style.space(6) + anchors.verticalCenter: parent.verticalCenter + text: spanBar.modelData.continuesBefore ? "β€Ή" : "" + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + Text { + anchors.fill: parent + anchors.leftMargin: Style.space(spanBar.modelData.continuesBefore ? 18 : 6) + anchors.rightMargin: Style.space(spanBar.modelData.continuesAfter ? 18 : 6) + verticalAlignment: Text.AlignVCenter + text: (spanBar.eventData.start.allDay ? "" : Calendar.timeLabel(spanBar.eventData.start.ms) + " ") + + String(spanBar.eventData.summary || "Untitled event") + textFormat: Text.PlainText + elide: Text.ElideRight + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + Text { + anchors.right: parent.right + anchors.rightMargin: Style.space(6) + anchors.verticalCenter: parent.verticalCenter + text: spanBar.modelData.continuesAfter ? "β€Ί" : "" + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + preventStealing: true + property point initial: Qt.point(0, 0) + onPressed: function(mouse) { root.beginMonthGesture(); initial = mapToItem(monthGrid, mouse.x, mouse.y) } + onCanceled: root.monthPointerDown = false + onReleased: function(mouse) { + root.monthPointerDown = false + var point = mapToItem(monthGrid, mouse.x, mouse.y) + if (Math.abs(point.x - initial.x) + Math.abs(point.y - initial.y) < 6) { + root.activateEvent(spanBar.eventData) + return + } + if (!root.controller || root.controller.rescheduleRefusal(spanBar.eventData) !== "") return + if (point.x < 0 || point.y < 0 || point.x >= monthGrid.width || point.y >= monthGrid.height) return + var from = Math.floor(initial.y / monthGrid.weekHeight) * 7 + Math.floor(initial.x / (monthGrid.width / 7)) + var to = Math.floor(point.y / monthGrid.weekHeight) * 7 + Math.floor(point.x / (monthGrid.width / 7)) + var range = Calendar.gestureRange(spanBar.eventData, to - from, 0, "") + if (range) root.reschedule(spanBar.eventData, range.start, range.end) } } } @@ -484,10 +970,10 @@ Item { WeekCalendarView { width: parent.width height: parent.height - y - visible: root.viewMode === "week" + visible: root.viewMode === "day" || root.viewMode === "week" controller: root.controller nowMs: root.controller ? root.controller.nowMs : 0 - days: root.weekDays + days: root.displayDays textColor: root.textColor backgroundColor: root.backgroundColor accentColor: root.accentColor @@ -499,14 +985,301 @@ Item { panelFontFamily: root.panelFontFamily selectedEventId: root.selectedEventId onCreateAt: function(startMs) { root.createAt(startMs) } + onCreateRange: function(startMs, endMs) { + if (root.controller) root.controller.composeRequested({ startMs: startMs, endMs: endMs }) + } + onCreateAllDay: function(startMs, endMs) { + if (root.controller) root.controller.composeRequested({ startMs: startMs, endMs: endMs, allDay: true }) + } + onEventRescheduled: function(event, startMs, endMs) { root.reschedule(event, startMs, endMs) } onEventActivated: function(event) { root.activateEvent(event) } } + + ListView { + id: agendaList + width: parent.width + height: parent.height - y + visible: root.viewMode === "agenda" + clip: true + spacing: Style.space(6) + model: root.agendaEvents + ScrollBar.vertical: ScrollBar {} + Text { + anchors.centerIn: parent + width: parent.width - Style.space(24) + visible: agendaList.count === 0 + text: "No upcoming events in this date range." + textFormat: Text.PlainText + wrapMode: Text.Wrap + horizontalAlignment: Text.AlignHCenter + color: root.dimColor + font.family: root.panelFontFamily + } + delegate: Rectangle { + id: agendaRow + required property var modelData + width: ListView.view.width + height: Style.space(64) + radius: Style.cornerRadius + color: Calendar.eventKey(modelData) === root.selectedEventId + ? Style.selectedFillFor(root.textColor, root.accentColor) + : agendaMouse.containsMouse ? Style.hoverFillFor(root.textColor, root.accentColor) + : Style.normalFillFor(root.textColor, root.accentColor) + Column { + anchors.fill: parent + anchors.margins: Style.space(8) + spacing: Style.space(4) + Text { + width: parent.width + text: String(agendaRow.modelData.summary || "Untitled event") + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.bold: true + elide: Text.ElideRight + } + Text { + width: parent.width + text: Qt.formatDateTime(new Date(agendaRow.modelData.start.ms), agendaRow.modelData.start.allDay ? "ddd, MMM d" : "ddd, MMM d Β· hh:mm") + + (agendaRow.modelData.start.allDay ? " Β· All day" : "") + textFormat: Text.PlainText + color: root.dimColor + font.family: root.panelFontFamily + elide: Text.ElideRight + } + } + MouseArea { + id: agendaMouse + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.activateEvent(agendaRow.modelData) + } + } + } + } + } + } + } + + // A hover preview, not a QQC.Popup: an open Popup takes every key before the + // window's shortcuts see it, focused or not (tst_popup_keys), so resting the + // pointer on a busy day would silence j, k and every view key until it left. + // An item drawn above the window keeps the keyboard with KeyRouter; Escape + // reaches it through goBack(). + Rectangle { + id: monthOverflow + objectName: "calendar-month-overflow" + parent: root.Window.window ? root.Window.window.contentItem : root + property Item dayCell: null + property bool opened: false + readonly property real padding: Style.space(10) + readonly property var events: dayCell ? Calendar.eventsOnDay(root.controller ? root.controller.events : [], dayCell.modelData) : [] + function open() { opened = true } + function close() { + if (!opened) return + opened = false + monthHoverClose.stop() + } + visible: opened + z: 1000 + width: Math.min(Style.space(400), parent.width - Style.space(16)) + height: Math.min(Style.space(460), parent.height - Style.space(24), overflowHeading.implicitHeight + + overflowEvents.height + padding * 2 + Style.space(10)) + color: root.backgroundColor + border.color: Style.normalBorderFor(root.textColor, root.accentColor) + radius: Style.cornerRadius + function place() { + if (!dayCell) return + var below = dayCell.mapToItem(parent, 0, dayCell.height) + var above = dayCell.mapToItem(parent, 0, 0) + x = Math.max(0, Math.min(above.x, parent.width - width)) + y = Math.max(0, Math.min(below.y + height > parent.height ? above.y - height : below.y, parent.height - height)) + } + onOpenedChanged: if (opened) place() + onHeightChanged: if (opened) place() + // Swallows clicks that miss an event, as the popup's background did, so + // one never lands on the month cell drawn underneath. + MouseArea { anchors.fill: parent; acceptedButtons: Qt.AllButtons; onWheel: function(wheel) { wheel.accepted = true } } + Item { + anchors.fill: parent + anchors.margins: monthOverflow.padding + HoverHandler { + id: overflowHover + onHoveredChanged: { + if (hovered) { monthHoverClose.stop(); monthHoverDelay.stop() } + else { root.hoveredMonthDay = null; monthHoverClose.restart() } + } + } + Text { + id: overflowHeading + width: parent.width + text: monthOverflow.dayCell ? Qt.formatDate(new Date(monthOverflow.dayCell.modelData.startMs), "dddd, d MMMM") + + " Β· " + monthOverflow.events.length + " events" : "" + wrapMode: Text.Wrap + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.body + font.bold: true + } + Flickable { + id: overflowScroll + objectName: "calendar-month-overflow-scroll" + anchors.top: overflowHeading.bottom + anchors.topMargin: Style.space(10) + anchors.bottom: parent.bottom + width: parent.width + clip: true + contentHeight: overflowEvents.height + contentWidth: width + boundsBehavior: Flickable.StopAtBounds + ScrollBar.vertical: ScrollBar { policy: overflowScroll.contentHeight > overflowScroll.height ? ScrollBar.AlwaysOn : ScrollBar.AsNeeded } + WheelScroller { view: overflowScroll } + Column { + id: overflowEvents + width: parent.width + spacing: Style.space(4) + Repeater { + model: monthOverflow.events + delegate: Rectangle { + id: overflowEvent + required property var modelData + objectName: "calendar-overflow-event-" + String(modelData.googleId || modelData.uid) + readonly property color eventColor: calendarPalette.colorFor(root.controller ? root.controller.colorKeyFor(modelData.sourceId) : "") + width: parent.width + height: overflowTitle.implicitHeight + overflowTime.implicitHeight + Style.space(18) + color: Qt.alpha(eventColor, overflowMouse.containsMouse ? 0.25 : 0.12) + radius: Style.cornerRadius + Rectangle { width: Style.space(3); height: parent.height; color: overflowEvent.eventColor } + Text { + id: overflowTitle + x: Style.space(8) + y: Style.space(6) + width: parent.width - Style.space(20) + text: String(overflowEvent.modelData.summary || "Untitled event") + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + Text { + id: overflowTime + x: overflowTitle.x + y: overflowTitle.y + overflowTitle.height + Style.space(2) + width: overflowTitle.width + text: overflowEvent.modelData.start.allDay ? "All day" + : Qt.formatDateTime(new Date(overflowEvent.modelData.start.ms), Calendar.spansMultipleDays(overflowEvent.modelData) ? "d MMM HH:mm" : "HH:mm") + + " – " + Qt.formatDateTime(new Date(overflowEvent.modelData.end.ms), Calendar.spansMultipleDays(overflowEvent.modelData) ? "d MMM HH:mm" : "HH:mm") + textFormat: Text.PlainText + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + MouseArea { + id: overflowMouse + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.activateEvent(overflowEvent.modelData) + } + } + } + } + } + } + } + + Popup { + id: datePopup + parent: root.toolbarHost && root.toolbarHost.Window.window ? root.toolbarHost.Window.window.contentItem : root + property date shownMonth: new Date() + width: Style.space(310) + padding: Style.space(10) + focus: true + function place() { + var below = dateButton.mapToItem(parent, 0, dateButton.height) + var above = dateButton.mapToItem(parent, 0, 0) + x = Math.max(0, Math.min(below.x, parent.width - width)) + y = Math.max(0, Math.min(below.y + height > parent.height ? above.y - height : below.y, parent.height - height)) + } + onOpened: place() + onHeightChanged: if (opened) place() + background: Rectangle { + color: root.backgroundColor + border.color: Style.normalBorderFor(root.textColor, root.accentColor) + radius: Style.cornerRadius + } + contentItem: Column { + spacing: Style.space(8) + Row { + spacing: Style.space(8) + IconTextButton { + text: "β€Ή" + Accessible.name: "Previous month" + foreground: root.textColor + fontFamily: root.panelFontFamily + onClicked: datePopup.shownMonth = new Date(datePopup.shownMonth.getFullYear(), datePopup.shownMonth.getMonth() - 1, 1) + } + Text { + anchors.verticalCenter: parent.verticalCenter + text: Qt.formatDate(datePopup.shownMonth, "MMM yyyy") + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + } + IconTextButton { + text: "β€Ί" + Accessible.name: "Next month" + foreground: root.textColor + fontFamily: root.panelFontFamily + onClicked: datePopup.shownMonth = new Date(datePopup.shownMonth.getFullYear(), datePopup.shownMonth.getMonth() + 1, 1) + } + } + Row { + width: parent.width + Repeater { + model: root.weekdayNames + Text { + required property string modelData + width: parent.width / 7 + text: modelData.substring(0, 2) + textFormat: Text.PlainText + horizontalAlignment: Text.AlignHCenter + color: root.dimColor + font.family: root.panelFontFamily + } + } + } + Grid { + width: parent.width + columns: 7 + Repeater { + model: Calendar.monthDays(datePopup.shownMonth.getFullYear(), datePopup.shownMonth.getMonth(), 1) + IconTextButton { + required property var modelData + width: parent.width / 7 + text: String(modelData.day) + foreground: modelData.inMonth ? root.textColor : root.dimColor + accent: root.accentColor + fontFamily: root.panelFontFamily + selected: modelData.isoDate === Calendar.isoDate(root.visibleWeek) + onClicked: { + root.visibleWeek = new Date(modelData.startMs) + root.visibleMonth = new Date(modelData.year, modelData.month, 1) + datePopup.close() + root.refresh() + } + } } } } } CalendarEventDetail { + refreshing: root.detailLoading + refreshError: root.detailError anchors.fill: parent z: 20 visible: root.detailOpen diff --git a/ui/components/ConfirmDeleteDialog.qml b/ui/components/ConfirmDeleteDialog.qml index 6114d45..3a7a349 100644 --- a/ui/components/ConfirmDeleteDialog.qml +++ b/ui/components/ConfirmDeleteDialog.qml @@ -20,6 +20,13 @@ Item { signal confirmed(var request) + // A request may carry `choices`, each a delete that differs in consequence + // β€” without telling guests, or the whole series. Every one is its own + // button, the last is the default, and the answer travels back as + // `request.choice`. A request without choices is a plain Delete. + readonly property var choices: request && Array.isArray(request.choices) && request.choices.length > 0 + ? request.choices : [{ value: "", label: "Delete" }] + anchors.fill: parent z: 80 @@ -29,15 +36,42 @@ Item { } function close() { dialog.close() } + function confirm(choice) { + var value = dialog.opened ? request : null + dialog.close() + if (!value) return + var answered = {} + for (var key in value) answered[key] = value[key] + answered.choice = choice === undefined ? String(root.choices[root.choices.length - 1].value) : String(choice) + confirmed(answered) + } + + // Cancel, then the choices left to right: the order Tab walks. + function buttonsInOrder() { + var ordered = [cancelButton] + for (var i = 0; i < choiceButtons.count; i++) ordered.push(choiceButtons.itemAt(i)) + return ordered + } + function moveFocus(step) { + var ordered = buttonsInOrder() + var at = 0 + for (var i = 0; i < ordered.length; i++) if (ordered[i] && ordered[i].activeFocus) at = i + var next = ordered[(at + step + ordered.length) % ordered.length] + if (next) next.forceActiveFocus() + } QQC.Popup { id: dialog anchors.centerIn: parent - width: Math.min(Style.space(360), parent.width - Style.space(32)) + width: Math.min(Style.space(420), parent.width - Style.space(32)) padding: Style.space(18) modal: true focus: true closePolicy: QQC.Popup.CloseOnEscape + onOpened: { + var ordered = root.buttonsInOrder() + ordered[ordered.length - 1].forceActiveFocus() + } onClosed: root.request = null background: Rectangle { radius: Style.cornerRadius @@ -47,6 +81,19 @@ Item { } contentItem: Column { spacing: Style.space(14) + // Popups consume keys before the window shortcut map. + Keys.onPressed: function(event) { + if (event.key === Qt.Key_Tab || event.key === Qt.Key_Backtab) { + event.accepted = true + root.moveFocus(event.key === Qt.Key_Backtab || (event.modifiers & Qt.ShiftModifier) ? -1 : 1) + return + } + if (event.key !== Qt.Key_Return && event.key !== Qt.Key_Enter) return + event.accepted = true + if (cancelButton.activeFocus) { root.close(); return } + for (var i = 0; i < choiceButtons.count; i++) + if (choiceButtons.itemAt(i).activeFocus) root.confirm(root.choices[i].value) + } Text { width: parent.width @@ -60,30 +107,40 @@ Item { } Text { width: parent.width + visible: text !== "" textFormat: Text.PlainText - text: String(root.request ? root.request.message : "") + text: String(root.request && root.request.message || "") color: root.dimColor font.family: root.panelFontFamily font.pixelSize: Style.font.bodySmall wrapMode: Text.Wrap } - Row { - anchors.right: parent.right + Flow { + width: parent.width spacing: Style.space(8) Button { + id: cancelButton + objectName: "delete-cancel" text: "Cancel" + bordered: true foreground: root.textColor - bordered: false + fontFamily: root.panelFontFamily + focusable: true onClicked: dialog.close() } - Button { - text: "Delete" - foreground: root.dangerColor - bordered: false - onClicked: { - var value = root.request - dialog.close() - if (value) root.confirmed(value) + Repeater { + id: choiceButtons + model: root.choices + Button { + required property var modelData + required property int index + objectName: index === root.choices.length - 1 ? "delete-confirm" : "delete-choice-" + String(modelData.value) + text: String(modelData.label) + bordered: true + foreground: root.dangerColor + fontFamily: root.panelFontFamily + focusable: true + onClicked: root.confirm(modelData.value) } } } diff --git a/ui/components/InviteCard.qml b/ui/components/InviteCard.qml index 77554c1..3ad67fa 100644 --- a/ui/components/InviteCard.qml +++ b/ui/components/InviteCard.qml @@ -26,6 +26,8 @@ Rectangle { property string response: "" property bool canRespond: false property bool sending: false + property bool fallbackAvailable: false + property string calendarUrl: "" required property color textColor required property color accentColor @@ -34,6 +36,7 @@ Rectangle { required property string panelFontFamily signal respondRequested(string answer) + signal mailOnlyRequested(string answer) signal openRequested(string url) readonly property bool cancelled: !!invite @@ -246,7 +249,7 @@ Rectangle { Row { id: rsvpRow spacing: Style.space(6) - visible: root.canRespond + visible: root.canRespond && !root.fallbackAvailable Text { anchors.verticalCenter: parent.verticalCenter @@ -281,6 +284,45 @@ Rectangle { } } + Column { + width: parent.width + spacing: Style.space(6) + visible: root.fallbackAvailable && root.canRespond + Text { + width: parent.width + text: "Calendar attendance cannot be confirmed here. You can open Calendar or send a reply email only; email does not confirm your Calendar attendance." + textFormat: Text.PlainText + wrapMode: Text.Wrap + color: root.dimColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + } + Flow { + width: parent.width + spacing: Style.space(6) + IconTextButton { + visible: root.calendarUrl !== "" + text: "Open Calendar..." + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + onClicked: root.openRequested(root.calendarUrl) + } + Repeater { + model: [{answer:"accepted",label:"Email Yes"}, {answer:"tentative",label:"Email Maybe"}, {answer:"declined",label:"Email No"}] + IconTextButton { + required property var modelData + text: modelData.label + enabled: !root.sending + foreground: root.textColor + accent: root.accentColor + fontFamily: root.panelFontFamily + onClicked: root.mailOnlyRequested(modelData.answer) + } + } + } + } + // What was answered, where there is no answering to be done β€” somebody // else's reply, a cancelled meeting, an invitation this account is the // organiser of. diff --git a/ui/components/MessageReader.qml b/ui/components/MessageReader.qml index 19fd7d1..9e4a5fc 100644 --- a/ui/components/MessageReader.qml +++ b/ui/components/MessageReader.qml @@ -602,6 +602,8 @@ Item { response: root.service ? root.service.selectedResponse : "" canRespond: !!root.service && root.service.canRespondToInvite sending: !!root.service && root.service.rsvpSending + fallbackAvailable: !!root.service && root.service.rsvpFallbackAvailable === true + calendarUrl: String(root.service && root.service.rsvpCalendarUrl || "") textColor: root.textColor accentColor: root.accentColor dimColor: root.dimColor @@ -610,6 +612,7 @@ Item { onRespondRequested: function(answer) { if (root.service) root.service.rsvp(answer) } + onMailOnlyRequested: function(answer) { if (root.service) root.service.rsvpMailOnly(answer) } // The same rule the body's own links obey: this leaves the app, and it // leaves it through the desktop's browser rather than anything here. onOpenRequested: function(url) { root.openLink(url) } diff --git a/ui/components/SettingsPage.qml b/ui/components/SettingsPage.qml index 7f0c0d3..70f08c4 100644 --- a/ui/components/SettingsPage.qml +++ b/ui/components/SettingsPage.qml @@ -28,6 +28,8 @@ Column { signal clientSetupRequested() signal addRequested() signal editRequested(int index) + signal openCalendarRequested() + signal calendarSignInRequested(int index) readonly property var accounts: service ? service.accountSummaries : [] // A separate list on purpose: accountSummaries carries live mailbox state and @@ -1329,6 +1331,14 @@ Column { accentColor: root.accentColor urgentColor: root.urgentColor panelFontFamily: root.panelFontFamily + onAccountSetupRequested: function(index) { + if (index < 0) return + if (root.accounts[index].calendarProvider === "google") root.calendarSignInRequested(index) + else root.editRequested(index) + } + onClientSetupRequested: root.clientSetupRequested() + onAddAccountRequested: root.addRequested() + onOpenCalendarRequested: root.openCalendarRequested() } PanelSeparator { @@ -1362,7 +1372,7 @@ Column { Text { width: parent.width text: root.auth && root.auth.credentialsPresent - ? String(root.auth.clientDescription || "Google OAuth client") : "No client yet" + ? "Google client configured" : "Google client setup required" color: root.textColor font.family: root.panelFontFamily font.pixelSize: Style.font.bodySmall @@ -1373,7 +1383,7 @@ Column { width: parent.width // Every mailbox signs in through this one client, which is why adding // an account never asks for another. - text: "Shared by every mailbox above" + text: "Advanced setup Β· shared by Gmail and Google Calendar accounts" color: root.dimColor font.family: root.panelFontFamily font.pixelSize: Style.font.caption diff --git a/ui/components/ShortcutHelp.qml b/ui/components/ShortcutHelp.qml index fc45c60..6132f61 100644 --- a/ui/components/ShortcutHelp.qml +++ b/ui/components/ShortcutHelp.qml @@ -152,6 +152,7 @@ Rectangle { Text { text: group.modelData.name + textFormat: Text.PlainText color: root.dimColor font.family: root.panelFontFamily font.pixelSize: Style.font.caption diff --git a/ui/components/WeekCalendarView.qml b/ui/components/WeekCalendarView.qml index 7d20fc7..44dafa7 100644 --- a/ui/components/WeekCalendarView.qml +++ b/ui/components/WeekCalendarView.qml @@ -21,19 +21,50 @@ Item { required property string selectedEventId signal createAt(double startMs) + signal createRange(double startMs, double endMs) + signal createAllDay(double startMs, double endMs) + signal eventRescheduled(var event, double startMs, double endMs) signal eventActivated(var event) + property var dragPreview: null + property var pendingGesture: null + onControllerChanged: pendingGesture = null + Connections { + target: root.controller + ignoreUnknownSignals: true + function onEventUpdated(ok, error) { + if (!ok) root.pendingGesture = null + } + function onLoadingChanged() { + if (!root.controller.loading && !root.controller.eventWriting) root.pendingGesture = null + } + } - readonly property real timeRailWidth: Style.space(52) + readonly property real timeRailWidth: Math.max(Style.space(52), allDayLabelMetrics.advanceWidth + Style.space(12)) + TextMetrics { + id: allDayLabelMetrics + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + text: "all-day" + } readonly property var weekdayNames: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] readonly property var hourRange: Calendar.weekHourRange( controller ? controller.events : [], days, 7, 19) - readonly property int firstHour: hourRange.first - readonly property int lastHour: hourRange.last + readonly property int firstHour: 0 + readonly property int lastHour: 24 + function resetTimeScroll() { + timeline.contentY = Math.max(0, Math.min(hourRange.first * timeline.hourHeight, + timeline.contentHeight - timeline.height)) + } + Component.onCompleted: Qt.callLater(root.resetTimeScroll) + onDaysChanged: Qt.callLater(root.resetTimeScroll) readonly property int hourCount: Math.max(1, lastHour - firstHour) - readonly property int allDayCount: Calendar.maxAllDayEvents( - controller ? controller.events : [], days) - readonly property real allDayHeight: allDayCount > 0 - ? Style.space(6 + allDayCount * 20) : 0 + readonly property var allDayLayout: Calendar.spanLayout( + (controller ? controller.events : []).filter(Calendar.displayInAllDayLane), days) + readonly property int allDayCount: allDayLayout.laneCounts[0] || 0 + readonly property real allDayHeight: Style.space(8 + Math.max(1, allDayCount) * 24) + property int allDayDragStart: -1 + property int allDayDragEnd: -1 + readonly property string todayIso: Calendar.isoDate(new Date(nowMs)) CalendarPalette { id: calendarPalette @@ -57,18 +88,28 @@ Item { Repeater { model: root.days delegate: Item { + id: dayHeader required property var modelData required property int index - width: (dayHeaders.width - root.timeRailWidth) / 7 + width: (dayHeaders.width - root.timeRailWidth) / Math.max(1, root.days.length) height: parent.height + Rectangle { + anchors.centerIn: parent + width: headerLabel.implicitWidth + Style.space(14) + height: headerLabel.implicitHeight + Style.space(6) + radius: Style.cornerRadius + color: Qt.alpha(root.accentColor, 0.12) + visible: dayHeader.modelData.isoDate === root.todayIso + } Text { + id: headerLabel anchors.centerIn: parent - text: root.weekdayNames[index] + " " + modelData.day - color: modelData.isoDate === Calendar.isoDate(new Date()) + text: root.weekdayNames[(new Date(modelData.startMs).getDay() + 6) % 7] + " " + modelData.day + color: modelData.isoDate === root.todayIso ? root.textColor : root.dimColor font.family: root.panelFontFamily font.pixelSize: Style.font.caption - font.bold: modelData.isoDate === Calendar.isoDate(new Date()) + font.bold: modelData.isoDate === root.todayIso textFormat: Text.PlainText } } @@ -77,14 +118,14 @@ Item { Rectangle { id: allDayLane - visible: root.allDayCount > 0 + objectName: "calendar-all-day-lane" anchors.left: parent.left anchors.right: parent.right anchors.top: dayHeaders.bottom height: root.allDayHeight color: "transparent" border.width: root.calendarBorderWidth - border.color: root.calendarBorderColor + border.color: Qt.alpha(root.calendarBorderColor, 0.2) clip: true Text { @@ -101,6 +142,7 @@ Item { } Row { + id: allDayColumns anchors.left: parent.left anchors.leftMargin: root.timeRailWidth anchors.right: parent.right @@ -110,56 +152,112 @@ Item { delegate: Item { id: allDayColumn required property var modelData - readonly property var events: Calendar.allDayEventsOnDay( - root.controller ? root.controller.events : [], modelData) - width: (allDayLane.width - root.timeRailWidth) / 7 + required property int index + width: (allDayLane.width - root.timeRailWidth) / Math.max(1, root.days.length) height: parent.height Rectangle { anchors.fill: parent - color: allDayColumn.modelData.isoDate === Calendar.isoDate(new Date()) + color: allDayMouse.containsMouse || (root.allDayDragStart >= 0 + && allDayColumn.index >= Math.min(root.allDayDragStart, root.allDayDragEnd) + && allDayColumn.index <= Math.max(root.allDayDragStart, root.allDayDragEnd)) + ? Qt.alpha(root.accentColor, 0.12) + : allDayColumn.modelData.isoDate === root.todayIso ? root.calendarTodayBackgroundColor : "transparent" border.width: root.calendarBorderWidth - border.color: root.calendarBorderColor + border.color: Qt.alpha(root.calendarBorderColor, 0.2) } - Column { + MouseArea { + id: allDayMouse + objectName: "calendar-all-day-slots-" + allDayColumn.modelData.isoDate anchors.fill: parent - anchors.margins: Style.space(2) - spacing: Style.space(2) - Repeater { - model: allDayColumn.events - delegate: Rectangle { - id: allDayEvent - required property var modelData - readonly property color eventColor: calendarPalette.colorFor( - root.controller ? root.controller.colorKeyFor(modelData.sourceId) : "") - width: parent.width - height: Style.space(18) - color: Qt.rgba(eventColor.r, eventColor.g, eventColor.b, - String(modelData.uid || "") === root.selectedEventId ? 0.3 : 0.16) - border.width: String(modelData.uid || "") === root.selectedEventId ? 2 : 1 - border.color: eventColor - clip: true + hoverEnabled: true + cursorShape: Qt.CrossCursor + preventStealing: true + function selectTo(x, y) { + var point = mapToItem(allDayColumns, x, y) + root.allDayDragEnd = Math.max(0, Math.min(root.days.length - 1, Math.floor(point.x / allDayColumn.width))) + } + onPressed: { + root.allDayDragStart = allDayColumn.index + root.allDayDragEnd = allDayColumn.index + } + onPositionChanged: function(mouse) { if (pressed) selectTo(mouse.x, mouse.y) } + onReleased: function(mouse) { + selectTo(mouse.x, mouse.y) + root.createAllDay(root.days[Math.min(root.allDayDragStart, root.allDayDragEnd)].startMs, + root.days[Math.max(root.allDayDragStart, root.allDayDragEnd)].endMs) + root.allDayDragStart = -1 + root.allDayDragEnd = -1 + } + onCanceled: { root.allDayDragStart = -1; root.allDayDragEnd = -1 } + } - Text { - anchors.fill: parent - anchors.leftMargin: Style.space(4) - anchors.rightMargin: Style.space(3) - verticalAlignment: Text.AlignVCenter - text: allDayEvent.modelData.summary || "Untitled event" - color: root.textColor - font.family: root.panelFontFamily - font.pixelSize: Style.font.caption - elide: Text.ElideRight - textFormat: Text.PlainText - } - MouseArea { - anchors.fill: parent - cursorShape: Qt.PointingHandCursor - onClicked: root.eventActivated(allDayEvent.modelData) - } - } + } + } + } + Item { + anchors.left: parent.left + anchors.leftMargin: root.timeRailWidth + anchors.right: parent.right + height: parent.height + Repeater { + model: root.allDayLayout.segments + delegate: Rectangle { + id: allDayEvent + required property var modelData + readonly property var eventData: modelData.event + objectName: "calendar-all-day-event-" + String(eventData.googleId || eventData.uid) + readonly property color eventColor: calendarPalette.colorFor( + root.controller ? root.controller.colorKeyFor(eventData.sourceId) : "") + x: modelData.startColumn * parent.width / Math.max(1, root.days.length) + Style.space(2) + y: Style.space(2) + modelData.lane * Style.space(24) + width: (modelData.endColumn - modelData.startColumn + 1) * parent.width / Math.max(1, root.days.length) - Style.space(4) + height: Style.space(22) + color: Qt.alpha(eventColor, Calendar.eventKey(eventData) === root.selectedEventId ? 0.3 : 0.16) + border.width: Calendar.eventKey(eventData) === root.selectedEventId ? 1 : 0 + border.color: eventColor + clip: true + + Text { + anchors.fill: parent + anchors.leftMargin: Style.space(4) + anchors.rightMargin: Style.space(3) + verticalAlignment: Text.AlignVCenter + text: (allDayEvent.modelData.continuesBefore ? "β€Ή " : "") + + (allDayEvent.eventData.start.allDay ? "" : "Timed Β· ") + + String(allDayEvent.eventData.summary || "Untitled event") + + (allDayEvent.modelData.continuesAfter ? " β€Ί" : "") + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + elide: Text.ElideRight + textFormat: Text.PlainText + } + MouseArea { + id: allDayEventMouse + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.eventActivated(allDayEvent.eventData) + } + ToolTip { + visible: allDayEventMouse.containsMouse + delay: 500 + contentItem: Text { + text: String(allDayEvent.eventData.summary || "Untitled event") + + (allDayEvent.eventData.start.allDay ? "" : "\n" + + Qt.formatDateTime(new Date(allDayEvent.eventData.start.ms), "ddd d MMM, HH:mm") + + " – " + Qt.formatDateTime(new Date(allDayEvent.eventData.end.ms), "ddd d MMM, HH:mm")) + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + } + background: Rectangle { + color: root.backgroundColor + border.color: Qt.alpha(root.textColor, 0.25) + radius: Style.cornerRadius } } } @@ -169,13 +267,14 @@ Item { Flickable { id: timeline + objectName: "calendar-time-scroll" WheelScroller { view: timeline } anchors.left: parent.left anchors.right: parent.right - anchors.top: root.allDayCount > 0 ? allDayLane.bottom : dayHeaders.bottom + anchors.top: allDayLane.bottom anchors.bottom: parent.bottom - readonly property real hourHeight: Math.max(Style.space(28), height / root.hourCount) + readonly property real hourHeight: Math.max(Style.space(60), height / root.hourCount) contentWidth: width contentHeight: Math.max(height, hourHeight * root.hourCount) clip: true @@ -211,7 +310,7 @@ Item { anchors.right: parent.right anchors.top: parent.top height: root.calendarBorderWidth - color: root.calendarBorderColor + color: Qt.alpha(root.calendarBorderColor, 0.18) } } } @@ -253,42 +352,78 @@ Item { id: dayColumn required property var modelData readonly property var dayEvents: Calendar.eventsOnDay( - root.controller ? root.controller.events : [], modelData).filter(function(event) { - return event && event.start && !event.start.allDay - }) - width: (timeline.width - root.timeRailWidth) / 7 + (root.controller ? root.controller.events : []).map(function(event) { + if (!root.pendingGesture || Calendar.eventKey(event) !== root.pendingGesture.key) return event + var moved = {} + for (var key in event) moved[key] = event[key] + moved.start = { ms: root.pendingGesture.start } + moved.end = { ms: root.pendingGesture.end } + return moved + }), modelData) + readonly property var positionedEvents: Calendar.timedLayout(dayEvents, modelData) + width: (timeline.width - root.timeRailWidth) / Math.max(1, root.days.length) height: parent.height Rectangle { anchors.fill: parent - color: dayColumn.modelData.isoDate === Calendar.isoDate(new Date()) + color: dayColumn.modelData.isoDate === root.todayIso ? root.calendarTodayBackgroundColor : "transparent" border.width: root.calendarBorderWidth - border.color: root.calendarBorderColor + border.color: Qt.alpha(root.calendarBorderColor, 0.18) } MouseArea { + objectName: "calendar-time-slots-" + dayColumn.modelData.isoDate anchors.fill: parent cursorShape: Qt.CrossCursor - onClicked: root.createAt(Calendar.slotStart(dayColumn.modelData, - mouseY, root.firstHour, timeline.hourHeight, 30)) + preventStealing: true + property real initialY: 0 + property var selection: null + function selectTo(y) { + var first = Calendar.slotStart(dayColumn.modelData, Math.min(initialY, y), root.firstHour, timeline.hourHeight, 15) + var last = Calendar.slotStart(dayColumn.modelData, Math.max(initialY, y) + timeline.hourHeight / 8, + root.firstHour, timeline.hourHeight, 15) + last = Math.min(dayColumn.modelData.endMs, Math.max(first + 900000, last)) + selection = { start: first, end: last } + var point = dayColumn.mapToItem(timeline.contentItem, 0, 0) + root.dragPreview = { x: point.x, + y: Calendar.eventTop({start:{ms:first}}, dayColumn.modelData, root.firstHour, timeline.hourHeight), + width: dayColumn.width, + height: (last - first) / 3600000 * timeline.hourHeight, + label: Qt.formatTime(new Date(first), "HH:mm") + "–" + Qt.formatTime(new Date(last), "HH:mm") } + } + onPressed: function(mouse) { initialY = mouse.y; selectTo(mouse.y) } + onPositionChanged: function(mouse) { if (pressed) selectTo(mouse.y) } + onReleased: function(mouse) { + selectTo(mouse.y) + root.dragPreview = null + if (Math.abs(mouse.y - initialY) < 6) root.createAt(selection.start) + else root.createRange(selection.start, selection.end) + selection = null + } + onCanceled: { selection = null; root.dragPreview = null } } Repeater { - model: dayColumn.dayEvents + model: dayColumn.positionedEvents delegate: Rectangle { id: eventBlock required property var modelData readonly property color eventColor: calendarPalette.colorFor( - root.controller ? root.controller.colorKeyFor(modelData.sourceId) : "") - x: Style.space(3) - width: dayColumn.width - Style.space(6) - y: Calendar.eventTop(modelData, dayColumn.modelData, + root.controller ? root.controller.colorKeyFor(eventData.sourceId) : "") + readonly property var eventData: modelData.event + readonly property bool canReschedule: !!root.controller + && typeof root.controller.rescheduleRefusal === "function" + && root.controller.rescheduleRefusal(eventData) === "" + x: Style.space(3) + modelData.column * (dayColumn.width - Style.space(6)) / modelData.columns + width: (dayColumn.width - Style.space(6)) / modelData.columns - Style.space(2) + y: Calendar.eventTop(eventData, dayColumn.modelData, root.firstHour, timeline.hourHeight) - height: Calendar.eventHeight(modelData, dayColumn.modelData, timeline.hourHeight) + height: Calendar.eventHeight(eventData, dayColumn.modelData, timeline.hourHeight) radius: Style.cornerRadius - color: Qt.rgba(eventColor.r, eventColor.g, eventColor.b, - String(modelData.uid || "") === root.selectedEventId ? 0.3 : 0.17) - border.width: String(modelData.uid || "") === root.selectedEventId ? 2 : 1 + z: 1 + color: Qt.tint(root.backgroundColor, Qt.alpha(eventColor, + Calendar.eventKey(eventData) === root.selectedEventId ? 0.3 : 0.17)) + border.width: Calendar.eventKey(eventData) === root.selectedEventId ? 1 : 0 border.color: eventColor clip: true @@ -305,36 +440,137 @@ Item { spacing: Style.space(1) Text { width: parent.width - text: eventBlock.modelData.summary || "Untitled event" + text: eventBlock.eventData.summary || "Untitled event" color: root.textColor font.family: root.panelFontFamily font.pixelSize: Style.font.caption font.bold: true + wrapMode: Text.WordWrap + maximumLineCount: eventBlock.height > Style.space(70) ? 2 : 1 elide: Text.ElideRight textFormat: Text.PlainText } Text { width: parent.width - text: Calendar.two(new Date(eventBlock.modelData.start.ms).getHours()) + ":" - + Calendar.two(new Date(eventBlock.modelData.start.ms).getMinutes()) + visible: eventBlock.height >= Style.space(38) + text: Qt.formatTime(new Date(eventBlock.eventData.start.ms), "HH:mm") + + (width >= timeMetrics.advanceWidth ? "–" + Qt.formatTime(new Date(eventBlock.eventData.end.ms), "HH:mm") : "") + elide: Text.ElideRight color: root.dimColor font.family: root.panelFontFamily font.pixelSize: Style.font.caption textFormat: Text.PlainText + TextMetrics { + id: timeMetrics + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption + text: "00:00–00:00" + } } } MouseArea { + id: eventMouse + objectName: "calendar-event-drag-" + String(eventBlock.eventData.googleId || eventBlock.eventData.uid) anchors.fill: parent - cursorShape: Qt.PointingHandCursor - onClicked: root.eventActivated(eventBlock.modelData) + hoverEnabled: true + enabled: !root.pendingGesture && !(root.controller && root.controller.eventWriting) + cursorShape: !eventBlock.canReschedule ? Qt.PointingHandCursor + : mouseY < Style.space(9) || mouseY > height - Style.space(9) + ? Qt.SizeVerCursor : Qt.OpenHandCursor + preventStealing: true + property point initial: Qt.point(0, 0) + property string edge: "" + property bool moved: false + property var proposed: null + onPressed: function(mouse) { + initial = mapToItem(timeline, mouse.x, mouse.y) + edge = mouse.y < Style.space(9) ? "start" : mouse.y > height - Style.space(9) ? "end" : "" + moved = false + proposed = null + } + onPositionChanged: function(mouse) { + if (!pressed || !eventBlock.canReschedule) return + var point = mapToItem(timeline, mouse.x, mouse.y) + if (!moved && Math.abs(point.x - initial.x) + Math.abs(point.y - initial.y) < 6) return + moved = true + var column = Math.max(0, Math.min(root.days.length - 1, + Math.floor((point.x - root.timeRailWidth) / dayColumn.width))) + var initialColumn = Math.floor((initial.x - root.timeRailWidth) / dayColumn.width) + proposed = Calendar.gestureRange(eventBlock.eventData, column - initialColumn, + (point.y - initial.y) / timeline.hourHeight * 60, edge) + if (!proposed) { root.dragPreview = null; return } + var previewDay = root.days[edge === "" ? column : initialColumn] + var previewEvent = { start: {ms: proposed.start}, end: {ms: proposed.end} } + root.dragPreview = { x: root.timeRailWidth + (edge === "" ? column : initialColumn) * dayColumn.width, + y: Calendar.eventTop(previewEvent, previewDay, root.firstHour, timeline.hourHeight), + width: dayColumn.width, height: Calendar.eventHeight(previewEvent, previewDay, timeline.hourHeight), + label: Qt.formatTime(new Date(proposed.start), "HH:mm") + "–" + Qt.formatTime(new Date(proposed.end), "HH:mm") } + } + onReleased: { + root.dragPreview = null + if (moved && proposed) { + var event = eventBlock.eventData + var next = { key: Calendar.eventKey(event), start: proposed.start, end: proposed.end } + root.eventRescheduled(event, proposed.start, proposed.end) + if (root.controller && root.controller.eventWriting) root.pendingGesture = next + } + else if (!moved) root.eventActivated(eventBlock.eventData) + } + onCanceled: { root.dragPreview = null; proposed = null } + } + Rectangle { + anchors.horizontalCenter: parent.horizontalCenter + anchors.top: parent.top + anchors.topMargin: Style.space(3) + width: Math.min(Style.space(24), parent.width * 0.4) + height: Style.space(3) + radius: height / 2 + color: eventBlock.eventColor + visible: eventBlock.canReschedule && (eventMouse.containsMouse || eventMouse.pressed) + } + Rectangle { + anchors.horizontalCenter: parent.horizontalCenter + anchors.bottom: parent.bottom + anchors.bottomMargin: Style.space(3) + width: Math.min(Style.space(24), parent.width * 0.4) + height: Style.space(3) + radius: height / 2 + color: eventBlock.eventColor + visible: eventBlock.canReschedule && (eventMouse.containsMouse || eventMouse.pressed) + } + ToolTip { + visible: eventMouse.containsMouse && !eventMouse.pressed + delay: 500 + contentItem: Text { + text: String(eventBlock.eventData.summary || "Untitled event") + "\n" + + Qt.formatTime(new Date(eventBlock.eventData.start.ms), "HH:mm") + "–" + + Qt.formatTime(new Date(eventBlock.eventData.end.ms), "HH:mm") + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + } + background: Rectangle { + color: root.backgroundColor + border.color: Qt.alpha(root.textColor, 0.25) + radius: Style.cornerRadius + } + } + Text { + anchors.right: parent.right + anchors.bottom: parent.bottom + anchors.margins: Style.space(4) + visible: !!root.pendingGesture && root.pendingGesture.key === Calendar.eventKey(eventBlock.eventData) + text: "Saving" + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.pixelSize: Style.font.caption } } } - // After the events, so a meeting in progress is crossed by the line - // rather than covering it. The dot is what survives a theme whose - // urgent colour sits close to an event's border: a bare rule reads - // as one more hour separator, a rule with a bead on it does not. + // Keep the line behind event text; the gutter time and dot remain + // visible without striking through a meeting's title. Item { readonly property real offset: Calendar.nowOffset( dayColumn.modelData, root.firstHour, root.lastHour, @@ -343,7 +579,7 @@ Item { y: offset width: parent.width height: 0 - z: 1 + z: 0 Rectangle { anchors.left: parent.left anchors.right: parent.right @@ -364,5 +600,26 @@ Item { } } } + Rectangle { + visible: root.dragPreview !== null + x: root.dragPreview ? root.dragPreview.x : 0 + y: root.dragPreview ? root.dragPreview.y : 0 + width: root.dragPreview ? root.dragPreview.width : 0 + height: root.dragPreview ? root.dragPreview.height : 0 + color: Qt.alpha(root.accentColor, 0.2) + border.color: root.accentColor + border.width: 2 + radius: Style.cornerRadius + Text { + anchors.top: parent.top + anchors.left: parent.left + anchors.margins: Style.space(5) + text: root.dragPreview ? root.dragPreview.label || "" : "" + textFormat: Text.PlainText + color: root.textColor + font.family: root.panelFontFamily + font.bold: true + } + } } } diff --git a/ui/components/WindowMoveArea.qml b/ui/components/WindowMoveArea.qml new file mode 100644 index 0000000..83dc208 --- /dev/null +++ b/ui/components/WindowMoveArea.qml @@ -0,0 +1,24 @@ +import QtQuick + +// Keep this below header controls so their pointer handlers win. Empty +// title-bar space delegates movement to the compositor; retaining a QML +// MouseArea grab while moving the native window makes it trail the pointer. +MouseArea { + id: root + required property var nativeWindow + objectName: "app-title-bar-drag-area" + acceptedButtons: Qt.NoButton + hoverEnabled: false + readonly property bool dragsTheWindow: windowMoveHandler.target === null + + DragHandler { + id: windowMoveHandler + enabled: root.enabled + target: null + dragThreshold: 0 + acceptedButtons: Qt.LeftButton + onActiveChanged: { + if (active && root.nativeWindow) root.nativeWindow.startSystemMove() + } + } +} diff --git a/ui/keys/Keymap.js b/ui/keys/Keymap.js index a8a4da5..80c29b9 100644 --- a/ui/keys/Keymap.js +++ b/ui/keys/Keymap.js @@ -13,7 +13,7 @@ // follows it β€” a context that is not text entry parks the focus rather than // leaving it wherever the last click put it. Keeping those two as separate // things is what let a dismissed compose field go on eating j and k. -var CONTEXTS = ["list", "reader", "search", "compose", "page", "calendar", "assistant", "assistantCommands"] +var CONTEXTS = ["list", "reader", "search", "compose", "eventCompose", "eventGuests", "page", "calendar", "assistant", "assistantCommands"] // Shorthands, so a row says where it lives rather than restating the set. var MAIL = ["list", "reader"] @@ -129,12 +129,26 @@ var BINDINGS = [ group: "Calendar", label: "Go to today" }, { id: "calendarWeek", keys: ["w"], contexts: ["calendar"], group: "Calendar", label: "Show week view" }, + { id: "calendarDay", keys: ["d"], contexts: ["calendar"], + group: "Calendar", label: "Show day view" }, + { id: "calendarAgenda", keys: ["a"], contexts: ["calendar"], + group: "Calendar", label: "Show agenda view" }, + { id: "calendarUndo", keys: ["u"], contexts: ["calendar"], + group: "Calendar", label: "Undo the last event change", hint: { calendar: "undo" } }, { id: "calendarMonth", keys: ["m"], contexts: ["calendar"], group: "Calendar", label: "Show month view" }, // Both Enters: the main keyboard's is Return, the numpad's is Enter, and // a hand on the numpad expects the same thing of them. { id: "send", keys: ["Ctrl+Return", "Ctrl+Enter"], contexts: ["compose"], group: "Writing", label: "Send", hint: { compose: "send" } }, + { id: "saveEvent", keys: ["Return", "Enter", "Ctrl+Return", "Ctrl+Enter"], contexts: ["eventCompose"], + group: "Writing", label: "Save and close the event", hint: { eventCompose: "save" } }, + { id: "guestNext", keys: ["Down"], contexts: ["eventGuests"], + group: "Writing", label: "Next guest suggestion" }, + { id: "guestPrevious", keys: ["Up"], contexts: ["eventGuests"], + group: "Writing", label: "Previous guest suggestion" }, + { id: "guestChoose", keys: ["Return", "Enter"], contexts: ["eventGuests"], + group: "Writing", label: "Choose guest suggestion" }, { id: "undoSend", keys: ["Alt+Z"], contexts: ANY, survivesOverlay: true, group: "Writing", label: "Undo send" }, @@ -220,7 +234,7 @@ var BINDINGS = [ { id: "back", keys: ["Escape"], contexts: ANY, survivesOverlay: true, group: "Mailbox", label: "Back, or close the window", - hint: { reader: "back", page: "back", compose: "close", search: "leave" } } + hint: { reader: "back", page: "back", compose: "close", eventCompose: "close", search: "leave" } } ] // A pending send is a transient action over the screen, not a screen of its @@ -230,6 +244,7 @@ function contextFor(state) { var value = state || ({}) if (value.assistantEditing) return value.assistantCommands ? "assistantCommands" : "assistant" if (value.showPage) return "page" + if (value.eventComposing) return value.guestSuggestions ? "eventGuests" : "eventCompose" if (value.composing) return "compose" if (value.searchFocused) return "search" if (value.calendarVisible) return "calendar" diff --git a/ui/providers/OAuth.js b/ui/providers/OAuth.js index dc29517..7f00890 100644 --- a/ui/providers/OAuth.js +++ b/ui/providers/OAuth.js @@ -25,7 +25,8 @@ var CALLBACK_PATH = "/oauth2callback" var SCOPES = [ "https://www.googleapis.com/auth/gmail.modify", "https://www.googleapis.com/auth/gmail.send", - "https://www.googleapis.com/auth/calendar.events" + "https://www.googleapis.com/auth/calendar.events", + "https://www.googleapis.com/auth/calendar.calendarlist.readonly" ] function normalizedPort(value) { diff --git a/ui/providers/Registry.js b/ui/providers/Registry.js index afc7390..23fe4e1 100644 --- a/ui/providers/Registry.js +++ b/ui/providers/Registry.js @@ -29,6 +29,14 @@ function capabilities(values) { } } +function calendarAttendanceMethod(id) { + return id === "gmail" ? "calendar.attendance" : "" +} + +function calendarAttendanceUrl(id, accountId) { + return id === "gmail" ? "https://calendar.google.com/calendar/u/0/r?authuser=" + encodeURIComponent(String(accountId || "")) : "" +} + function mailbox(raw) { var entry = raw || {} var result = { diff --git a/ui/tests/qml/tst_app_compose_pending.qml b/ui/tests/qml/tst_app_compose_pending.qml index dcde6e9..5066e61 100644 --- a/ui/tests/qml/tst_app_compose_pending.qml +++ b/ui/tests/qml/tst_app_compose_pending.qml @@ -309,7 +309,7 @@ Item { wait(20) compare(composer.visible, true) compare(app.navKinds.join(","), "list,eventComposer") - compare(named(app, "key-router").context, "compose") + compare(named(app, "key-router").context, "eventCompose") app.back() compare(composer.opened, false) compare(app.composing, false) diff --git a/ui/tests/qml/tst_app_navigation.qml b/ui/tests/qml/tst_app_navigation.qml index f1b19d8..4fec74d 100644 --- a/ui/tests/qml/tst_app_navigation.qml +++ b/ui/tests/qml/tst_app_navigation.qml @@ -582,7 +582,7 @@ Item { waitForRendering(app) } - function test_header_creation_actions_keep_their_labels() { + function test_header_shows_compose_for_mail_and_view_selector_for_calendar() { var compose = named(app, "compose-button") verify(compose && compose.visible) compare(compose.text, "Compose") @@ -590,10 +590,14 @@ Item { app.showCalendar() waitForRendering(app) - var createEvent = named(app, "create-event-button") - verify(createEvent && createEvent.visible) - compare(createEvent.text, "Create event") - compare(typeof createEvent.iconName, "undefined") + verify(!compose.visible) + compare(named(app, "create-event-button"), null) + var selector = named(app, "calendar-view-selector") + verify(selector && selector.visible) + app.runShortcut("calendarWeek") + compare(selector.currentText, "Week (w)") + app.runShortcut("calendarDay") + compare(selector.currentText, "Day (d)") } function test_status_error_opens_external_diagnosis_once() { mailService.lastError = "Could not confirm AI started. Check the conversation before retrying." diff --git a/ui/tests/qml/tst_backend_runtime.qml b/ui/tests/qml/tst_backend_runtime.qml index 5ea75c3..0653952 100644 --- a/ui/tests/qml/tst_backend_runtime.qml +++ b/ui/tests/qml/tst_backend_runtime.qml @@ -1,6 +1,7 @@ import QtQuick import QtTest import "../../backend" as BackendModule +import "../../backend/Compatibility.js" as Compatibility Item { Component { @@ -21,8 +22,34 @@ Item { } } } + Component { + id: bundledFactory + BackendModule.Runtime { + pluginDir: "/synthetic/plugin" + bundledMode: true + bundledExecutable: "/synthetic/app/omamail" + bundledVersion: "0.10.7" + bundledApiVersion: 5 + } + } TestCase { name: "PrivateRuntime" + // `make app-run` bundles the backend this checkout builds, which answers + // with the unreleased step; a release bundle answers with the pin. + function test_bundle_accepts_the_pin_and_one_step_past_it() { + var runtime = createTemporaryObject(bundledFactory, parent) + runtime.refresh() + compare(runtime.state, "ready") + compare(runtime.requiredApiVersion, 5) + compare(runtime.latestApiVersion, 6) + compare(runtime.unreleasedMethods.length, 0) + for (var api = 5; api <= 7; api++) { + var info = { protocol: 1, version: "0.10.7", apiVersion: api } + compare(Compatibility.accepts(info, runtime.requiredVersion, runtime.requiredApiVersion, + runtime.latestApiVersion), api !== 7, "API " + api) + } + } + function make() { return createTemporaryObject(factory, parent) } function processOf(runtime) { for (var i = 0; i < runtime.children.length; i++) diff --git a/ui/tests/qml/tst_calendar_attendance.qml b/ui/tests/qml/tst_calendar_attendance.qml new file mode 100644 index 0000000..d35f1de --- /dev/null +++ b/ui/tests/qml/tst_calendar_attendance.qml @@ -0,0 +1,150 @@ +import QtQuick +import QtTest +import "../../account" + +TestCase { + name: "CalendarAttendance" + QtObject { + id: backend + property bool ready: true + property int apiVersion: 6 + property var calls: [] + property var callback: null + function call(method, params, done) { + calls = calls.concat([{ method: method, params: params }]) + callback = done + } + } + QtObject { + id: owner + property var backend: null + property bool ready: true + property bool rsvpSending: false + property bool canRespondToInvite: true + property string providerId: "gmail" + property string accountId: "me@example.org" + property string selectedId: "mail-1" + property string receivedAsAddress: "me@example.org" + property string receivedAsName: "Synthetic owner" + property string ownAddress: "me@example.org" + property var selectedMessage: ({messageId:"synthetic-message",threadId:"synthetic-thread"}) + property var sent: [] + property var api: ({sendMessage:function(payload, callback) { + owner.sent = owner.sent.concat([payload]) + callback({}, null) + }}) + property var selectedInvite: ({ uid: "meeting", recurrenceIdMs: 0, organizer: { email: "organizer@example.test" } }) + property string notice: "" + property string failure: "" + property var selectedBody: ({text:"Invitation",source:"plain"}) + property var selectedAttachments: [] + property var selectedImages: [] + property var selectedUnsubscribe: null + property var bodies: ({put:function(id, value) { owner.cachedInvite = value.invite }}) + property var cachedInvite: null + function clearNotice() { notice = "" } + function note(text) { notice = text } + function fail(text) { failure = text } + } + Rsvp { id: action; account: owner } + + function init() { + owner.backend = backend + backend.calls = [] + backend.callback = null + backend.apiVersion = 6 + owner.rsvpSending = false + owner.selectedId = "mail-1" + owner.selectedInvite = { uid: "meeting", recurrenceIdMs: 0, organizer: { email: "organizer@example.test" } } + owner.notice = "" + owner.failure = "" + owner.cachedInvite = null + owner.sent = [] + action.fallbackMessageId = "" + } + + function test_refusal_does_not_fall_back_to_a_reply_email() { + action.run("accepted") + compare(backend.calls.length, 1) + compare(backend.calls[0].method, "calendar.attendance") + compare(backend.calls[0].params.response, "accepted") + verify(owner.rsvpSending) + backend.callback(null, { message: "calendar_invitation_not_found" }) + verify(!owner.rsvpSending) + verify(owner.failure !== "") + compare(owner.notice, "") + } + + function test_request_names_the_invitation_organizer() { + action.run("accepted") + compare(backend.calls[0].params.organizer, "organizer@example.test") + } + + function test_invitation_without_organizer_makes_no_request() { + owner.selectedInvite = { uid: "meeting", recurrenceIdMs: 0 } + action.run("accepted") + action.reconcile() + compare(backend.calls.length, 0) + verify(owner.failure !== "") + } + + function test_organizer_mismatch_exposes_only_explicit_mail_fallback() { + action.run("declined") + backend.callback(null, { message: "calendar_organizer_mismatch" }) + verify(action.fallbackAvailable) + compare(owner.cachedInvite, null) + compare(owner.notice, "") + } + + function test_old_backend_is_refused_before_request() { + backend.apiVersion = 5 + action.run("TENTATIVE") + compare(backend.calls.length, 0) + verify(owner.failure !== "") + compare(owner.sent.length, 0, "a native response must not silently become an email") + } + + function test_old_backend_offers_an_explicit_email_only_reply() { + backend.apiVersion = 5 + owner.selectedInvite = {uid:"meeting",summary:"Synthetic meeting", + organizer:{email:"organizer@example.test"},attendees:[]} + verify(action.fallbackAvailable) + action.run("accepted", true) + compare(backend.calls.length, 0) + compare(owner.sent.length, 1) + compare(owner.notice, "Reply email sent; Calendar attendance is not confirmed") + compare(owner.cachedInvite, null) + compare(owner.selectedInvite.attendees.length, 0) + backend.apiVersion = 6 + verify(!action.fallbackAvailable) + } + + function test_success_is_cached_only_after_readback_confirmation() { + action.run("accepted") + compare(owner.cachedInvite, null) + backend.callback({response:"accepted"}, null) + verify(owner.cachedInvite !== null) + compare(owner.cachedInvite.attendees[0].partstat, "ACCEPTED") + } + + function test_unmatched_invitation_exposes_only_explicit_mail_fallback() { + action.run("tentative") + backend.callback(null, {message:"calendar_invitation_not_found"}) + verify(action.fallbackAvailable) + compare(owner.cachedInvite, null) + owner.selectedId = "different-mail" + verify(!action.fallbackAvailable) + } + + function test_occurrence_uses_original_date_and_late_result_does_not_replace_new_mail() { + owner.selectedInvite = { uid: "meeting", recurrenceIdMs: Date.UTC(2026, 9, 1), + organizer: { email: "organizer@example.test" }, + source: { recurrenceId: "RECURRENCE-ID;VALUE=DATE:20261001" } } + action.run("DECLINED") + compare(backend.calls[0].params.originalStart, "2026-10-01") + owner.selectedId = "mail-2" + backend.callback({ response: "declined" }, null) + compare(owner.selectedInvite.uid, "meeting") + verify(owner.notice !== "") + } +} diff --git a/ui/tests/qml/tst_calendar_controller.qml b/ui/tests/qml/tst_calendar_controller.qml index 0485b05..b8b7eea 100644 --- a/ui/tests/qml/tst_calendar_controller.qml +++ b/ui/tests/qml/tst_calendar_controller.qml @@ -13,6 +13,7 @@ Item { property var nextResult: ({ body: "{}", status: 200 }) property var nextError: null property bool backendCanDiscoverCalendars: true + property bool backendCanGoogleCalendars: false property var discoveryCallback: null property var credentialWrites: [] property var configWrites: [] @@ -70,6 +71,131 @@ Item { property var originalSummaries: JSON.parse(JSON.stringify(mailService.accountSummaries)) + function test_settings_can_target_another_accounts_calendar() { + controller.accountId = "one@gmail.com" + verify(controller.findSource("google:two@gmail.com") === null, + "event writes remain scoped to the current mailbox") + controller.setReminderPolicy("google:two@gmail.com", false, -1) + compare(mailService.configWrites.length, 1) + var saved = JSON.parse(mailService.configWrites[0].payload).sources.filter(function(s) { + return s.id === "google:two@gmail.com" + })[0] + compare(saved.remindersEnabled, false) + mailService.configCallback(true, "") + controller.setDefaultCalendar("google:two@gmail.com") + compare(mailService.configWrites.length, 2) + saved = JSON.parse(mailService.configWrites[1].payload).sources.filter(function(s) { + return s.id === "google:two@gmail.com" + })[0] + compare(saved.preferred, true) + mailService.configCallback(true, "") + } + + function test_legacy_sources_cannot_enter_reminder_polling_or_settings() { + var kinds = ["microsoft", "icloud", "caldav", "hey"] + for (var i = 0; i < kinds.length; i++) { + var source = {id:"legacy",kind:kinds[i],enabled:true,remindersEnabled:true,reminderMinutes:10} + controller.reminderMode = false + compare(controller.sourceIncluded(source), true) + controller.reminderMode = true + compare(controller.sourceIncluded(source), false) + controller.sourceList = {version:1,sources:[source]} + var writes = mailService.configWrites.length + controller.setReminderPolicy("legacy", true, 5) + compare(mailService.configWrites.length, writes) + } + compare(controller.sourceIncluded({kind:"google",enabled:false,remindersEnabled:true}), true) + controller.reminderMode = false + } + + function test_confirmed_delete_carries_the_chosen_consequence() { + mailService.backendCanGoogleCalendars = true + controller.accountId = "one@gmail.com" + controller.sourceList = {version:1,sources:[ + {id:"google:one@gmail.com",kind:"google",accountId:"one@gmail.com",calendarId:"primary",enabled:true}]} + var event = {sourceId:"google:one@gmail.com",googleId:"meeting",recurringEventId:"series", + summary:"Review",eventType:"default",etag:"e1",organizer:{self:true}, + attendees:[{self:true},{email:"sam@example.test"}]} + var request = controller.deleteRequest("google:one@gmail.com", event) + compare(request.choices.length, 3) + request.choice = "none" + verify(controller.confirmDelete(request)) + compare(mailService.requests[mailService.requests.length - 1].params.operation, "delete") + compare(mailService.requests[mailService.requests.length - 1].params.sendUpdates, "none") + compare(event.deleteSendUpdates, undefined, "the event on screen is not changed") + controller.eventWriting = false + mailService.requests = [] + mailService.nextResult = {body:JSON.stringify({id:"series",etag:"s1",summary:"Review", + recurrence:["RRULE:FREQ=WEEKLY"],start:{dateTime:"2026-10-01T10:00:00Z"},end:{dateTime:"2026-10-01T11:00:00Z"}, + organizer:{self:true}})} + request.choice = "series" + verify(controller.confirmDelete(request)) + compare(mailService.requests[0].params.operation, "get") + compare(mailService.requests[0].params.eventId, "series") + compare(mailService.requests[1].params.operation, "delete") + compare(mailService.requests[1].params.eventId, "series") + controller.eventWriting = false + } + + function test_undo_does_not_follow_the_view_to_another_account() { + mailService.backendCanGoogleCalendars = true + controller.accountId = "one@gmail.com" + var change = {source:{id:"google:one@gmail.com",kind:"google",accountId:"one@gmail.com",calendarId:"primary"}, + eventId:"meeting",ifMatch:"etag",body:"{}",sendUpdates:"none",scope:controller.calendarScope} + controller.undoChange = change + controller.accountId = "two@gmail.com" + mailService.requests = [] + controller.undoLastChange() + compare(mailService.requests.length, 0) + compare(controller.undoChange, null) + } + + function test_old_backend_refuses_google_options_instead_of_dropping_them() { + controller.accountId = "one@gmail.com" + controller.sourceList = {version:1,sources:[ + {id:"google:one@gmail.com",kind:"google",accountId:"one@gmail.com",calendarId:"primary",enabled:true,canCreateMeet:true}]} + var start = new Date(2026, 9, 1, 10).getTime() + var base = {title:"Planning",allDay:false,startMs:start,endMs:start + 3600000,location:"",description:"", + recurrence:{enabled:false}} + var asks = [{guestEmails:"guest@example.org"}, {createMeet:true}] + for (var i = 0; i < asks.length; i++) { + var fields = JSON.parse(JSON.stringify(base)) + for (var key in asks[i]) fields[key] = asks[i][key] + compare(controller.createEvent("google:one@gmail.com", fields), false) + } + compare(mailService.requests.length, 0) + var event = {sourceId:"google:one@gmail.com",googleId:"meeting",eventType:"default",organizer:{self:true}, + start:{ms:start},end:{ms:start + 3600000}} + verify(controller.rescheduleRefusal(event) !== "") + mailService.backendCanGoogleCalendars = true + compare(controller.rescheduleRefusal(event), "") + } + + function test_immediate_transfer_sends_only_move_and_uses_new_event_identity() { + mailService.backendCanGoogleCalendars = true + controller.accountId = "one@gmail.com" + controller.sourceList = {version:1,sources:[ + {id:"google:one@gmail.com",kind:"google",accountId:"one@gmail.com",calendarId:"primary",enabled:true}, + {id:"google:family",kind:"google",accountId:"one@gmail.com",calendarId:"family",enabled:true}]} + controller.rangeStart = 0 + controller.rangeEnd = 0 + var event = {googleId:"meeting",eventType:"default",etag:"before",organizer:{self:true}} + mailService.nextResult = {body:JSON.stringify({id:"meeting",etag:"after",summary:"Saved title", + start:{dateTime:"2026-10-01T10:00:00Z"},end:{dateTime:"2026-10-01T11:00:00Z"},organizer:{self:true}})} + var moved = null + verify(controller.transferEvent("google:one@gmail.com","google:family",event,function(value,error) { + compare(error,""); moved=value + })) + compare(mailService.requests.length,1) + compare(mailService.requests[0].params.operation,"move") + compare(mailService.requests[0].params.destination,"family") + compare(mailService.requests[0].params.ifMatch,"before") + compare(mailService.requests[0].params.body,undefined) + compare(moved.sourceId,"google:family") + compare(moved.etag,"after") + compare(controller.eventWriting,false) + } + function init() { // Reset here rather than at the end of each case: a failed compare aborts // the function, so a restore on its last line does not run and one real @@ -79,6 +205,7 @@ Item { mailService.nextResult = ({ body: "{}", status: 200 }) mailService.nextError = null mailService.backendCanDiscoverCalendars = true + mailService.backendCanGoogleCalendars = false mailService.discoveryCallback = null mailService.backend.ready = false mailService.accountSummaries = [ @@ -207,7 +334,7 @@ Item { var cases = [ {message: "auth_signed_out", expected: "Sign in to this mailbox again"}, {message: "calendar_auth_refused", expected: "Sign in to this mailbox again"}, - {message: "calendar_provider_unsupported", expected: "This mailbox does not provide iCloud or Microsoft calendars"}, + {message: "calendar_provider_unsupported", expected: "This mailbox does not support calendar discovery"}, {message: "calendar_timeout", expected: "Calendar discovery timed out"}, {message: "private diagnostic ", expected: "Calendars could not be discovered"} ] diff --git a/ui/tests/qml/tst_calendar_detail_refresh.qml b/ui/tests/qml/tst_calendar_detail_refresh.qml new file mode 100644 index 0000000..39f2a1c --- /dev/null +++ b/ui/tests/qml/tst_calendar_detail_refresh.qml @@ -0,0 +1,156 @@ +import QtQuick +import QtTest +import "../../components" as Views +import "../../calendar/Calendar.js" as Calendar + +Item { + width: 1000 + height: 700 + SystemPalette { id: palette } + property string shortcutFired: "" + Shortcut { sequence: "j"; onActivated: shortcutFired = "j" } + QtObject { + id: serviceFixture + property bool backendCanGoogleCalendars: true + property string calendarPalettePath: "" + } + QtObject { + id: fixture + property var service: serviceFixture + property var source: ({id:"google:test",kind:"google",calendarId:"primary",readOnly:false}) + property var availableSources: ({sources:[source]}) + property var events: [] + property var pending: [] + property bool sourcesLoaded: false + property bool loading: false + property bool clockRunning: false + property bool eventWriting: false + property double nowMs: Date.now() + property string lastError: "" + property string lastErrorKind: "" + function findSource(id) { return source } + function colorKeyFor(id) { return "accent" } + function refresh(start, end) {} + function nativeRequest(source, operation, fields, callback) { + pending = pending.concat([{operation:operation,fields:fields,callback:callback}]) + } + } + Views.CalendarView { + id: view + anchors.fill: parent + controller: fixture + textColor: palette.text + backgroundColor: palette.base + accentColor: palette.highlight + urgentColor: palette.highlight + dimColor: palette.mid + calendarBorderColor: palette.mid + calendarTodayBackgroundColor: palette.alternateBase + calendarBorderWidth: 1 + panelFontFamily: "sans-serif" + } + TestCase { + name: "CalendarDetailRefresh" + when: windowShown + function resource(id, count) { + return {id:id,iCalUID:id,etag:"version-1",summary:"Planning", + start:{dateTime:"2026-10-25T10:00:00Z"},end:{dateTime:"2026-10-25T11:00:00Z"}, + attendees:count === 2 ? [{email:"one@example.test"},{email:"two@example.test"}] + : [{email:"one@example.test"}]} + } + function event(id) { return Calendar.eventsFromGoogle({items:[resource(id,1)]},fixture.source.id)[0] } + function reply(index, id, count) { fixture.pending[index].callback({body:JSON.stringify(resource(id,count))}, "") } + function init() { + view.closeDetail() + fixture.pending = [] + fixture.events = [event("first"),event("second")] + } + function test_click_refreshes_guests_and_same_etag_list_does_not_erase_them() { + view.activateEvent(fixture.events[0]) + compare(fixture.pending.length,1) + compare(fixture.pending[0].operation,"get") + compare(view.detailLoading,true) + reply(0,"first",2) + compare(view.detailEvent.attendees.length,2) + compare(view.detailLoading,false) + fixture.events = [event("first"),event("second")] + compare(view.detailOpen,true) + compare(view.detailEvent.attendees.length,2) + } + function test_previous_event_response_cannot_replace_current_details() { + view.activateEvent(fixture.events[0]) + view.activateEvent(fixture.events[1]) + reply(0,"first",2) + compare(view.detailEvent.googleId,"second") + reply(1,"second",2) + compare(view.detailEvent.attendees.length,2) + } + function test_closed_details_are_not_reopened_by_late_response() { + view.activateEvent(fixture.events[0]) + view.closeDetail() + reply(0,"first",2) + compare(view.detailOpen,false) + } + function test_agenda_model_survives_a_clock_tick() { + view.visibleMonth = new Date(2026,9,1) + fixture.nowMs = Date.UTC(2026,9,20) + view.setView("agenda") + fixture.events = [event("first"),event("second")] + var agenda = view.agendaEvents + compare(agenda.length,2) + fixture.nowMs = Date.UTC(2026,9,20) + 60000 + fixture.events = [event("first"),event("second")] + verify(view.agendaEvents === agenda, "an unchanged agenda keeps its model") + fixture.nowMs = Date.UTC(2026,9,26) + compare(view.agendaEvents.length,0) + fixture.nowMs = Date.now() + view.setView("month") + } + function test_busy_day_preview_leaves_window_shortcuts_live() { + view.visibleMonth = new Date(2026,9,1) + view.setView("month") + var values = [] + for (var i = 0; i < 20; i++) values.push(event("keys-" + i)) + fixture.events = values + wait(0) + var day = findChild(view,"calendar-month-day-2026-10-25") + mouseMove(day,day.width/2,day.height-5) + var preview = findChild(view,"calendar-month-overflow") + tryCompare(preview,"opened",true) + shortcutFired = "" + keyClick(Qt.Key_J) + compare(shortcutFired,"j") + verify(view.dismissPreview()) + compare(preview.opened,false) + verify(!view.dismissPreview()) + mouseMove(view,5,5) + } + function test_overflow_hover_shows_all_events_and_opens_hidden_event() { + view.visibleMonth = new Date(2026,9,1) + view.setView("month") + var values = [] + for (var i = 0; i < 20; i++) values.push(event("busy-" + i)) + fixture.events = values + wait(0) + var day = findChild(view,"calendar-month-day-2026-10-25") + verify(day.overflowCount > 0) + mouseMove(day,day.width/2,day.height-5) + var popup = findChild(view,"calendar-month-overflow") + tryCompare(popup,"opened",true) + compare(popup.events.length,20) + var scroll = findChild(view,"calendar-month-overflow-scroll") + verify(scroll.contentHeight > scroll.height) + mouseMove(scroll,scroll.width/2,10) + wait(350) + compare(popup.opened,true) + var hiddenEvent = findChild(scroll,"calendar-overflow-event-busy-19") + verify(hiddenEvent !== null) + scroll.contentY = Math.min(hiddenEvent.y, scroll.contentHeight - scroll.height) + wait(0) + mouseClick(hiddenEvent,hiddenEvent.width/2,hiddenEvent.height/2) + compare(view.detailEvent.googleId,"busy-19") + compare(popup.opened,false) + view.closeDetail() + } + } +} diff --git a/ui/tests/qml/tst_calendar_event_composer.qml b/ui/tests/qml/tst_calendar_event_composer.qml index 38c1739..bed9794 100644 --- a/ui/tests/qml/tst_calendar_event_composer.qml +++ b/ui/tests/qml/tst_calendar_event_composer.qml @@ -6,12 +6,33 @@ Item { width: 900 height: 600 + QtObject { + id: contacts + property var recipientContacts: [] + property bool backendCanGoogleCalendars: true + property int refreshCalls: 0 + function refreshRecipientContacts() { refreshCalls++ } + } QtObject { id: eventController + property var service: contacts property bool creatingEvent: false property bool eventWriting: false property int createCalls: 0 property int updateCalls: 0 + property var createdFields: null + property var transferCallback: null + function findSource(id) { + for (var i=0;i