From df869a31d4fc077e2b1e171de8959dcd87b6a798 Mon Sep 17 00:00:00 2001 From: Derek Ross Date: Fri, 30 Oct 2026 11:11:44 -0400 Subject: [PATCH] omamobile-omarchy 0.1.17: the lock is back on the glance whenever the screen goes dark MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On the Pixel 7 Pro the glance came back after 15 s on the PIN view, but a power-button press or a tap that woke the screen went straight to the PIN view, and "sometimes the view is reset". The lock blanks the display itself 10 s after the last input, before the glance's 15 s return, and after that the phone may sleep (omamobile-sleepd), which freezes QML timers, so the return never ran. Nothing that turned the screen off told the glance, and the touch that woke a dark screen was delivered to the lock and counted as the glance's tap to show the PIN view. Patch 0023 (revised in place, as it was merged today and nothing has built on it) now brings the glance back, with an empty field, whenever the locked display goes dark: - the lock's own blank bumps a blankSerial in the Service; - a new "omarchy-shell lock dark" call does the same for what blanks it from outside, without touching the display itself. The Service keeps displayDark until the display is lit through the lock again (runWake). While it is dark, a touch or swipe on the glance only lights the screen through the lock, and so does a touch that starts within 400 ms of a wake. The 15 s return is now counted on the wall clock (a 1 s check against when the PIN view last had input), as the lock's blank timer is, so a sleep in between can't freeze it. The computer lock and the fingerprint PAM flow are unchanged. From the maintainer's hands-on test, a tap no longer opens the PIN view. He touched a notification to read it and got the PIN pad. Now only a swipe up opens it, from anywhere, a card included: a clear drag of 8 % of the screen's height, or a quick flick. A typed key and fingerprint unlock still work as before. A tap on a card opens it to more of its text (summary up to 2 lines, body up to 4) and runs nothing; a second tap closes it. A tap elsewhere does nothing, and open cards close when the glance comes back. A sideways swipe on a card dismisses it, as on a phone and in the shade. The first 12 px of a drag decide its way: mostly sideways is a card swipe, mostly vertical is the swipe up, from a card too. The card slides as a toast does (patch 0017's finishSwipe: past 35 % or a flick it flies off, else it springs back). That one notification is then forgotten through the notifications service's forget call (patch 0019), the call the shade makes, so it leaves the history and the shade too. Nothing of it runs, the next one moves up from the "more" line, and the last one leaves "No new notifications". He also asked for the glance to show the notifications the phone's shade shows. It left out Omarchy's own messages (omarchy-action), bare notify-send pings and anything over 24 h old, and grouped one card per app, so three Omarchy messages showed as one. The shade (omamobile.quicksettings NotificationsModel) lists the newest ten of the toasts on screen and the history, which Omarchy's service trims to ten (historyLimit). It has no age limit, leaves no app out and skips only rows with neither summary nor body. The glance now: - uses the same rows; - shows each notification as its own card, newest first, as many as fit above the hint (up to three); - counts every one not shown in "N more from A and B" (or "A, B and 2 others"); - gives each card its age ("2m") as its detail; - names omarchy-action "Omarchy" (with its glyph, as NotificationCard draws it) and notify-send "Notifications". Do-not-disturb now follows the toasts rather than hiding every card: only what still toasts shows (Omarchy's own messages, and a critical notify-send, NotificationLogic.shouldBypassDnd). omamobile-shell 0.2.41 makes the calls: - omamobile-keys calls "lock dark" before the power key turns a locked screen off, and before it powers off the panel behind a new lock; - omamobile-sleepd calls it, bounded by a 3 s timeout, just before each suspend, for a screen that went dark some other way. An older lock without the call ignores it. It also fills the glance's weather line, which had nothing to read. The maintainer's weather is a community home screen widget that fetches on its own and keeps nothing to borrow, so the shell now owns the weather, whatever widgets are placed. A new omamobile-weather user service runs at login and every 30 minutes (omamobile-weather.timer, enabled for every graphical session). It fetches Open-Meteo's current weather, with the same API and words as the shell's weather widget (a test checks the words agree with HomeModel.weatherText for every code). It writes ~/.local/state/omamobile/weather.json atomically: {"at", "temperature" (rounded), "unit", "text", "source"}. Where, in order: - the phone's position: GeoClue at city accuracy, at most every 3 h, asked only while the Location switch runs GeoClue's agent, with a hard timeout. The client is where-am-i, which omamobile-gnss lets through, so a timer never raises a prompt. A failed fix falls back to the last one, up to a day old. - the setting ~/.config/omamobile/weather.json ({"city"} or coordinates, "unit", "location": "auto" or "fixed"; fixed puts it before the position). - the home screen today widget's city (its owl state), or the weather widget's named place. A city is looked up once with Open-Meteo's geocoding and kept by name, and "Town, ST" picks the US state. The unit is the setting's, else the locale's (°F in the US). There is one try per run, and a failure leaves the old reading. There is no IP geolocation, and nothing is fetched without a place. The lock still hides a reading over 3 h old. Tests: - test/lock-glance: - a blank on the PIN view returns to the glance and clears the PIN; - a wake tap and a wake swipe on a dark display don't show the PIN view, and neither does a swipe that starts right after a wake; - a frozen timer (the wall clock 20 s on) returns to the glance; - taps on a card or on empty space don't show the PIN view; - a card opens and closes, and only that card; - a swipe up from a card shows the PIN view; - a short, slow drag doesn't; - three notifications from one app are three cards, and five are three cards plus "2 more from Mail and GitHub"; - a sideways swipe on a card dismisses it (the forget names its file) without showing the PIN view, and the next one moves up; - a short one springs back; - a mostly vertical swipe from a card shows the PIN view; - the last one dismissed, with hidden text, leaves "No new notifications"; - the shade's ten, Omarchy's own and 30 h old notifications show, and do-not-disturb shows only what still toasts. - test/patches.py checks the Service's blank, dark and wake paths. - omamobile-shell: keys.sh and sleepd.sh check the call order. weather.py checks: - the words against HomeModel.weatherText; - the settings and units; - the order of the sources, with GeoClue stubbed (unusable, so the widget's city or the setting; fixed, so the setting; a fix reused for 3 h and up to a day after a failure); - the JSON shape and source, the city cache; - one try that keeps the old reading; - where-am-i's output. Both packages' test/all and tools/pr-check pass. The series applies with --fuzz=0 to the real aarch64 Omarchy 4.0.6-1 (20 applied). Co-Authored-By: Claude Opus 5.5 --- ...a-glance-view-for-touch-only-devices.patch | 494 ++++++++++++++---- .../omamobile-omarchy/test/lock-glance.qml | 339 ++++++++++-- packages/omamobile-omarchy/test/patches.py | 13 +- packages/omamobile-omarchy/version | 2 +- packages/omamobile-shell/README.md | 1 + packages/omamobile-shell/bin/omamobile-keys | 12 +- packages/omamobile-shell/bin/omamobile-sleepd | 5 + .../omamobile-shell/bin/omamobile-weather | 405 ++++++++++++++ packages/omamobile-shell/install | 5 + .../systemd/user/omamobile-weather.service | 11 + .../systemd/user/omamobile-weather.timer | 16 + packages/omamobile-shell/test/all | 12 + packages/omamobile-shell/test/keys.sh | 7 + packages/omamobile-shell/test/sleepd.sh | 6 +- packages/omamobile-shell/test/weather.py | 240 +++++++++ packages/omamobile-shell/version | 2 +- 16 files changed, 1420 insertions(+), 150 deletions(-) create mode 100644 packages/omamobile-shell/bin/omamobile-weather create mode 100644 packages/omamobile-shell/systemd/user/omamobile-weather.service create mode 100644 packages/omamobile-shell/systemd/user/omamobile-weather.timer create mode 100644 packages/omamobile-shell/test/weather.py diff --git a/packages/omamobile-omarchy/patches/0023-lock-a-glance-view-for-touch-only-devices.patch b/packages/omamobile-omarchy/patches/0023-lock-a-glance-view-for-touch-only-devices.patch index c61f162e7..63b08c33a 100644 --- a/packages/omamobile-omarchy/patches/0023-lock-a-glance-view-for-touch-only-devices.patch +++ b/packages/omamobile-omarchy/patches/0023-lock-a-glance-view-for-touch-only-devices.patch @@ -1,34 +1,54 @@ # Lock: a glance view on touch-only devices (the lock-keypad toggle), as a # phone's lock screen opens: the time, the date, the home screen's last -# weather reading and the notifications, grouped by app, over the lock's -# blurred wallpaper. A swipe up, a tap above the fingerprint sensor or a -# typed key (kept in the field) moves to the PIN view, which is the lock as -# before plus a small clock. With an empty field and no input it comes back -# after 15 s, and whenever the lock is shown or the screen is woken (the -# wake call from 0009). Only one view shows outside the short change; the -# other is hidden, so nothing of the PIN view renders or takes touches under -# the glance. Fingerprint unlock is untouched and works from both. +# weather reading and the newest notifications, over the lock's blurred +# wallpaper. Only a swipe up (a clear drag, 8 % of the height, or a quick +# flick, from anywhere, a card included) or a typed key (kept in the field) +# moves to the PIN view, which is the lock as before plus a small clock. A +# tap never does: a tap on a card opens it to more of its text (summary up +# to 2 lines, body up to 4) and runs nothing, a second tap closes it, and a +# tap elsewhere does nothing. The first 12 px of a drag decide its way: +# mostly sideways on a card swipes it as a toast swipes (0017's +# finishSwipe: past 35 % or a flick it flies off), and that one notification +# is forgotten through the notifications service's forget call (0019), the +# call the phone's shade makes, so it leaves the history and the shade too, +# and the next one moves up; mostly vertical is the swipe up. It comes back +# whenever the lock is shown, the +# screen is woken (the wake call from 0009) or the screen goes dark: the +# lock's own blank, or a new "dark" call for what blanks it from outside +# (the phone's power button, and sleep). With an empty field and no input it +# also comes back after 15 s, counted on the wall clock so that a sleep in +# between can't freeze it. A touch on a dark screen, and one within 400 ms +# of a wake, only wakes it, and open cards close again. Only one view shows +# outside the short change; the other is hidden, so nothing of the PIN view +# renders or takes touches under the glance. Fingerprint unlock is untouched +# and works from both. # # The cards are Omarchy's NotificationCard, static as the history uses it, -# one per app (newest three apps, the rest as "N more from A and B"), with -# three new card properties: summaryLines, bodyLines and a detail label. -# Read-only, from the notifications plugin's persisted toasts and history -# (~/.local/state/omarchy/notifications/*.json, history/*.json), none while -# do-not-disturb is on (notifications.json "dnd"), as no toast shows then. +# one per notification, newest first, as many as fit above the hint (up to +# three), then a line for the rest ("N more from A and B", "N more from A, +# B and 2 others"), with three new card properties: summaryLines, bodyLines +# and a detail label (the age, "2m"). +# Read (the forget is the one change) from the notifications plugin's +# persisted toasts and history +# (~/.local/state/omarchy/notifications/*.json, history/*.json): the same +# notifications the phone's shade lists, the newest ten with no age limit, +# Omarchy's own messages (omarchy-action, shown as Omarchy) and notify-send +# included. While do-not-disturb is on (notifications.json "dnd"), only what +# still toasts shows: Omarchy's own messages and a critical notify-send. # The toggle lock-hide-notification-text shows the app name and "Unlock to # read" instead of the text. Weather comes from -# ~/.local/state/omamobile/weather.json, written by the phone shell's weather -# widget, and is hidden when absent or over 3 h old; the lock makes no -# network calls. The clock follows the bar's clockFormat (shell.json), else +# ~/.local/state/omamobile/weather.json, written by the phone shell's +# omamobile-weather service, and is hidden when absent or over 3 h old; the +# lock makes no network calls. The clock follows the bar's clockFormat (shell.json), else # the locale. On a computer the lock is unchanged. # -# Against Omarchy 4.0.6 (edge 4.0.6-1), after 0003, 0009, 0011, 0014 and -# 0017. +# Against Omarchy 4.0.6 (edge 4.0.6-1), after 0003, 0009, 0011, 0014, 0017 +# and 0019. diff --git i/shell/plugins/lock/LockGlance.js w/shell/plugins/lock/LockGlance.js new file mode 100644 --- /dev/null +++ w/shell/plugins/lock/LockGlance.js -@@ -0,0 +1,116 @@ +@@ -0,0 +1,139 @@ +.pragma library +.import "../notifications/NotificationLogic.js" as NotificationLogic + @@ -36,10 +56,15 @@ new file mode 100644 +// 12- or 24-hour choice, the notifications grouped by app, and the weather +// line. Plain functions of their inputs, so the test can drive them. + -+// Up to this many apps get a card; the rest fold into one line. -+var MAX_GROUPS = 3 -+// Older notifications are not news on a lock screen. -+var MAX_AGE_MS = 24 * 60 * 60 * 1000 ++// Up to this many notifications get a card; the rest fold into one line. ++var MAX_CARDS = 3 ++// The notifications the lock sums up are the ones the phone's notification ++// shade lists: the newest ten of the toasts on screen and the history, ++// which the notifications service trims to ten (historyLimit), with no age ++// limit and no app left out. ++var SHADE_LIMIT = 10 ++// NotificationUrgency.Critical, for the do-not-disturb rule. ++var CRITICAL = 2 +// A weather reading older than this is not shown. +var WEATHER_MAX_AGE_MS = 3 * 60 * 60 * 1000 + @@ -65,67 +90,85 @@ new file mode 100644 + return Math.floor(minutes / 60) + "h" +} + -+function firstLine(text) { -+ var lines = String(text || "").split(/\r\n|\r|\n|/i) -+ for (var i = 0; i < lines.length; i++) if (lines[i].trim()) return lines[i].trim() -+ return "" ++ ++// The name a card goes by: Omarchy's own messages (omarchy-action) ++// as Omarchy, a bare notify-send or a nameless sender as Notifications. ++function appName(app) { ++ var name = String(app || "").trim() ++ if (name === "omarchy-action") return "Omarchy" ++ if (!name || name === "notify-send") return "Notifications" ++ return name ++} ++ ++// The shade's rows (see SHADE_LIMIT; a row with neither summary nor body is ++// skipped, as there) from the persisted popup and history files (the ++// notifications plugin's state, one JSON line each, read together). ++function shadeRows(raw) { ++ var rows = NotificationLogic.historyRows(raw, [], 1, 1000) ++ var out = [] ++ for (var i = 0; i < rows.length && out.length < SHADE_LIMIT; i++) { ++ var e = rows[i] ++ if (!String(e.summary || "").trim() && !String(e.body || "").trim()) continue ++ out.push(e) ++ } ++ return out ++} ++ ++// The file names (NotificationLogic.popupFileName) of every notification ++// the files hold, as a set. ++function fileNames(raw) { ++ var rows = NotificationLogic.historyRows(raw, [], 1, 1000) ++ var out = {} ++ for (var i = 0; i < rows.length; i++) out[NotificationLogic.popupFileName(rows[i])] = true ++ return out +} + -+// The persisted popup and history files (the notifications plugin's state, -+// one JSON line each, read together) as cards: newest first, one per app, -+// at most MAX_GROUPS, and what is left over. Omarchy's own action toasts -+// and bare notify-send pings are left out, as the notifications plugin -+// leaves them out of what it keeps while silenced. hideText shows the app -+// name and "Unlock to read" instead of the text, and no sender picture. -+function groups(raw, now, hideText) { -+ var rows = NotificationLogic.historyRows(raw, [], 1, 200) -+ var byApp = {} -+ var order = [] ++// Those rows as cards, one per notification, newest first. While ++// do-not-disturb is on, only what would still toast: Omarchy's own ++// messages, and a critical notify-send (NotificationLogic.shouldBypassDnd). ++// hideText shows the app name and "Unlock to read" instead of the text, and ++// no sender picture. The detail beside the summary is the age ("2m"). ++function cards(raw, now, hideText, dnd) { ++ var rows = shadeRows(raw) ++ var out = [] + for (var i = 0; i < rows.length; i++) { + var e = rows[i] -+ if (NotificationLogic.isEphemeralApp(e.app)) continue -+ if (Number(now) - Number(e.timestamp || 0) > MAX_AGE_MS) continue -+ var name = String(e.app || "").trim() || "Notifications" -+ var key = name.toLowerCase() -+ if (byApp[key]) { byApp[key].count += 1; continue } -+ byApp[key] = { ++ if (dnd && !NotificationLogic.shouldBypassDnd({ appName: e.app, urgency: e.urgency }, CRITICAL)) continue ++ var name = appName(e.app) ++ out.push({ + app: name, + appIcon: e.appIcon, + image: hideText ? "" : e.image, + glyph: e.glyph, + urgency: e.urgency, + timestamp: e.timestamp, -+ summary: hideText ? name : String(e.summary || ""), -+ body: hideText ? "Unlock to read" : firstLine(NotificationLogic.sanitizeBody(e.body, e.app, e.appIcon)), -+ count: 1, ++ summary: hideText ? name : (String(e.summary || "").trim() || name), ++ body: hideText ? "Unlock to read" : NotificationLogic.sanitizeBody(e.body, e.app, e.appIcon), ++ detail: age(e.timestamp, now), + file: NotificationLogic.popupFileName(e) -+ } -+ order.push(byApp[key]) ++ }) + } -+ for (var j = 0; j < order.length; j++) { -+ var g = order[j] -+ g.detail = (g.count > 1 ? g.count + " new, " : "") + age(g.timestamp, now) -+ if (!g.summary) g.summary = g.app -+ } -+ return order ++ return out +} + -+// "6 more from Mail and GitHub" for the apps without a card. ++// The line under the cards for the notifications without one: "5 more from ++// Mail and GitHub", "5 more from Mail, GitHub and 2 others", each app named ++// once, newest first. +function moreText(rest) { + if (!rest || rest.length === 0) return "" -+ var n = 0 + var names = [] + for (var i = 0; i < rest.length; i++) { -+ n += rest[i].count -+ names.push(rest[i].app) ++ var app = String(rest[i].app || "") ++ if (app && names.indexOf(app) < 0) names.push(app) + } ++ if (names.length === 0) return rest.length + " more" + var from = names.length <= 2 ? names.join(" and ") + : names.slice(0, 2).join(", ") + " and " + (names.length - 2) + (names.length === 3 ? " other" : " others") -+ return n + " more from " + from ++ return rest.length + " more from " + from +} + +// notifications.json's do-not-disturb flag: silenced notifications make no -+// toast, so the lock shows none either. ++// toast, so the lock shows only what still toasts (cards). +function doNotDisturb(raw) { + var parsed = NotificationLogic.parseSettings(raw) + return parsed.dnd === true @@ -149,7 +192,7 @@ diff --git i/shell/plugins/lock/LockGlance.qml w/shell/plugins/lock/LockGlance.q new file mode 100644 --- /dev/null +++ w/shell/plugins/lock/LockGlance.qml -@@ -0,0 +1,437 @@ +@@ -0,0 +1,624 @@ +import QtQuick +import Quickshell +import Quickshell.Io @@ -160,12 +203,14 @@ new file mode 100644 +import "LockGlance.js" as Glance + +// The lock's glance view on touch-only devices (the lock-keypad toggle): -+// the time, the date, the weather, the notifications grouped by app and a -+// hint, over the lock's own blurred wallpaper. A swipe up, a tap above the -+// fingerprint sensor or a typed key moves to the PIN view, which is the -+// lock as before plus a small clock; with no input it comes back after -+// 15 s, and whenever the lock is shown or the screen is woken. Fingerprint -+// unlock runs underneath either view, untouched. ++// the time, the date, the weather, the newest notifications and a hint, ++// over the lock's own blurred wallpaper. A tap on a card opens it to more ++// of its text, a sideways swipe dismisses it (as in the shade); only a swipe up or a typed key moves to the PIN view, which ++// is the lock as before plus a small clock; with no input it comes back after ++// 15 s, and whenever the lock is shown, the screen goes dark (any way: the ++// lock's own blank, the power button, sleep) or the screen is woken. The ++// touch that wakes a dark screen only wakes it. Fingerprint unlock runs ++// underneath either view, untouched. +// +// Read-only: the notifications plugin's persisted toasts and history, its +// do-not-disturb flag, the lock-hide-notification-text toggle, the bar's @@ -198,23 +243,38 @@ new file mode 100644 + property string weatherRaw: "" + readonly property double now: clock.date.getTime() + readonly property bool twelveHour: Glance.twelveHour(barClockFormat, Qt.locale().timeFormat(Locale.ShortFormat)) -+ readonly property var groups: active ? Glance.groups(notificationsRaw, now, hideText) : [] -+ readonly property var shownGroups: groups.slice(0, Glance.MAX_GROUPS) ++ // Swiped away: hidden at once by file name, until a read no longer finds ++ // the file (the service's forget runs on its file queue), as the shade ++ // does. A mark the files still show after 15 s lapses (a forget that never ++ // happened), and the card comes back. ++ property var dismissed: ({}) ++ readonly property var cards: active ? Glance.cards(notificationsRaw, now, hideText, doNotDisturb) ++ .filter(function(c) { return !glance.dismissed[c.file] }) : [] ++ readonly property var shownCards: cards.slice(0, Glance.MAX_CARDS) + // How many of those cards fit above the hint (refit). -+ property int fitCount: Glance.MAX_GROUPS -+ readonly property string moreText: Glance.moreText(groups.slice(Math.min(fitCount, shownGroups.length))) ++ property int fitCount: Glance.MAX_CARDS ++ readonly property string moreText: Glance.moreText(cards.slice(Math.min(fitCount, shownCards.length))) ++ // The cards opened to more of their text, by notification file name; ++ // all closed again whenever the glance comes back. ++ property var expanded: ({}) + readonly property string weatherText: active ? Glance.weatherLine(weatherRaw, now) : "" -+ // Where the under-display sensor's part of the screen starts: nothing -+ // here reacts to a tap below it (LockView's keypadClearsSensor). ++ // Where the under-display sensor's part of the screen starts (LockView's ++ // keypadClearsSensor): the hint sits just below it, the cards above. + readonly property real sensorTop: lock && lock.keypadClearsSensor ? height - lock.keypadBottomMargin : height + property double lastActivity: Date.now() + property bool polling: true ++ // A touch on a dark screen only wakes it, as on a phone, and so does one ++ // within this long of a wake (the rest of that touch, or a finger already ++ // on its way). ++ property int wakeGuardMs: 400 ++ property double wakeGuardUntil: 0 + + visible: active + + function show() { + if (!active || (lock && lock.authenticatingPassword)) return + shown = true ++ expanded = ({}) + if (lock.passwordText.length > 0) lock.passwordTextEdited("") + noteActivity() + refresh() @@ -242,12 +302,27 @@ new file mode 100644 + + function noteActivity() { + lastActivity = Date.now() ++ idleTimer.since = lastActivity + if (!active) return + if (!polling) { + polling = true + refresh() + } -+ if (idleTimer.running) idleTimer.restart() ++ } ++ ++ function armWakeGuard() { ++ wakeGuardUntil = Date.now() + wakeGuardMs ++ } ++ ++ // Whether a touch that starts now only wakes the screen; a dark one is ++ // lit through the lock, as any touch on the lock lights it. ++ function wakeTouch() { ++ if (lock.displayDark) { ++ armWakeGuard() ++ lock.wakeRequested() ++ return true ++ } ++ return Date.now() < wakeGuardUntil + } + + function refresh() { @@ -264,7 +339,7 @@ new file mode 100644 + var item = cardsRepeater.itemAt(i) + if (!item) break + var h = item.implicitHeight + (n > 0 ? gap : 0) -+ var needMore = i + 1 < groups.length ++ var needMore = i + 1 < cards.length + if (used + h + (needMore ? moreHeight : 0) > avail) break + used += h + n++ @@ -272,7 +347,65 @@ new file mode 100644 + fitCount = n + } + -+ onShownGroupsChanged: Qt.callLater(refit) ++ onShownCardsChanged: Qt.callLater(refit) ++ ++ // A card swiped off its side: that one notification is forgotten through ++ // the notifications service's forget call (omamobile-omarchy patch 0019), ++ // the call the phone's shade makes, so it leaves the toasts, the history ++ // and the shade too. Nothing of the notification runs. ++ property var forgetQueue: [] ++ function dismiss(file) { ++ if (!file || dismissed[file]) return ++ var marks = {} ++ for (var k in dismissed) marks[k] = dismissed[k] ++ marks[file] = Date.now() ++ dismissed = marks ++ forgetQueue = forgetQueue.concat([file]) ++ noteActivity() ++ Qt.callLater(runForget) ++ } ++ ++ function runForget() { ++ if (forgetProc.running || forgetQueue.length === 0) return ++ forgetProc.command = ["sh", "-c", ++ "dir=$1; shift; for name; do qs ipc -p \"$dir\" call notifications forget \"$name\"; done; exit 0", ++ "sh", Quickshell.shellDir].concat(forgetQueue) ++ forgetQueue = [] ++ forgetProc.running = true ++ } ++ ++ function pruneDismissed(raw) { ++ var present = Glance.fileNames(raw) ++ var marks = {} ++ var any = false ++ for (var k in dismissed) { ++ if (!present[k]) continue ++ if (Date.now() - dismissed[k] > 15000) continue ++ marks[k] = dismissed[k] ++ any = true ++ } ++ dismissed = any ? marks : ({}) ++ } ++ ++ function toggleCard(file) { ++ var next = {} ++ for (var k in expanded) next[k] = expanded[k] ++ if (next[file]) delete next[file] ++ else next[file] = true ++ expanded = next ++ noteActivity() ++ } ++ ++ // The card under a point of the glance, or null. ++ function cardAt(item, x, y) { ++ for (var i = 0; i < cardsRepeater.count; i++) { ++ var card = cardsRepeater.itemAt(i) ++ if (!card || !card.visible) continue ++ var p = item.mapToItem(card, x, y) ++ if (p.x >= 0 && p.y >= 0 && p.x <= card.width && p.y <= card.height) return card ++ } ++ return null ++ } + onHeightChanged: Qt.callLater(refit) + + // A typed key on the glance moves to the PIN view and keeps the key: a @@ -297,7 +430,9 @@ new file mode 100644 + target: glance.lock + enabled: glance.active + function onInputEnabledChanged() { if (glance.lock.inputEnabled) glance.show() } -+ function onWakeSerialChanged() { glance.show() } ++ function onWakeSerialChanged() { glance.armWakeGuard(); glance.show() } ++ function onBlankSerialChanged() { glance.show() } ++ function onDisplayDarkChanged() { if (!glance.lock.displayDark) glance.armWakeGuard() } + function onWakeRequested() { glance.noteActivity() } + // Text that reaches the field another way still shows the PIN view. + function onPasswordTextChanged() { if (glance.showing && glance.lock.passwordText.length > 0) glance.reveal() } @@ -306,13 +441,23 @@ new file mode 100644 + Component.onCompleted: if (active) { refresh(); Qt.callLater(function() { if (glance.showing) glance.forceActiveFocus() }) } + onActiveChanged: if (active) refresh() + -+ // Back to the glance after 15 s on the PIN view with nothing typed. ++ // Back to the glance after 15 s on the PIN view with nothing typed, ++ // counted on the wall clock as the lock's blank timer is: a countdown ++ // frozen by sleep would otherwise pick up where it stopped after resume. + Timer { + id: idleTimer + objectName: "lockGlanceIdle" -+ interval: 15000 ++ property int returnAfter: 15000 ++ // When the PIN view last had input, or the countdown began. ++ property double since: 0 ++ interval: 1000 ++ repeat: true + running: glance.active && !glance.shown && glance.lock.passwordText.length === 0 && !glance.lock.authenticatingPassword -+ onTriggered: glance.show() ++ onRunningChanged: if (running) since = Date.now() ++ onTriggered: { ++ if (!(since > 0)) since = Date.now() ++ else if (Date.now() - since >= returnAfter) glance.show() ++ } + } + + // The notification files have no change signal to watch, so they are read @@ -340,7 +485,18 @@ new file mode 100644 + "--", glance.home + "/.local/state/omarchy/notifications/"] + stdout: StdioCollector { + waitForEnd: true -+ onStreamFinished: glance.notificationsRaw = String(text || "") ++ onStreamFinished: { ++ glance.notificationsRaw = String(text || "") ++ glance.pruneDismissed(glance.notificationsRaw) ++ } ++ } ++ } ++ ++ Process { ++ id: forgetProc ++ onExited: { ++ glance.runForget() ++ glance.refresh() + } + } + @@ -479,7 +635,6 @@ new file mode 100644 + width: header.width + height: Math.max(0, hint.y - Style.space(24) - y) + onHeightChanged: Qt.callLater(glance.refit) -+ visible: !glance.doNotDisturb + + Column { + id: cardsColumn @@ -489,7 +644,7 @@ new file mode 100644 + + Repeater { + id: cardsRepeater -+ model: glance.shownGroups ++ model: glance.shownCards + + NotificationCard { + required property var modelData @@ -506,14 +661,20 @@ new file mode 100644 + summary: modelData.summary + body: modelData.body + detail: modelData.detail -+ summaryLines: 1 -+ bodyLines: 1 ++ readonly property bool open: !!glance.expanded[modelData.file] ++ summaryLines: open ? 2 : 1 ++ bodyLines: open ? 4 : 1 + cornerRadius: Style.cornerRadius + fontFamily: Style.font.family + swipeEnabled: false + closeButtonShown: false -+ // No actions from the lock: a tap asks for the PIN. -+ onCardClicked: glance.reveal() ++ // No actions from the lock: a tap opens or closes the card ++ // (the glance's touch area below does it; this is the same ++ // for a click that reaches the card), and a card swiped off ++ // its side (the touch area moves it, the card's own ++ // finishSwipe from patch 0017 decides) is forgotten. ++ onCardClicked: glance.toggleCard(modelData.file) ++ onCloseRequested: glance.dismiss(modelData.file) + onImplicitHeightChanged: Qt.callLater(glance.refit) + } + } @@ -536,7 +697,7 @@ new file mode 100644 + Text { + objectName: "lockGlanceQuiet" + width: parent.width -+ visible: glance.groups.length === 0 ++ visible: glance.cards.length === 0 + horizontalAlignment: Text.AlignHCenter + textFormat: Text.PlainText + text: "No new notifications" @@ -566,45 +727,117 @@ new file mode 100644 + } + } + -+ // Over everything, cards included (a card only asks for the PIN, like -+ // any tap): a swipe up from anywhere, or a tap above the sensor's part -+ // of the screen, shows the PIN view. A finger resting on the sensor -+ // does neither. ++ // Over everything, cards included. The first 12 px of a drag decide its ++ // way: mostly sideways on a card swipes that card (off its side, past ++ // 35 % or a flick, dismisses it); mostly vertical is the swipe up to the ++ // PIN view (a clear drag, 8 % of the height, or a quick flick), from a ++ // card too. A tap on a card opens or closes it, a tap anywhere else does ++ // nothing, and a touch that wakes a dark screen only wakes it. + MouseArea { + id: swipe + objectName: "lockGlanceSwipe" + anchors.fill: parent + property real startY: 0 ++ property real startX: 0 ++ property double startAt: 0 + property real dragY: 0 -+ onPressed: function(mouse) { startY = mouse.y; dragY = 0 } -+ onPositionChanged: function(mouse) { dragY = mouse.y - startY } ++ // This touch woke the screen (glance.wakeTouch): it does nothing else. ++ property bool wakeOnly: false ++ // "", "x" (a card swipe) or "y" (toward the PIN view), from the first ++ // 12 px of movement. ++ property string axis: "" ++ property var swipeCard: null ++ property real lastX: 0 ++ property double lastAt: 0 ++ property real velocityX: 0 ++ onPressed: function(mouse) { ++ wakeOnly = glance.wakeTouch() ++ startY = mouse.y ++ startX = mouse.x ++ startAt = Date.now() ++ lastX = mouse.x ++ lastAt = startAt ++ velocityX = 0 ++ dragY = 0 ++ axis = "" ++ swipeCard = null ++ } ++ onPositionChanged: function(mouse) { ++ if (wakeOnly) return ++ var dx = mouse.x - startX ++ var dy = mouse.y - startY ++ if (!axis && Math.max(Math.abs(dx), Math.abs(dy)) >= Style.space(12)) { ++ axis = Math.abs(dx) > Math.abs(dy) ? "x" : "y" ++ if (axis === "x") { ++ var card = glance.cardAt(swipe, startX, startY) ++ swipeCard = card && !card.dismissing ? card : null ++ } ++ } ++ if (axis === "y") dragY = dy ++ if (axis === "x" && swipeCard) { ++ var t = Date.now() ++ if (t > lastAt) velocityX = (mouse.x - lastX) * 1000 / (t - lastAt) ++ lastX = mouse.x ++ lastAt = t ++ swipeCard.swipeOffset = dx ++ swipeCard.swipeVelocity = velocityX ++ } ++ } + onReleased: function(mouse) { + var moved = mouse.y - startY + dragY = 0 -+ if (moved < -Style.space(60) || (Math.abs(moved) < Style.space(12) && mouse.y < glance.sensorTop)) glance.reveal() ++ if (wakeOnly) { ++ wakeOnly = false ++ return ++ } ++ if (axis === "x") { ++ if (swipeCard) swipeCard.finishSwipe() ++ swipeCard = null ++ return ++ } ++ var quick = Date.now() - startAt < 300 && moved < -Style.space(24) ++ if (axis === "y" && (moved < -glance.height * 0.08 || quick)) { ++ glance.reveal() ++ return ++ } ++ if (Math.abs(moved) < Style.space(12) && Math.abs(mouse.x - startX) < Style.space(12)) { ++ var card = glance.cardAt(swipe, mouse.x, mouse.y) ++ if (card) glance.toggleCard(card.modelData.file) ++ } ++ } ++ onCanceled: { ++ dragY = 0 ++ wakeOnly = false ++ if (swipeCard) { ++ swipeCard.swipeVelocity = 0 ++ swipeCard.swipeOffset = 0 ++ } ++ swipeCard = null + } -+ onCanceled: dragY = 0 + } + } +} diff --git i/shell/plugins/lock/LockView.qml w/shell/plugins/lock/LockView.qml --- i/shell/plugins/lock/LockView.qml +++ w/shell/plugins/lock/LockView.qml -@@ -31,6 +31,13 @@ +@@ -31,6 +31,16 @@ // The ABC/123 switch in the field swaps either way, so a password with // letters and digits can always be typed. property bool passwordFirst: false + // The glance view (LockGlance.qml) over the PIN view on touch-only + // devices: the PIN view's parts fade in as it goes, and are hidden while it -+ // is up. The lock bumps wakeSerial when the screen is woken, which brings -+ // the glance back. ++ // is up. The lock bumps wakeSerial when the screen is woken and ++ // blankSerial when it goes dark, and each brings the glance back; while ++ // displayDark, a touch only wakes the screen. + property int wakeSerial: 0 ++ property int blankSerial: 0 ++ property bool displayDark: false + readonly property real pinOpacity: 1 - glance.progress + readonly property bool pinVisible: glance.progress < 1 property bool switchedInput: false readonly property bool padShown: keypad && (passwordFirst === switchedInput) readonly property real inputSwitchReserve: keypad ? Math.round(inputSwitch.implicitWidth + 12) : 0 -@@ -73,6 +80,10 @@ +@@ -73,6 +83,10 @@ } function forcePasswordFocus() { @@ -615,7 +848,7 @@ diff --git i/shell/plugins/lock/LockView.qml w/shell/plugins/lock/LockView.qml if (padShown) { keypadKeys.forceActiveFocus() return -@@ -200,7 +211,8 @@ +@@ -200,7 +214,8 @@ Keypad { id: numberPad @@ -625,7 +858,7 @@ diff --git i/shell/plugins/lock/LockView.qml w/shell/plugins/lock/LockView.qml enabled: root.inputEnabled && !root.authenticatingPassword anchors.horizontalCenter: parent.horizontalCenter anchors.bottom: parent.bottom -@@ -226,6 +238,8 @@ +@@ -226,6 +241,8 @@ BorderSurface { id: inputField @@ -634,7 +867,7 @@ diff --git i/shell/plugins/lock/LockView.qml w/shell/plugins/lock/LockView.qml width: root.fieldWidth height: root.fieldHeight anchors.horizontalCenter: parent.horizontalCenter -@@ -365,7 +379,8 @@ +@@ -365,7 +382,8 @@ anchors.bottomMargin: Style.space(18) anchors.horizontalCenter: inputField.horizontalCenter width: parent.width - Style.space(32) @@ -644,7 +877,7 @@ diff --git i/shell/plugins/lock/LockView.qml w/shell/plugins/lock/LockView.qml text: root.padShown ? "Touch the fingerprint sensor or enter your PIN" : "Touch the fingerprint sensor or enter your password" color: Commons.Color.lock.text -@@ -383,9 +398,10 @@ +@@ -383,9 +401,10 @@ Item { id: emergencyButton objectName: "lockEmergencyCall" @@ -657,7 +890,7 @@ diff --git i/shell/plugins/lock/LockView.qml w/shell/plugins/lock/LockView.qml anchors.topMargin: Style.space(20) width: emergencyLabel.implicitWidth + Style.space(40) height: Math.max(Style.space(44), emergencyLabel.implicitHeight + Style.space(16)) -@@ -411,5 +427,12 @@ +@@ -411,5 +430,12 @@ } } } @@ -673,25 +906,56 @@ diff --git i/shell/plugins/lock/LockView.qml w/shell/plugins/lock/LockView.qml diff --git i/shell/plugins/lock/Service.qml w/shell/plugins/lock/Service.qml --- i/shell/plugins/lock/Service.qml +++ w/shell/plugins/lock/Service.qml -@@ -31,6 +31,9 @@ +@@ -31,6 +31,15 @@ property int failedAttempts: 0 property string backgroundPath: "" property int backgroundVersion: 0 + // Bumped by the wake call (a phone's power button): the lock's glance view + // comes back each time the screen is woken. + property int wakeSerial: 0 ++ // Bumped whenever the locked display goes dark: the lock's own blank, or ++ // the dark call (a phone's power button, sleep). The glance view comes ++ // back each time, and displayDark holds until the display is lit through ++ // the lock again, so the touch that wakes a dark screen only wakes it. ++ property int blankSerial: 0 ++ property bool displayDark: false property string lastEvent: "init" property string lastEventAt: "" property bool strandedLock: false -@@ -280,6 +283,7 @@ +@@ -178,14 +187,22 @@ + } + + function runWake() { ++ displayDark = false + if (!wakeProcess.running) wakeProcess.running = true + if (lockRequested) armBlankTimer() + } + + function runBlank() { ++ markDark() + if (!blankProcess.running) blankProcess.running = true + } + ++ function markDark() { ++ if (!lockRequested) return ++ blankSerial += 1 ++ displayDark = true ++ } ++ + function submitPassword(value) { + var password = String(value || "") + if (!lockRequested || authenticatingPassword || password.length === 0) return +@@ -280,6 +297,9 @@ LockView { keypad: root.keypad + wakeSerial: root.wakeSerial ++ blankSerial: root.blankSerial ++ displayDark: root.displayDark id: lockView anchors.fill: parent backgroundPath: root.backgroundPath -@@ -548,6 +552,7 @@ +@@ -548,10 +568,21 @@ // it and re-arm the blank timer (a phone's power button). function wake(): string { if (!root.currentlyLocked()) return "unlocked" @@ -699,6 +963,20 @@ diff --git i/shell/plugins/lock/Service.qml w/shell/plugins/lock/Service.qml root.runWake() return "ok" } + ++ // The locked display went dark some other way than the lock's own blank ++ // (a phone's power button, or just before sleep): back to the glance ++ // view, and the touch that next wakes the screen only wakes it. The ++ // display itself is left as it is. ++ function dark(): string { ++ if (!root.currentlyLocked()) return "unlocked" ++ root.markDark() ++ return "ok" ++ } ++ + function isLocked(): string { + return root.currentlyLocked() ? "true" : "false" + } diff --git i/shell/plugins/notifications/components/NotificationCard.qml w/shell/plugins/notifications/components/NotificationCard.qml --- i/shell/plugins/notifications/components/NotificationCard.qml +++ w/shell/plugins/notifications/components/NotificationCard.qml diff --git a/packages/omamobile-omarchy/test/lock-glance.qml b/packages/omamobile-omarchy/test/lock-glance.qml index be53da5a0..5d51f97d8 100644 --- a/packages/omamobile-omarchy/test/lock-glance.qml +++ b/packages/omamobile-omarchy/test/lock-glance.qml @@ -2,7 +2,8 @@ // The lock's glance view (patch 0023) under qmltestrunner; test/lock-glance // runs this against the patched Omarchy shell. A LockView as the lock // Service makes it on a phone (keypad on, fingerprints set up), with the -// field's text kept here as the Service keeps it. +// field's text kept here as the Service keeps it, and the display lit again +// by a wake request as the Service's runWake lights it. import QtQuick import QtTest import Quickshell @@ -16,6 +17,7 @@ Item { property string password: "" property var submitted: [] + property int wakes: 0 property string notificationsRaw: "" property var view: null @@ -33,6 +35,7 @@ Item { passwordText: harness.password onPasswordTextEdited: function(value) { harness.password = value } onSubmitPassword: function(value) { harness.submitted = harness.submitted.concat([value]) } + onWakeRequested: { displayDark = false; harness.wakes += 1 } } } @@ -85,13 +88,51 @@ Item { function settle() { wait(400) } + // A clear swipe up from (x, y): 200 px, about a fifth of the screen. + function swipeUp(item, x, y) { + mousePress(item, x, y) + for (var d = 10; d <= 200; d += 10) mouseMove(item, x, y - d, -1, Qt.LeftButton) + mouseRelease(item, x, y - 200) + } + + // A drag sideways by dx from (x, y), and up by dy as it goes. + function drag(item, x, y, dx, dy) { + mousePress(item, x, y) + for (var i = 1; i <= 20; i++) mouseMove(item, x + dx * i / 20, y + dy * i / 20, -1, Qt.LeftButton) + mouseRelease(item, x + dx, y + dy) + } + + function visibleCards() { return byName("lockGlanceCard").filter(function(x) { return x.visible }) } + function centre(card) { return card.mapToItem(harness.view, card.width / 2, card.height / 2) } + function forgets() { + return Quickshell.started.filter(function(a) { return a.join(" ").indexOf("call notifications forget") >= 0 }) + } + + // To the PIN view, as a person gets there: a swipe up. + function toPin() { + swipeUp(harness.view, 240, 700) + settle() + } + function init() { harness.password = "" harness.submitted = [] + harness.wakes = 0 harness.notificationsRaw = "" Quickshell.vars = { HOME: harness.home } + Quickshell.started = [] Quickshell.responder = function(argv) { var cmd = argv.join(" ") + // The notifications service's forget: the file goes. + if (cmd.indexOf("call notifications forget") >= 0) { + var names = argv.slice(5) + harness.notificationsRaw = harness.notificationsRaw.split("\n").filter(function(line) { + if (!line) return false + var e = JSON.parse(line) + return names.indexOf(e.timestamp + "-" + e.originalId + ".json") < 0 + }).join("\n") + "\n" + return "" + } return cmd.indexOf("/.local/state/omarchy/notifications/") >= 0 ? harness.notificationsRaw : null } writeFile(".local/state/omarchy/toggles/lock-hide-notification-text", "") @@ -104,8 +145,17 @@ Item { settle() } + // A wake, and past the moment after it in which a touch only wakes. function show() { harness.view.wakeSerial += 1 + wait(500) + } + + // The screen goes dark as the lock Service has it go: the serial, and + // dark until a wake request lights it. + function blank() { + harness.view.blankSerial += 1 + harness.view.displayDark = true settle() } @@ -121,9 +171,8 @@ Item { compare(one("keypadFingerprintHint").visible, false) } - function test_tap_shows_pin_view_alone() { - mouseClick(harness.view, 240, 300) - settle() + function test_swipe_shows_pin_view_alone() { + toPin() compare(glance().showing, false) compare(one("lockGlanceView").visible, false, "the glance is hidden, not just transparent") compare(visibleGlanceParts(), []) @@ -134,6 +183,24 @@ Item { verify(one("lockPinClock").y < one("keypadFingerprintHint").y, "the small clock sits above the hint") } + function test_tap_on_empty_glance_does_nothing() { + mouseClick(harness.view, 240, 300) + settle() + compare(glance().showing, true, "a tap never shows the PIN view") + mouseClick(harness.view, 240, 120) + settle() + compare(glance().showing, true) + } + + // Short, slow drags (a scroll that went nowhere) don't count. + function test_a_short_drag_does_nothing() { + mousePress(harness.view, 240, 600) + for (var y = 595; y >= 560; y -= 5) { mouseMove(harness.view, 240, y, -1, Qt.LeftButton); wait(50) } + mouseRelease(harness.view, 240, 560) + settle() + compare(glance().showing, true) + } + function test_tap_on_the_sensor_does_nothing() { mouseClick(harness.view, 240, 1040 - 120) settle() @@ -162,8 +229,8 @@ Item { function test_idle_returns_to_glance() { var idle = findChild(glance(), "lockGlanceIdle") verify(idle) - idle.interval = 800 - mouseClick(harness.view, 240, 300) + idle.returnAfter = 800 + swipeUp(harness.view, 240, 700) wait(100) compare(glance().showing, false) tryCompare(glance(), "showing", true, 3000) @@ -173,17 +240,15 @@ Item { function test_idle_waits_for_a_typed_pin() { var idle = findChild(glance(), "lockGlanceIdle") - idle.interval = 300 - mouseClick(harness.view, 240, 300) - settle() + idle.returnAfter = 300 + toPin() harness.password = "12" - wait(800) + wait(1600) compare(glance().showing, false, "a half-typed PIN keeps the PIN view") } function test_wake_returns_to_glance_and_clears() { - mouseClick(harness.view, 240, 300) - settle() + toPin() harness.password = "12" harness.view.wakeSerial += 1 settle() @@ -192,9 +257,66 @@ Item { compare(visiblePinParts(), []) } - function test_failed_attempt_keeps_pin_view() { + // The countdown is on the wall clock: a sleep froze the timer, but not + // the clock, and the PIN view has been up 20 s by the time it resumes. + function test_frozen_timer_returns_by_wall_clock() { + var idle = findChild(glance(), "lockGlanceIdle") + compare(idle.returnAfter, 15000) + toPin() + compare(glance().showing, false) + idle.since = Date.now() - 20000 + tryCompare(glance(), "showing", true, 2500) + } + + function test_blank_on_pin_view_returns_to_glance() { + toPin() + harness.password = "12" + compare(glance().showing, false) + blank() + compare(glance().showing, true, "the screen went dark: back to the glance") + compare(harness.password, "", "a half-typed PIN is cleared") + compare(visiblePinParts(), []) + } + + function test_wake_tap_on_dark_display_only_wakes() { + toPin() + blank() + harness.wakes = 0 mouseClick(harness.view, 240, 300) settle() + compare(glance().showing, true, "the tap that woke the screen doesn't show the PIN view") + compare(harness.view.displayDark, false, "it lit the screen through the lock") + compare(harness.wakes, 1) + wait(200) + toPin() + compare(glance().showing, false, "a swipe up on the lit glance shows the PIN view") + } + + function test_wake_swipe_on_dark_display_only_wakes() { + blank() + mousePress(harness.view, 240, 600) + for (var y = 590; y >= 400; y -= 10) mouseMove(harness.view, 240, y, -1, Qt.LeftButton) + mouseRelease(harness.view, 240, 400) + settle() + compare(glance().showing, true) + compare(harness.view.displayDark, false) + } + + function test_touch_right_after_a_wake_only_wakes() { + // The power button lit the screen; a finger lands on it at once. + blank() + harness.view.wakeSerial += 1 + harness.view.displayDark = false + swipeUp(harness.view, 240, 700) + wait(100) + compare(glance().showing, true, "a swipe that starts within the guard doesn't show the PIN view") + wait(500) + toPin() + compare(glance().showing, false) + } + + function test_failed_attempt_keeps_pin_view() { + toPin() harness.view.authenticatingPassword = true harness.view.authenticatingPassword = false harness.view.failureMessage = "Authentication failed (1)" @@ -202,9 +324,9 @@ Item { compare(glance().showing, false) } - function test_notifications_grouped() { + function test_notifications_as_cards() { harness.notificationsRaw = [ - entry("Messages", 2 * minute, 1, "Sam", "Running late\nsecond line"), + entry("Messages", 2 * minute, 1, "Sam", "Running late\nsecond line\nthird line"), entry("Messages", 5 * minute, 2, "Sam", "Earlier"), entry("Updates", 18 * minute, 3, "4 updates ready", "omamobile-shell and 3 more"), entry("Calendar", 60 * minute, 4, "Standup at 10:00", "Video call"), @@ -215,31 +337,151 @@ Item { entry("Old", 30 * 60 * minute, 9, "Yesterday's", "news") ].join("\n") + "\n" show() - var g = glance().groups - compare(g.length, 5, "one group per app, Omarchy's action toasts and old ones left out") - compare(g[0].app, "Messages") - compare(g[0].count, 2) - compare(g[0].detail, "2 new, 2m") - compare(g[0].body, "Running late", "one line of the newest body") - compare(g[2].detail, "1h") - var cards = byName("lockGlanceCard").filter(function(c) { return c.visible }) + var c = glance().cards + compare(c.length, 9, "one card per notification, as the shade lists them: Omarchy's own and old ones included") + compare(c[0].app, "Omarchy", "Omarchy's own messages (omarchy-action) go by Omarchy") + compare(c[0].summary, "Theme changed") + compare(c[1].app, "Messages") + compare(c[1].detail, "2m", "the detail is the age, nothing more") + compare(c[2].summary, "Sam") + compare(c[2].detail, "5m") + compare(c[4].detail, "1h") + compare(c[8].app, "Old") + compare(c[8].detail, "30h", "no age limit, as in the shade") + var cards = byName("lockGlanceCard").filter(function(x) { return x.visible }) compare(cards.length, 3) - compare(cards[0].summary, "Sam") - compare(cards[0].bodyLines, 1) - compare(cards[0].swipeEnabled, false) - compare(cards[0].closeButtonShown, false) - compare(one("lockGlanceMore").text, "3 more from Mail and GitHub") + compare(cards[0].summary, "Theme changed") + compare(cards[1].summary, "Sam") + compare(cards[2].summary, "Sam", "two from one app are two cards") + compare(cards[1].summaryLines, 1) + compare(cards[1].bodyLines, 1) + compare(cards[1].swipeEnabled, false) + compare(cards[1].closeButtonShown, false) + compare(one("lockGlanceMore").text, "6 more from Updates, Calendar and 3 others") compare(one("lockGlanceQuiet").visible, false) var hint = one("lockGlanceHint") var last = cards[2] verify(last.mapToItem(harness, 0, last.height).y < hint.mapToItem(harness, 0, 0).y, "the cards stay above the hint") - // A card asks for the PIN, nothing else (the pad folds the on-screen - // keyboard, as before). + // A tap on a card opens it to more of its text and runs nothing; a + // second tap closes it. The PIN view stays away. Quickshell.executed = [] - mouseClick(cards[0], 20, 10) + var closedHeight = cards[1].height + mouseClick(cards[1], cards[1].width / 2, 10) settle() - compare(glance().showing, false) + compare(glance().showing, true, "a tap on a card doesn't show the PIN view") + compare(cards[1].summaryLines, 2) + compare(cards[1].bodyLines, 4) + verify(cards[1].height > closedHeight, "the open card is taller") + compare(cards[0].bodyLines, 1, "only that card opens") compare(Quickshell.executed.filter(function(a) { return a[0] !== "busctl" }), []) + mouseClick(cards[1], cards[1].width / 2, 10) + settle() + compare(cards[1].bodyLines, 1) + // A swipe up that starts on a card shows the PIN view. + var p = cards[0].mapToItem(harness.view, cards[0].width / 2, cards[0].height / 2) + swipeUp(harness.view, p.x, p.y) + settle() + compare(glance().showing, false, "a swipe up from a card shows the PIN view") + } + + function test_an_open_card_closes_when_the_glance_comes_back() { + harness.notificationsRaw = entry("Messages", 2 * minute, 1, "Sam", "Hi\nthere") + "\n" + show() + var card = byName("lockGlanceCard")[0] + mouseClick(card, card.width / 2, 10) + settle() + compare(card.bodyLines, 4) + blank() + compare(card.bodyLines, 1) + } + + function test_three_from_one_app_are_three_cards() { + harness.notificationsRaw = [ + entry("omarchy-action", 1 * minute, 1, "Theme changed", ""), + entry("omarchy-action", 2 * minute, 2, "Wallpaper changed", ""), + entry("omarchy-action", 3 * minute, 3, "Update available", "") + ].join("\n") + "\n" + show() + var cards = byName("lockGlanceCard").filter(function(x) { return x.visible }) + compare(cards.length, 3) + compare(cards.map(function(x) { return x.summary }), ["Theme changed", "Wallpaper changed", "Update available"]) + compare(one("lockGlanceMore").visible, false) + } + + function test_five_are_three_cards_and_a_line() { + harness.notificationsRaw = [ + entry("Messages", 1 * minute, 1, "Sam", "One"), + entry("Messages", 2 * minute, 2, "Sam", "Two"), + entry("Mail", 3 * minute, 3, "Invoice", "Three"), + entry("Mail", 4 * minute, 4, "Invoice 2", "Four"), + entry("GitHub", 5 * minute, 5, "Review", "Five") + ].join("\n") + "\n" + show() + compare(byName("lockGlanceCard").filter(function(x) { return x.visible }).length, 3) + compare(one("lockGlanceMore").text, "2 more from Mail and GitHub") + } + + function test_swipe_a_card_sideways_dismisses_it() { + harness.notificationsRaw = [ + entry("Messages", 1 * minute, 1, "Sam", "One"), + entry("Mail", 2 * minute, 2, "Invoice", "Two"), + entry("GitHub", 3 * minute, 3, "Review", "Three"), + entry("Calendar", 4 * minute, 4, "Standup", "Four") + ].join("\n") + "\n" + show() + compare(visibleCards().length, 3) + compare(one("lockGlanceMore").text, "1 more from Calendar") + var file = glance().cards[1].file + var p = centre(visibleCards()[1]) + drag(harness.view, p.x, p.y, 300, 10) + wait(800) + compare(glance().showing, true, "a sideways swipe doesn't show the PIN view") + var calls = forgets() + compare(calls.length, 1, "one forget") + verify(calls[0].indexOf(file) > 0, "the forget names that notification: " + calls[0].join(" ")) + verify(/^[0-9]+-2\.json$/.test(file), "its file name carries its id: " + file) + compare(Quickshell.executed.filter(function(a) { return a[0] !== "busctl" }), [], "nothing of it runs") + tryCompare(one("lockGlanceMore"), "visible", false, 2000) + compare(visibleCards().map(function(c) { return c.summary }), ["Sam", "Review", "Standup"], + "the next one moves up from the more line") + } + + function test_a_short_sideways_swipe_springs_back() { + harness.notificationsRaw = entry("Messages", 1 * minute, 1, "Sam", "One") + "\n" + show() + var p = centre(visibleCards()[0]) + mousePress(harness.view, p.x, p.y) + for (var i = 1; i <= 10; i++) { mouseMove(harness.view, p.x + 4 * i, p.y, -1, Qt.LeftButton); wait(30) } + mouseRelease(harness.view, p.x + 40, p.y) + wait(600) + compare(forgets().length, 0) + compare(visibleCards().length, 1) + compare(visibleCards()[0].swipeOffset, 0) + } + + function test_a_mostly_vertical_swipe_from_a_card_shows_the_pin_view() { + harness.notificationsRaw = entry("Messages", 1 * minute, 1, "Sam", "One") + "\n" + show() + var p = centre(visibleCards()[0]) + drag(harness.view, p.x, p.y, 60, -200) + settle() + compare(glance().showing, false) + compare(forgets().length, 0, "nothing dismissed") + } + + function test_dismiss_the_last_one_with_hidden_text() { + writeFile(".local/state/omarchy/toggles/lock-hide-notification-text", "1\n") + harness.notificationsRaw = entry("Messages", 1 * minute, 1, "Sam", "Secret") + "\n" + show() + compare(visibleCards()[0].body, "Unlock to read") + var p = centre(visibleCards()[0]) + drag(harness.view, p.x, p.y, -300, 0) + wait(800) + compare(forgets().length, 1) + tryCompare(one("lockGlanceQuiet"), "visible", true, 2000) + compare(visibleCards().length, 0) + compare(glance().showing, true) + writeFile(".local/state/omarchy/toggles/lock-hide-notification-text", "") } function test_hide_text_toggle() { @@ -255,14 +497,36 @@ Item { compare(byName("lockGlanceCard")[0].summary, "Sam") } - function test_do_not_disturb_hides_cards() { - harness.notificationsRaw = entry("Messages", 2 * minute, 1, "Sam", "Hi") + "\n" + // Do-not-disturb as the toasts have it: only what still toasts shows + // (Omarchy's own messages, a critical notify-send). + function test_do_not_disturb_shows_what_still_toasts() { + harness.notificationsRaw = [ + entry("Messages", 2 * minute, 1, "Sam", "Hi"), + entry("omarchy-action", 3 * minute, 2, "Theme changed", ""), + entry("notify-send", 4 * minute, 3, "Ping", "") + ].join("\n") + "\n" writeFile(".local/state/omarchy/notifications.json", '{"version": 3, "dnd": true}\n') show() - compare(byName("lockGlanceCard").filter(function(c) { return c.visible }).length, 0) + var cards = byName("lockGlanceCard").filter(function(c) { return c.visible }) + compare(cards.length, 1) + compare(cards[0].summary, "Theme changed") writeFile(".local/state/omarchy/notifications.json", '{"version": 3, "dnd": false}\n') settle() - compare(byName("lockGlanceCard").filter(function(c) { return c.visible }).length, 1) + compare(byName("lockGlanceCard").filter(function(c) { return c.visible }).length, 3) + compare(glance().cards[2].app, "Notifications", "a bare notify-send goes by Notifications") + } + + // The shade's ten: the newest ten notifications, whatever their age. + function test_the_shades_ten() { + var lines = [] + for (var i = 0; i < 12; i++) lines.push(entry("App" + i, (i + 1) * minute, 10 + i, "Note " + i, "body")) + lines.push(JSON.stringify({ id: 99, originalId: 99, app: "Empty", summary: "", body: "", timestamp: test.glance().now })) + harness.notificationsRaw = lines.join("\n") + "\n" + show() + var g = glance().cards + compare(g.length, 10) + compare(g[0].app, "App0", "a row with no text is skipped, as in the shade") + compare(g[9].app, "App9") } function test_no_notifications() { @@ -311,6 +575,9 @@ Item { function test_computer_lock_unchanged() { harness.view.keypad = false settle() + harness.view.blankSerial += 1 + harness.view.displayDark = true + settle() compare(glance().visible, false) compare(one("lockGlanceView").visible, false) compare(harness.view.pinOpacity, 1) diff --git a/packages/omamobile-omarchy/test/patches.py b/packages/omamobile-omarchy/test/patches.py index d31a41f4d..26a4b1004 100755 --- a/packages/omamobile-omarchy/test/patches.py +++ b/packages/omamobile-omarchy/test/patches.py @@ -460,12 +460,21 @@ def lock_glance(root): ok(len(wake) == 2 and "root.wakeSerial += 1" in wake[1].split("}", 1)[0] and "wakeSerial: root.wakeSerial" in service, "real omarchy: the wake call brings the glance back (0023)") + blank = service.split("function runBlank() {", 1) + dark = service.split("function dark(): string {", 1) + run_wake = service.split("function runWake() {", 1) + ok(len(blank) == 2 and "markDark()" in blank[1].split("}", 1)[0] + and len(dark) == 2 and "root.markDark()" in dark[1].split("}", 1)[0] + and len(run_wake) == 2 and "displayDark = false" in run_wake[1].split("}", 1)[0] + and "blankSerial: root.blankSerial" in service and "displayDark: root.displayDark" in service, + "real omarchy: the lock's blank and the dark call bring the glance back, a wake lights it (0023)") ok("maximumLineCount: root.summaryLines" in card and "maximumLineCount: root.bodyLines" in card and "property int summaryLines: 2" in card and "property int bodyLines: 3" in card, "real omarchy: notification toasts keep their line counts (0023)") glance = read(root, lock + "LockGlance.qml") + read(root, lock + "LockGlance.js") - ok("XMLHttpRequest" not in glance and "curl" not in glance and "execDetached" not in glance, - "real omarchy: the glance asks no network and runs nothing (0023)") + ok("XMLHttpRequest" not in glance and "curl" not in glance and "execDetached" not in glance + and "call notifications forget" in glance and "invokeAction" not in glance, + "real omarchy: the glance asks no network and runs no notification action, only the forget call (0023)") p = subprocess.run(["bash", os.path.join(HERE, "lock-glance"), os.path.join(root, "usr/share/omarchy/shell")], capture_output=True, text=True) if p.returncode == 77: diff --git a/packages/omamobile-omarchy/version b/packages/omamobile-omarchy/version index e8e277f2f..04c5555c6 100644 --- a/packages/omamobile-omarchy/version +++ b/packages/omamobile-omarchy/version @@ -1 +1 @@ -0.1.16 +0.1.17 diff --git a/packages/omamobile-shell/README.md b/packages/omamobile-shell/README.md index 53569f2bd..607eaed3f 100644 --- a/packages/omamobile-shell/README.md +++ b/packages/omamobile-shell/README.md @@ -20,6 +20,7 @@ Omarchy Mobile's phone profile for Omarchy's own shell. It isn't a fork: these a | `bin/omamobile-osk-watch` | Reports squeekboard's visibility (sm.puri.OSK0) to the fingerprint, keyboard and launcher plugins | | `bin/omamobile-osk-guard` | Turns the on-screen keyboard (`screen-keyboard-enabled`) back on when it was left off with no screensaver running (a user unit for every graphical session) | | `bin/omamobile-sleepd` | Sleep (s2idle) once the screen has been off behind a secure lock for `OMAMOBILE_SLEEP_AFTER_OFF` s (30), and again 5 s after a dark resume; `now` for the power key (`omamobile-keys`), `check` to see what holds it awake. Refuses with the screen on, Stay awake on, an SSH session open, a logind sleep block inhibitor (calls, GNSS) or a RUNNING PipeWire sink. A user unit for every graphical session, **off until `omarchy-toggle omamobile-sleep on`** (device/cheetah/SUSPEND-PLAN.md 6.2) | +| `bin/omamobile-weather` | The current weather for the lock screen's glance (`~/.local/state/omamobile/weather.json`, with the `source` it used) from Open-Meteo, at login and every 30 minutes (`omamobile-weather.timer`, a user unit for every graphical session). Where, in order: the phone's position from GeoClue at city accuracy, at most every 3 h and only while the Location switch runs GeoClue's agent (never a prompt); the setting `~/.config/omamobile/weather.json` (`omamobile-weather set "State College, PA" F`, or `{"latitude", "longitude"}`; `"location": "fixed"` puts it before the position); the home screen's today widget's city, or the weather widget's named place. Unit: the setting's, else the locale's. One try per run; a failure keeps the old reading. `omamobile-weather show` says where it would look | | `bin/omamobile-fp-enroll` | fprintd enrollment helper the fingerprint screen runs (JSON lines) | | `bin/omamobile-bt-agent` | BlueZ pairing agent and discovery helper the quick-settings Bluetooth panel runs while open | | `bin/omamobile-portal-access` | The xdg-desktop-portal Access backend (`org.freedesktop.impl.portal.desktop.omamobile`, a D-Bus-activated user unit) that shows the permission sheet and answers the portal | diff --git a/packages/omamobile-shell/bin/omamobile-keys b/packages/omamobile-shell/bin/omamobile-keys index 62578a431..6bd245bc1 100644 --- a/packages/omamobile-shell/bin/omamobile-keys +++ b/packages/omamobile-shell/bin/omamobile-keys @@ -5,7 +5,8 @@ # power, short unlocked: lock and turn the screen off # unlocked, dark: screen on (nothing locked it, or the # panel was powered off by hand) -# locked: screen off if it's on, on (PIN pad) if it's off +# locked: screen off if it's on (the lock goes back to +# its glance view), on if it's off # screensaver up: lock (it wakes to the PIN pad) # a press that turned the screen off behind a secure # lock also asks omamobile-sleepd to sleep now (it does @@ -107,6 +108,13 @@ chord() { (sleep 0.4; omarchy-capture-screenshot fullscreen) >/dev/null 2>&1 & } +# The locked screen is going dark: the lock goes back to its glance view, so +# whatever wakes it next finds the glance, and the touch that wakes it only +# wakes it (patches/omarchy/0023). An older lock without the call ignores it. +lock_dark() { + omarchy-shell lock dark >/dev/null 2>&1 +} + # The screen just went off: sleep now if the lock is secure (SUSPEND-PLAN # 6.1). omamobile-sleepd checks the toggle, the screen and its inhibitors # itself; in the background, so the key handler returns at once. @@ -143,6 +151,7 @@ short_press() { if screen_off; then wake_locked else + lock_dark omarchy-brightness-display off sleep_now fi @@ -174,6 +183,7 @@ short_press() { omarchy-shell lock status 2>/dev/null | grep -q '"secure":true' && break sleep 0.1 done + lock_dark omarchy-brightness-display off # The brightness the next wake lights up with: the saved level, or 40 % when # the press caught the panel at 0. diff --git a/packages/omamobile-shell/bin/omamobile-sleepd b/packages/omamobile-shell/bin/omamobile-sleepd index d106d1566..41b29831d 100755 --- a/packages/omamobile-shell/bin/omamobile-sleepd +++ b/packages/omamobile-shell/bin/omamobile-sleepd @@ -119,6 +119,11 @@ wake_reason() { request() { log "sleeping ($1)" + # The lock goes back to its glance view before the freeze, for a screen + # that went dark some way that didn't tell it (patches/omarchy/0023): the + # next wake finds the glance, and a touch that wakes it only wakes it. + # Bounded: a stuck shell must not hold the watcher up. + timeout 3 omarchy-shell lock dark >/dev/null 2>&1 systemctl suspend 2>&1 | sed 's/^/omamobile-sleepd: systemctl: /' } diff --git a/packages/omamobile-shell/bin/omamobile-weather b/packages/omamobile-shell/bin/omamobile-weather new file mode 100644 index 000000000..2b9bdf016 --- /dev/null +++ b/packages/omamobile-shell/bin/omamobile-weather @@ -0,0 +1,405 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""omamobile-weather: the phone's current weather, for the lock screen. + +Fetches the current weather from Open-Meteo (open-meteo.com: free, no key, +no account; the same API and the same words as the home screen's weather +widget, HomeModel.js) and writes ~/.local/state/omamobile/weather.json, which +Omarchy's lock glance shows (omamobile-omarchy patch 0023; it hides a +reading over 3 h old): + + {"at": , "temperature": 12, "unit": "°C", "text": "Partly cloudy", + "source": "location" | "widget" | "setting"} + +Run by omamobile-weather.timer (at login and every 30 minutes). Where, in +this order: + + 1. location: the phone's position from GeoClue at city accuracy (no GNSS + power-up), asked at most every 3 h, and only while the Location switch + has GeoClue's agent running (omamobile-geoclue-agent.service, from + omamobile-gnss); the client is GeoClue's where-am-i, which GeoClue lets + through without asking, so a timer never raises a prompt. A fix that + fails or times out falls back to the last one, up to a day old. + 2. widget: the city the home screen's "today" widget is set to (the newest + ~/.local/state/omamobile/owl/owl_simonschubert.today_*.json), or else + the shell weather widget's named place. + 3. setting: ~/.config/omamobile/weather.json, + + {"city": "State College, PA", "unit": "F"} or + {"latitude": 40.79, "longitude": -77.86, "unit": "C"} + + which wins over 2, and over 1 too with "location": "fixed" (default + "auto"). + +A city is looked up once with Open-Meteo's geocoding and kept, by name, in +~/.local/state/omamobile/weather-place.json with the last position fix. The +unit is the setting's, else the locale's (°F in the US). With no place at +all, nothing is fetched. No IP geolocation. + +One try per run with short timeouts; on any failure the old reading stays. +Only coordinates rounded to about 1 km, or the city name, leave the phone. + + omamobile-weather fetch once and write the reading + omamobile-weather set CITY [F|C] save the place (and the unit) + omamobile-weather show print where it would look and the reading +""" +import glob +import json +import os +import re +import subprocess +import sys +import tempfile +import time +import urllib.parse +import urllib.request + +TIMEOUT = 10 +HOME = os.path.expanduser("~") +CONFIG = os.path.join(HOME, ".config/omamobile/weather.json") +HOME_LAYOUT = os.path.join(HOME, ".config/omamobile/home.json") +STATE_DIR = os.path.join(HOME, ".local/state/omamobile") +READING = os.path.join(STATE_DIR, "weather.json") +PLACE = os.path.join(STATE_DIR, "weather-place.json") +OWL_TODAY = os.path.join(STATE_DIR, "owl", "owl_simonschubert.today_*.json") +WHERE_AM_I = os.environ.get("OMAMOBILE_WHERE_AM_I", "/usr/lib/geoclue-2.0/demos/where-am-i") +GEOCLUE_AGENT = "omamobile-geoclue-agent.service" +FIX_FRESH = 3 * 3600 # ask GeoClue at most this often +FIX_KEEP = 24 * 3600 # a failed fix falls back to the last one this young + +# Open-Meteo's WMO weather codes -> words, as HomeModel.weatherText (the +# test checks the two agree for every code). +def weather_text(code): + # As JavaScript's Number(code): nothing or "" is 0, anything unreadable + # has no words. + if code is None or (isinstance(code, str) and not code.strip()): + code = 0 + try: + c = float(code) + except (TypeError, ValueError): + return "" + if c != c or c != int(c): + return "" + c = int(c) + if c == 0: + return "Clear" + if c in (1, 2): + return "Mostly clear" if c == 1 else "Partly cloudy" + if c == 3: + return "Overcast" + if c in (45, 48): + return "Fog" + if 51 <= c <= 57: + return "Drizzle" + if 61 <= c <= 67 or 80 <= c <= 82: + return "Rain" + if 71 <= c <= 77 or c in (85, 86): + return "Snow" + if 95 <= c <= 99: + return "Thunderstorm" + return "" + + +# Countries that measure temperature in °F. +FAHRENHEIT_TERRITORIES = {"US", "LR", "MM", "BS", "BZ", "KY", "PW", "FM", "MH", "PR", "GU", "VI", "AS", "MP", "UM"} + +US_STATES = { + "al": "alabama", "ak": "alaska", "az": "arizona", "ar": "arkansas", "ca": "california", "co": "colorado", + "ct": "connecticut", "de": "delaware", "dc": "district of columbia", "fl": "florida", "ga": "georgia", + "hi": "hawaii", "id": "idaho", "il": "illinois", "in": "indiana", "ia": "iowa", "ks": "kansas", + "ky": "kentucky", "la": "louisiana", "me": "maine", "md": "maryland", "ma": "massachusetts", + "mi": "michigan", "mn": "minnesota", "ms": "mississippi", "mo": "missouri", "mt": "montana", + "ne": "nebraska", "nv": "nevada", "nh": "new hampshire", "nj": "new jersey", "nm": "new mexico", + "ny": "new york", "nc": "north carolina", "nd": "north dakota", "oh": "ohio", "ok": "oklahoma", + "or": "oregon", "pa": "pennsylvania", "ri": "rhode island", "sc": "south carolina", "sd": "south dakota", + "tn": "tennessee", "tx": "texas", "ut": "utah", "vt": "vermont", "va": "virginia", "wa": "washington", + "wv": "west virginia", "wi": "wisconsin", "wy": "wyoming", +} + + +def log(message): + print("omamobile-weather: " + message, file=sys.stderr) + + +def read_json(path): + try: + with open(path, encoding="utf-8") as f: + value = json.load(f) + return value if isinstance(value, dict) else None + except (OSError, ValueError): + return None + + +def write_json(path, value): + """Whole or not at all: a temporary file in the same directory, renamed.""" + os.makedirs(os.path.dirname(path), exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".weather-", dir=os.path.dirname(path)) + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + json.dump(value, f, ensure_ascii=False) + f.write("\n") + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def locale_unit(env=None): + env = os.environ if env is None else env + for name in ("LC_ALL", "LC_MEASUREMENT", "LANG"): + value = env.get(name) or "" + if value: + territory = value.split(".")[0].split("@")[0].partition("_")[2].upper() + return "F" if territory in FAHRENHEIT_TERRITORIES else "C" + return "C" + + +def unit_of(value, env=None): + v = str(value or "").strip().upper().lstrip("°") + if v in ("F", "FAHRENHEIT"): + return "F" + if v in ("C", "CELSIUS"): + return "C" + return locale_unit(env) + + +def number(value): + return value if isinstance(value, (int, float)) and not isinstance(value, bool) and value == value else None + + +def setting_place(config, env=None): + """The setting's place ({"city"} or {"latitude", "longitude"}) with its + unit and "fixed", or None without a place.""" + if not config: + return None + unit = unit_of(config.get("unit"), env) + fixed = str(config.get("location") or "auto").strip().lower() == "fixed" + lat, lon = number(config.get("latitude")), number(config.get("longitude")) + if lat is not None and lon is not None: + return {"latitude": lat, "longitude": lon, "unit": unit, "fixed": fixed} + city = str(config.get("city") or "").strip() + if city: + return {"city": city, "unit": unit, "fixed": fixed} + return None + + +def today_city(pattern=None): + """The city of the newest "today" home screen widget, or "".""" + files = glob.glob(pattern or OWL_TODAY) + for path in sorted(files, key=lambda f: os.path.getmtime(f), reverse=True): + city = str((read_json(path) or {}).get("city") or "").strip() + if city: + return city + return "" + + +def home_widget_place(layout): + """The shell weather widget's named place, if it is on and has one.""" + for page in (layout or {}).get("pages") or []: + for item in (page or {}).get("items") or []: + if not isinstance(item, dict) or item.get("type") != "weather": + continue + c = item.get("config") or {} + lat, lon = number(c.get("latitude")), number(c.get("longitude")) + if c.get("enabled") is True and lat is not None and lon is not None: + return {"latitude": lat, "longitude": lon, + "unit": "F" if c.get("units") == "fahrenheit" else "C" if c.get("units") == "celsius" else None} + return None + + +def geoclue_usable(): + """GeoClue answers this user only while its agent runs (the Location + switch); without it a request queues for ever, so it isn't made.""" + if not os.access(WHERE_AM_I, os.X_OK): + return False + return subprocess.run(["systemctl", "--user", "--quiet", "is-active", GEOCLUE_AGENT], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0 + + +def where_am_i(): + """(lat, lon) from GeoClue at city accuracy, or None; never longer than + about 20 s, whatever GeoClue does.""" + try: + out = subprocess.run(["timeout", "-k", "2", "20", WHERE_AM_I, "-a", "4", "-t", "12"], + capture_output=True, text=True, env=dict(os.environ, LC_ALL="C")).stdout + except OSError: + return None + lat = re.findall(r"^Latitude:\s*(-?[0-9][0-9.]*)", out, re.M) + lon = re.findall(r"^Longitude:\s*(-?[0-9][0-9.]*)", out, re.M) + if not lat or not lon: + return None + return round(float(lat[-1]), 2), round(float(lon[-1]), 2) + + +def position(state, now_s): + """The phone's position (lat, lon), or None: a fix younger than 3 h as + it is, else a new one from GeoClue when it is usable (kept in state), + else, when that fails, the last one up to a day old.""" + fix = state.get("fix") if isinstance(state.get("fix"), dict) else None + age = now_s - number(fix.get("at")) if fix and number(fix.get("at")) is not None else None + have = fix and number(fix.get("latitude")) is not None and number(fix.get("longitude")) is not None + if have and age is not None and 0 <= age < FIX_FRESH: + return fix["latitude"], fix["longitude"] + if not geoclue_usable(): + return None + got = where_am_i() + if got: + state["fix"] = {"latitude": got[0], "longitude": got[1], "at": int(now_s)} + return got + if have and age is not None and 0 <= age < FIX_KEEP: + log("no position from GeoClue: the last one, %d min old" % (age // 60)) + return fix["latitude"], fix["longitude"] + return None + + +def resolve(config, layout, state, now_s, env=None, owl_pattern=None): + """Where to fetch for, in order (location, the setting, the widgets): + {"latitude", "longitude"} or {"city"}, with "unit" and "source"; or None.""" + setting = setting_place(config, env) + unit = setting["unit"] if setting else unit_of((config or {}).get("unit"), env) + if setting and setting["fixed"]: + return dict(setting, source="setting") + here = position(state, now_s) + if here: + return {"latitude": here[0], "longitude": here[1], "unit": unit, "source": "location"} + if setting: + return dict(setting, source="setting") + city = today_city(owl_pattern) + if city: + return {"city": city, "unit": unit, "source": "widget"} + home = home_widget_place(layout) + if home: + return {"latitude": home["latitude"], "longitude": home["longitude"], + "unit": unit if (config or {}).get("unit") else home["unit"] or unit, "source": "widget"} + return None + + +def city_key(city): + return " ".join(str(city or "").lower().split()) + + +def geocode_url(name): + return "https://geocoding-api.open-meteo.com/v1/search?count=10&format=json&name=" + urllib.parse.quote(name) + + +def pick_place(city, answer): + """The best geocoding result for "Town, Region": the first whose region, + country or country code matches what follows the comma (US state + abbreviations read as states), else the first.""" + results = (answer or {}).get("results") or [] + results = [r for r in results if isinstance(r, dict) and number(r.get("latitude")) is not None and number(r.get("longitude")) is not None] + if not results: + return None + qualifiers = [q.strip().lower() for q in str(city).split(",")[1:] if q.strip()] + wanted = set() + for q in qualifiers: + wanted.add(q) + if q in US_STATES: + wanted.add(US_STATES[q]) + best = results[0] + if wanted: + for r in results: + fields = {str(r.get(k) or "").lower() for k in ("admin1", "admin2", "country", "country_code")} + if wanted & fields: + best = r + break + return {"latitude": best["latitude"], "longitude": best["longitude"], "name": str(best.get("name") or "")} + + +def forecast_url(latitude, longitude, unit): + lat = round(float(latitude) * 100) / 100 + lon = round(float(longitude) * 100) / 100 + return ("https://api.open-meteo.com/v1/forecast?latitude=%s&longitude=%s¤t=temperature_2m,weather_code&timezone=auto" + % (lat, lon)) + ("&temperature_unit=fahrenheit" if unit == "F" else "") + + +def reading(answer, unit, now_ms): + """The lock's reading from a forecast answer, or None.""" + cur = (answer or {}).get("current") or {} + t = number(cur.get("temperature_2m")) + if t is None: + return None + return {"at": int(now_ms), "temperature": int(round(t)), "unit": "°F" if unit == "F" else "°C", + "text": weather_text(cur.get("weather_code"))} + + +def fetch_json(url): + request = urllib.request.Request(url, headers={"User-Agent": "omamobile-weather"}) + with urllib.request.urlopen(request, timeout=TIMEOUT) as response: + return json.loads(response.read().decode("utf-8")) + + +def coordinates(where, state, fetch=fetch_json): + """(lat, lon) for a place; a city from state's "cities", else looked up + (and kept there).""" + if "city" not in where: + return where["latitude"], where["longitude"] + key = city_key(where["city"]) + cities = state.get("cities") if isinstance(state.get("cities"), dict) else {} + known = cities.get(key) + if isinstance(known, dict) and number(known.get("latitude")) is not None and number(known.get("longitude")) is not None: + return known["latitude"], known["longitude"] + town = where["city"].split(",")[0].strip() + place = pick_place(where["city"], fetch(geocode_url(town))) + if not place: + raise LookupError("no place called %r" % where["city"]) + cities = dict(cities) + cities[key] = {"latitude": place["latitude"], "longitude": place["longitude"], "name": place["name"]} + state["cities"] = cities + log("%s is at %.2f, %.2f" % (where["city"], place["latitude"], place["longitude"])) + return place["latitude"], place["longitude"] + + +def run(fetch=fetch_json, now=time.time, env=None): + now_s = now() + state = read_json(PLACE) or {} + before = json.dumps(state, sort_keys=True) + where = resolve(read_json(CONFIG), read_json(HOME_LAYOUT), state, now_s, env) + try: + if not where: + log("no place (Location off, no today widget city, no setting: omamobile-weather set CITY): nothing fetched") + return 0 + try: + lat, lon = coordinates(where, state, fetch) + value = reading(fetch(forecast_url(lat, lon, where["unit"])), where["unit"], now_s * 1000) + except Exception as e: # one try; the old reading stays + log("weather unavailable: %s" % e) + return 1 + if not value: + log("weather unavailable: no temperature in the answer") + return 1 + value["source"] = where["source"] + write_json(READING, value) + return 0 + finally: + if json.dumps(state, sort_keys=True) != before: + write_json(PLACE, state) + + +def main(argv): + if len(argv) <= 1: + return run() + if argv[1] == "set" and len(argv) in (3, 4): + config = {"city": argv[2].strip()} + if len(argv) == 4: + if argv[3].strip().upper().lstrip("°") not in ("F", "C"): + print("Usage: omamobile-weather set CITY [F|C]", file=sys.stderr) + return 2 + config["unit"] = argv[3].strip().upper().lstrip("°") + write_json(CONFIG, config) + print("saved %s" % json.dumps(config, ensure_ascii=False)) + return 0 + if argv[1] == "show" and len(argv) == 2: + state = read_json(PLACE) or {} + print(json.dumps({"where": resolve(read_json(CONFIG), read_json(HOME_LAYOUT), state, time.time()), + "reading": read_json(READING)}, ensure_ascii=False, indent=2)) + return 0 + print("Usage: omamobile-weather [set CITY [F|C] | show]", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/packages/omamobile-shell/install b/packages/omamobile-shell/install index 0cf63cdb8..7dc84b5e1 100755 --- a/packages/omamobile-shell/install +++ b/packages/omamobile-shell/install @@ -45,6 +45,11 @@ ln -sfn ../omamobile-osk-guard.service "$destination/usr/lib/systemd/user/graphi # until the user turns the omamobile-sleep toggle on. install -Dm644 systemd/user/omamobile-sleepd.service "$destination/usr/lib/systemd/user/omamobile-sleepd.service" ln -sfn ../omamobile-sleepd.service "$destination/usr/lib/systemd/user/graphical-session.target.wants/omamobile-sleepd.service" +# The lock screen's weather, at login and every 30 minutes, for every user's +# graphical session; it fetches nothing until a place is set. +install -Dm644 systemd/user/omamobile-weather.service "$destination/usr/lib/systemd/user/omamobile-weather.service" +install -Dm644 systemd/user/omamobile-weather.timer "$destination/usr/lib/systemd/user/omamobile-weather.timer" +ln -sfn ../omamobile-weather.timer "$destination/usr/lib/systemd/user/graphical-session.target.wants/omamobile-weather.timer" # The file chooser: xdg-desktop-portal-gnome on plain Wayland (its drop-in). install -Dm644 systemd/user/xdg-desktop-portal-gnome-omamobile.conf \ "$destination/usr/lib/systemd/user/xdg-desktop-portal-gnome.service.d/omamobile.conf" diff --git a/packages/omamobile-shell/systemd/user/omamobile-weather.service b/packages/omamobile-shell/systemd/user/omamobile-weather.service new file mode 100644 index 000000000..333008e2a --- /dev/null +++ b/packages/omamobile-shell/systemd/user/omamobile-weather.service @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: MIT +# The current weather for the lock screen (~/.local/state/omamobile/weather.json), +# one fetch per run, started by omamobile-weather.timer. Fetches nothing +# until a place is set: omamobile-weather set CITY [F|C]. +[Unit] +Description=Omarchy Mobile weather for the lock screen + +[Service] +Type=oneshot +ExecStart=/usr/bin/omamobile-weather +TimeoutStartSec=60 diff --git a/packages/omamobile-shell/systemd/user/omamobile-weather.timer b/packages/omamobile-shell/systemd/user/omamobile-weather.timer new file mode 100644 index 000000000..5805ab681 --- /dev/null +++ b/packages/omamobile-shell/systemd/user/omamobile-weather.timer @@ -0,0 +1,16 @@ +# SPDX-License-Identifier: MIT +# omamobile-weather at login and every 30 minutes of the clock; a half hour +# that passed while the phone slept runs on resume. +[Unit] +Description=Omarchy Mobile weather for the lock screen, every 30 minutes +PartOf=graphical-session.target +After=graphical-session.target + +[Timer] +OnActiveSec=30s +OnCalendar=*:00/30 +Persistent=true +Unit=omamobile-weather.service + +[Install] +WantedBy=graphical-session.target diff --git a/packages/omamobile-shell/test/all b/packages/omamobile-shell/test/all index d4559c16c..4fc649cf7 100755 --- a/packages/omamobile-shell/test/all +++ b/packages/omamobile-shell/test/all @@ -600,6 +600,8 @@ bash -n bin/omamobile-osk-guard || fail "omamobile-osk-guard parses" bash test/osk-guard.sh || fail "omamobile-osk-guard" bash -n bin/omamobile-sleepd || fail "omamobile-sleepd parses" bash test/sleepd.sh || fail "omamobile-sleepd" +python3 -B -c 'import ast,sys; ast.parse(open(sys.argv[1]).read())' bin/omamobile-weather || fail "omamobile-weather parses" +python3 -B test/weather.py 2>/dev/null || fail "omamobile-weather" tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT ./install "$tmp/root" [[ -x $tmp/root/usr/bin/omamobile-setup-user && -f $tmp/root/usr/share/omamobile/shell/profile/shell.json ]] \ @@ -626,6 +628,16 @@ grep -cx 'ExecStart=/usr/bin/omamobile-setup-user' systemd/user/omamobile-setup- $(readlink "$u/graphical-session.target.wants/omamobile-sleepd.service") == ../omamobile-sleepd.service ]] \ || fail "the sleep watcher is staged and runs for every user's session" grep -cx 'ExecStart=/usr/bin/omamobile-sleepd' systemd/user/omamobile-sleepd.service >/dev/null || fail "the unit runs the watcher" +# The lock screen's weather: a timer for every session, a one-shot service. +[[ -x $tmp/root/usr/bin/omamobile-weather && -f $u/omamobile-weather.service && -f $u/omamobile-weather.timer && + $(readlink "$u/graphical-session.target.wants/omamobile-weather.timer") == ../omamobile-weather.timer ]] \ + || fail "the weather timer is staged and runs for every user's session" +grep -cx 'ExecStart=/usr/bin/omamobile-weather' systemd/user/omamobile-weather.service >/dev/null \ + && grep -cx 'Type=oneshot' systemd/user/omamobile-weather.service >/dev/null \ + && grep -cx 'OnCalendar=\*:00/30' systemd/user/omamobile-weather.timer >/dev/null \ + && grep -cx 'Unit=omamobile-weather.service' systemd/user/omamobile-weather.timer >/dev/null \ + || fail "the weather timer runs the one-shot service every 30 minutes" +pass "the lock screen's weather runs at login and every 30 minutes" if grep -rnE '^[^#]*(omarchy-toggle omamobile-sleep( on| toggle|$)|toggles/omamobile-sleep)' bin install systemd plugins; then fail "nothing turns the omamobile-sleep toggle on by default" fi diff --git a/packages/omamobile-shell/test/keys.sh b/packages/omamobile-shell/test/keys.sh index 9c27b815a..8f5cb47b7 100755 --- a/packages/omamobile-shell/test/keys.sh +++ b/packages/omamobile-shell/test/keys.sh @@ -81,17 +81,24 @@ echo true >"$t/secure" echo foot >"$t/class" press() { reset; keys power-down; keys power-up; sleep 0.5; } +# The lock hears that its screen goes dark before the panel goes off, so it +# is back on its glance view for the next wake (patches/omarchy/0023). +before() { awk -v a="$1" -v b="$2" '{ sub(/ +$/, "") } $0 == a && !x { x = NR } $0 == b && !y { y = NR } END { exit !(x && y && x < y) }' "$log"; } echo false >"$t/locked"; echo true >"$t/dpms" press; grep -q "omarchy-system-lock" "$log" || fail "unlocked and lit: a press locks" +before "omarchy-system-lock" "omarchy-shell lock dark" && before "omarchy-shell lock dark" "omarchy-brightness-display off" \ + || fail "unlocked and lit: the new lock hears it goes dark, before the panel goes off" echo false >"$t/locked"; echo false >"$t/dpms" press; grep -q "omarchy-brightness-display on" "$log" || fail "unlocked and dark: a press lights the screen" grep -q "omarchy-system-lock" "$log" && fail "unlocked and dark: a press does not lock" echo true >"$t/locked"; echo true >"$t/dpms" press; grep -q "omarchy-brightness-display off" "$log" || fail "locked and lit: a press turns the screen off" +before "omarchy-shell lock dark" "omarchy-brightness-display off" || fail "locked and lit: the lock hears it goes dark, before the panel goes off" grep -q "omarchy-system-lock" "$log" && fail "locked and lit: a press does not lock again" echo true >"$t/locked"; echo false >"$t/dpms" press; grep -q "omarchy-shell lock wake" "$log" || fail "locked and dark: a press wakes the lock screen" grep -q "omarchy-brightness-display on" "$log" || fail "locked and dark: a press lights the screen" +grep -q "lock dark" "$log" && fail "locked and dark: a wake doesn't tell the lock it went dark" grep -q "omarchy-system-lock" "$log" && fail "locked and dark: a press does not lock again" # hyprctl failing must read as "screen on": the press locks, never wakes blind. cat >"$t/bin/hyprctl" <= $(cat "$T/off_at") )); then rm fake omarchy-toggle-enabled '[[ $1 == omamobile-sleep && -f $T/toggle ]]' fake omarchy-hw-display 'echo panel' fake hyprctl '[[ $1 == monitors ]] && printf "[{\"dpmsStatus\": %s}]\n" "$(cat "$T/dpms")"' -fake omarchy-shell '[[ "$*" == "lock status" ]] && printf "{\"locked\":true,\"secure\":%s}\n" "$(cat "$T/secure")"' +fake omarchy-shell '[[ "$*" == "lock status" ]] && printf "{\"locked\":true,\"secure\":%s}\n" "$(cat "$T/secure")" +[[ "$*" == "lock dark" ]] && echo "omarchy-shell lock dark at $(cat "$T/clock")" >>"$T/log" +true' fake ss 'cat "$T/ssh"' fake busctl 'printf "{\"type\":\"a(ssssuu)\",\"data\":[[%s]]}\n" "$(cat "$T/inhibitors")"' fake pactl 'cat "$T/sinks"' @@ -64,6 +66,8 @@ reset; watch 100 [[ $(suspends) -ge 1 ]] || fail "screen off and locked: it sleeps" at=$(first_at); ((at >= 1030 && at <= 1034)) || fail "the first sleep comes 30 s after the screen went off (at $at)" grep -c 'sleeping (screen off and locked for 30 s)' "$t/out" >/dev/null || fail "the sleep is logged with its cause" +[[ $(sed -n 1p "$t/log") == "omarchy-shell lock dark at $at" && $(sed -n 2p "$t/log") == "systemctl suspend at $at" ]] \ + || fail "the lock hears the screen is dark (back to its glance) just before the suspend" reset; watch 100 OMAMOBILE_SLEEP_AFTER_OFF=12 at=$(first_at); ((at >= 1012 && at <= 1016)) || fail "OMAMOBILE_SLEEP_AFTER_OFF sets the wait (at $at)" reset; watch 100 OMAMOBILE_SLEEP_AFTER_OFF=0 diff --git a/packages/omamobile-shell/test/weather.py b/packages/omamobile-shell/test/weather.py new file mode 100644 index 000000000..cafbce94e --- /dev/null +++ b/packages/omamobile-shell/test/weather.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +# omamobile-weather against a fake HOME and a fake network: the reading it +# writes for the lock screen (the shape LockGlance.js weatherLine reads), +# its words for the weather codes against the home screen's +# (HomeModel.weatherText, through node), the settings it reads, the city +# lookup and its cache, and one try per run that leaves the old reading. +import glob +import importlib.machinery +import importlib.util +import json +import os +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +home = tempfile.mkdtemp() +os.environ["HOME"] = home +loader = importlib.machinery.SourceFileLoader("omamobile_weather", os.path.join(ROOT, "bin/omamobile-weather")) +spec = importlib.util.spec_from_loader("omamobile_weather", loader) +W = importlib.util.module_from_spec(spec) +loader.exec_module(W) + + +def ok(cond, name): + if not cond: + print("not ok - weather: " + name) + sys.exit(1) + + +def write(path, value): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as f: + json.dump(value, f) + + +def reset(): + for p in (W.CONFIG, W.HOME_LAYOUT, W.READING, W.PLACE): + if os.path.exists(p): + os.unlink(p) + + +# The words agree with the home screen widget's for every code. +js = ("const M = require(process.argv[1]); const out = {};" + "for (let c = -1; c <= 120; c++) out[c] = M.weatherText(c).text;" + "out.x = M.weatherText('x').text; out.n = M.weatherText(null).text;" + "console.log(JSON.stringify(out))") +theirs = json.loads(subprocess.run(["node", "-e", js, os.path.join(ROOT, "plugins/omamobile.home/HomeModel.js")], + check=True, capture_output=True, text=True).stdout) +mine = {str(c): W.weather_text(c) for c in range(-1, 121)} +mine["x"] = W.weather_text("x") +mine["n"] = W.weather_text(None) +diff = {k: (mine[k], theirs[k]) for k in theirs if mine.get(k) != theirs[k]} +ok(not diff, "the words for each code are the home screen widget's %s" % diff) +print("ok - weather: the words for every code are the home screen widget's (HomeModel.weatherText)") + +# Settings and where to look +us = {"LANG": "en_US.UTF-8"} +de = {"LANG": "de_DE.UTF-8"} +ok(W.locale_unit(us) == "F" and W.locale_unit(de) == "C" and W.locale_unit({"LANG": "C.UTF-8"}) == "C" + and W.locale_unit({}) == "C" and W.locale_unit({"LC_ALL": "de_DE.UTF-8", "LANG": "en_US.UTF-8"}) == "C" + and W.locale_unit({"LC_MEASUREMENT": "en_US.UTF-8", "LANG": "de_DE.UTF-8"}) == "F", "the unit follows the locale") +ok(W.setting_place({"city": " State College, PA ", "unit": "F"}, de) == {"city": "State College, PA", "unit": "F", "fixed": False}, + "a city and a unit") +ok(W.setting_place({"city": "Oslo"}, us)["unit"] == "F" and W.setting_place({"city": "Oslo"}, de)["unit"] == "C", "no unit: the locale's") +ok(W.setting_place({"city": "Oslo", "unit": "°c"}, us)["unit"] == "C" + and W.setting_place({"city": "Oslo", "unit": "fahrenheit"}, de)["unit"] == "F", "units read loosely") +ok(W.setting_place({"latitude": 59.9, "longitude": 10.7, "city": "ignored", "unit": "C", "location": "fixed"}, us) + == {"latitude": 59.9, "longitude": 10.7, "unit": "C", "fixed": True}, "coordinates win over a city; fixed") +ok(W.setting_place({"latitude": "59.9", "longitude": 10.7}, us) is None, "coordinates must be numbers") +ok(W.setting_place({}, us) is None and W.setting_place(None, us) is None and W.setting_place({"unit": "F"}, us) is None, + "no place set") +layout = {"pages": [{"items": [{"type": "clock"}, {"type": "weather", "config": { + "enabled": True, "useLocation": False, "latitude": 52.52, "longitude": 13.41, "units": "celsius"}}]}]} +here_only = {"pages": [{"items": [{"type": "weather", "config": {"enabled": True, "useLocation": True, + "latitude": None, "longitude": None}}]}]} +off = {"pages": [{"items": [{"type": "weather", "config": {"enabled": False, "latitude": 1.0, "longitude": 2.0}}]}]} +ok(W.home_widget_place(layout) == {"latitude": 52.52, "longitude": 13.41, "unit": "C"}, "the weather widget's named place") +ok(W.home_widget_place(here_only) is None and W.home_widget_place(off) is None, "no named place, or off: none") + +owl = os.path.join(home, ".local/state/omamobile/owl") +os.makedirs(owl, exist_ok=True) +write(os.path.join(owl, "owl_simonschubert.today_w3.json"), {"city": "old town"}) +os.utime(os.path.join(owl, "owl_simonschubert.today_w3.json"), (1000, 1000)) +write(os.path.join(owl, "owl_simonschubert.today_w17.json"), {"city": "state college, pa"}) +write(os.path.join(owl, "owl_someone.else_w1.json"), {"city": "elsewhere"}) +ok(W.today_city() == "state college, pa", "the newest today widget's city") + +geo = {"usable": False, "answer": None, "asked": 0} + + +def usable(): + return geo["usable"] + + +def where(): + geo["asked"] += 1 + return geo["answer"] + + +W.geoclue_usable = usable +W.where_am_i = where +T = 1790000000.0 +st = {} +r = W.resolve({"city": "Oslo", "unit": "C"}, None, st, T, us) +ok(r["source"] == "setting" and r["city"] == "Oslo" and geo["asked"] == 0, "GeoClue not usable, a setting: the setting, GeoClue never asked") +r = W.resolve(None, None, {}, T, us) +ok(r == {"city": "state college, pa", "unit": "F", "source": "widget"}, "GeoClue not usable, no setting: the today widget's city %s" % r) +r = W.resolve({"unit": "C"}, None, {}, T, us) +ok(r["source"] == "widget" and r["unit"] == "C", "a unit alone still sets the unit") +geo.update(usable=True, answer=(40.79, -77.86)) +st = {} +r = W.resolve({"city": "Oslo"}, None, st, T, us) +ok(r == {"latitude": 40.79, "longitude": -77.86, "unit": "F", "source": "location"} and geo["asked"] == 1, + "with Location on, the phone's position comes first %s" % r) +ok(st["fix"] == {"latitude": 40.79, "longitude": -77.86, "at": int(T)}, "the fix is kept with its time") +r = W.resolve({"city": "Oslo"}, None, st, T + 2 * 3600, us) +ok(r["source"] == "location" and geo["asked"] == 1, "a fix under 3 h old is used again without asking") +r = W.resolve({"city": "Oslo", "location": "fixed"}, None, st, T + 4 * 3600, us) +ok(r["source"] == "setting" and r["city"] == "Oslo" and geo["asked"] == 1, "location fixed: the setting, GeoClue never asked") +geo["answer"] = None +r = W.resolve(None, None, st, T + 4 * 3600, us) +ok(r["source"] == "location" and r["latitude"] == 40.79 and geo["asked"] == 2, "a failed fix: the last one, under a day old") +r = W.resolve(None, None, st, T + 30 * 3600, us) +ok(r["source"] == "widget" and geo["asked"] == 3, "a failed fix and the last over a day old: the widget's city") +geo["usable"] = False +r = W.resolve(None, None, st, T + 3600, us) +ok(r["source"] == "location", "Location off but a fix under 3 h old: still used") +r = W.resolve(None, None, st, T + 5 * 3600, us) +ok(r["source"] == "widget" and geo["asked"] == 3, "Location off and the fix older: GeoClue isn't asked, the widget's city") +for f in glob.glob(os.path.join(owl, "owl_simonschubert.today_*")): + os.unlink(f) +ok(W.resolve(None, layout, {}, T, us)["source"] == "widget" + and W.resolve(None, layout, {}, T, us)["latitude"] == 52.52, "no today widget: the weather widget's named place") +ok(W.resolve(None, here_only, {}, T, us) is None, "no place anywhere: none (no IP geolocation)") +print("ok - weather: where, in order: the phone's position (at most every 3 h, never asked with Location off), the setting, the widgets' city") + +# Requests +url = W.forecast_url(40.79345, -77.86012, "F") +ok("latitude=40.79&longitude=-77.86" in url and url.endswith("&temperature_unit=fahrenheit") + and "current=temperature_2m,weather_code" in url, "the forecast asks for a rounded place " + url) +ok("temperature_unit" not in W.forecast_url(1, 2, "C"), "celsius is the default") +ok(W.geocode_url("State College") .endswith("name=State%20College"), "the city is quoted") +results = {"results": [ + {"name": "State College", "latitude": 33.4, "longitude": -88.8, "admin1": "Mississippi", "country_code": "US"}, + {"name": "State College", "latitude": 40.79, "longitude": -77.86, "admin1": "Pennsylvania", "country_code": "US"}]} +ok(W.pick_place("State College, PA", results)["latitude"] == 40.79, "a state abbreviation picks the state") +ok(W.pick_place("State College, Mississippi", results)["latitude"] == 33.4, "a region by name") +ok(W.pick_place("State College", results)["latitude"] == 33.4, "no region: the first") +ok(W.pick_place("Nowhere", {"generationtime_ms": 0.1}) is None, "no results: no place") +print("ok - weather: the requests send a rounded place or the city, and \"Town, ST\" picks the state") + +# A run +ok(W.reading({"current": {"temperature_2m": 11.6, "weather_code": 2}}, "C", 1790000000000.4) + == {"at": 1790000000000, "temperature": 12, "unit": "°C", "text": "Partly cloudy"}, "the reading's shape") +ok(W.reading({"current": {}}, "C", 1) is None, "no temperature: no reading") + +calls = [] + + +def fake(answers): + def fetch(url): + calls.append(url) + for key, value in answers.items(): + if key in url: + if isinstance(value, Exception): + raise value + return value + raise AssertionError(url) + return fetch + + +geo.update(usable=False, answer=None) +net = {"geocoding-api": results, "api.open-meteo.com/v1/forecast": {"current": {"temperature_2m": 47.4, "weather_code": 61}}} +reset(); calls.clear() +ok(W.run(fake(net), lambda: 1790000000.0, us) == 0 and calls == [], "no place: nothing fetched") +ok(not os.path.exists(W.READING), "no place: nothing written") +W.main(["omamobile-weather", "set", "State College, PA", "F"]) +ok(json.load(open(W.CONFIG)) == {"city": "State College, PA", "unit": "F"}, "set saves the city and unit") +ok(W.main(["omamobile-weather", "set", "Oslo", "K"]) == 2, "set refuses a unit that isn't F or C") +ok(W.run(fake(net), lambda: 1790000000.0, us) == 0, "a run with a city") +ok(len(calls) == 2 and "name=State" in calls[0] and "latitude=40.79&longitude=-77.86" in calls[1] + and "temperature_unit=fahrenheit" in calls[1], "the city is looked up, then its weather fetched " + str(calls)) +r = json.load(open(W.READING)) +ok(r == {"at": 1790000000000, "temperature": 47, "unit": "°F", "text": "Rain", "source": "setting"}, "the reading the lock reads %s" % r) +ok(isinstance(r["temperature"], int), "a whole temperature") +calls.clear() +ok(W.run(fake(net), lambda: 1790001800.0, us) == 0 and len(calls) == 1 and "forecast" in calls[0], "the place is looked up once") +write(W.CONFIG, {"city": "state college, pa", "unit": "F"}) +calls.clear() +W.run(fake(net), lambda: 1790001800.0, us) +ok(len(calls) == 1, "the same city written differently: no new lookup") +write(W.CONFIG, {"city": "Oslo", "unit": "C"}) +calls.clear() +W.run(fake({"geocoding-api": {"results": [{"name": "Oslo", "latitude": 59.91, "longitude": 10.75}]}, + "api.open-meteo.com": {"current": {"temperature_2m": 3.2, "weather_code": 71}}}), lambda: 1790003600.0, us) +ok(len(calls) == 2 and "name=Oslo" in calls[0] and "latitude=59.91" in calls[1], "a new city is looked up again") +ok(set(json.load(open(W.PLACE))["cities"]) == {"state college, pa", "oslo"}, "both cities are kept, by name") +before = open(W.READING).read() +ok(json.loads(before)["text"] == "Snow" and json.loads(before)["unit"] == "°C", "the new city's reading") +geo.update(usable=True, answer=(52.52, 13.41)) +calls.clear() +W.run(fake({"api.open-meteo.com": {"current": {"temperature_2m": 9.0, "weather_code": 3}}}), lambda: 1790003600.0, us) +ok(len(calls) == 1 and "latitude=52.52&longitude=13.41" in calls[0] and json.load(open(W.READING))["source"] == "location", + "with Location on, the reading is for the phone's position, and says so") +ok(json.load(open(W.PLACE))["fix"]["latitude"] == 52.52, "the fix is kept in the state file") +geo.update(usable=False, answer=None) +write(W.PLACE, {"cities": json.load(open(W.PLACE))["cities"]}) +W.run(fake({"api.open-meteo.com": {"current": {"temperature_2m": 3.2, "weather_code": 71}}}), lambda: 1790003600.0, us) +before = open(W.READING).read() +calls.clear() +ok(W.run(fake({"api.open-meteo.com": OSError("timed out")}), lambda: 1790005400.0, us) == 1 and len(calls) == 1, + "a failed fetch: one try, and the run fails") +ok(open(W.READING).read() == before, "a failed fetch leaves the old reading") +calls.clear() +ok(W.run(fake({"api.open-meteo.com": {"error": True}}), lambda: 1790005400.0, us) == 1 and open(W.READING).read() == before, + "an answer without a temperature leaves the old reading") +write(W.CONFIG, {"city": "Atlantis"}) +calls.clear() +ok(W.run(fake({"geocoding-api": {"generationtime_ms": 0.1}}), lambda: 1790005400.0, us) == 1 and len(calls) == 1 + and open(W.READING).read() == before, "a city that isn't found: no forecast, the old reading stays") +ok(not [n for n in os.listdir(W.STATE_DIR) if n.startswith(".weather-")], "no temporary files are left behind") +print("ok - weather: a run writes the lock's reading (with its source) atomically, looks a city up once, and keeps the old reading on failure") + +# where-am-i's output, as GeoClue's demo prints it +fake_wai = os.path.join(home, "wai") +with open(fake_wai, "w") as f: + f.write("#!/bin/sh\nprintf 'New location:\\nLatitude: 40.793450\\302\\260\\nLongitude: -77.860120\\302\\260\\nAccuracy: 25000.000000 meters\\n'\n") +os.chmod(fake_wai, 0o755) +loader.exec_module(W) +W.WHERE_AM_I = fake_wai +ok(W.where_am_i() == (40.79, -77.86), "where-am-i's answer, rounded to about 1 km") +with open(fake_wai, "w") as f: + f.write("#!/bin/sh\necho 'Failed to connect to GeoClue service'\n") +ok(W.where_am_i() is None, "no answer: none") +W.WHERE_AM_I = os.path.join(home, "missing") +ok(W.geoclue_usable() is False, "no where-am-i: GeoClue isn't usable") +print("ok - weather: GeoClue's where-am-i is read at city accuracy, and missing means not usable") diff --git a/packages/omamobile-shell/version b/packages/omamobile-shell/version index 655b3ef46..c1e088e61 100644 --- a/packages/omamobile-shell/version +++ b/packages/omamobile-shell/version @@ -1 +1 @@ -0.2.40 +0.2.41