Files
omarchy-tempestwx/Panel.qml
T

1159 lines
48 KiB
QML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Quickshell
import Quickshell.Io
import qs.Commons
import qs.Commons as Commons
import qs.Ui
// TempestWX: bar pill (icon + temperature) and a panel with current
// conditions, the next hours and the week ahead from a Tempest personal
// weather station (WeatherFlow REST API).
//
// Token: ~/.config/tempestwx/token (dir 0700, file 0600). The token is never
// placed in a command line, logged or displayed: curl reads its URL from
// stdin and the paste field hands the token to the saver over stdin.
Panel {
id: root
moduleName: "io.github.swaits.tempestwx"
ipcTarget: "io.github.swaits.tempestwx"
manageIpc: false
readonly property string pluginId: "io.github.swaits.tempestwx"
readonly property string tokensUrl: "https://tempestwx.com/settings/tokens"
readonly property string apiBase: "https://swd.weatherflow.com/swd/rest/"
Commons.Translations { id: strings; directory: Qt.resolvedUrl("i18n") }
function tr(key) { return strings.t(key) }
// ---- settings -----------------------------------------------------------
readonly property bool metric: String(setting("units", "us")) === "metric"
readonly property int refreshMinutes: Math.max(1, Math.min(60, Number(setting("refreshMinutes", 5)) || 5))
readonly property string stationSetting: {
var s = String(setting("stationId", ""))
return /^[0-9]{1,10}$/.test(s) ? s : ""
}
readonly property string tUnit: metric ? "°C" : "°F"
readonly property string wUnit: metric ? "m/s" : "mph"
readonly property string pUnit: metric ? "hPa" : "inHg"
readonly property string rUnit: metric ? "mm" : "in"
readonly property string dUnit: metric ? "km" : "mi"
// ---- data ---------------------------------------------------------------
property var current: null
property var daily: []
property var hourly: []
property var stations: [] // [{id, name}]
property string autoStationId: ""
property string stationName: ""
property string tokenState: "unknown" // unknown | ok | missing | invalid
property string tokenTail: ""
property string statusText: "" // "", "error"
property string errorDetail: ""
property double fetchedAt: 0
property double nowMs: Date.now()
property bool settingsOpen: false
property bool replacing: false
property bool removeArmed: false
property bool setupBusy: false
property string setupMessage: ""
property bool setupOk: false
property bool aiAvailable: false
readonly property string stationId: stationSetting !== "" ? stationSetting : autoStationId
readonly property bool needPick: tokenState === "ok" && stationSetting === "" && autoStationId === "" && stations.length > 1
readonly property string view: {
if (tokenState === "missing" || tokenState === "invalid" || replacing) return "setup"
if (settingsOpen) return "settings"
if (needPick) return "stations"
return "weather"
}
readonly property bool stale: fetchedAt > 0 && (nowMs - fetchedAt) > (refreshMinutes * 2 + 1) * 60000
readonly property bool failing: statusText !== "" && fetchedAt > 0
readonly property color foreground: bar ? bar.foreground : Commons.Color.foreground
readonly property color urgent: bar ? bar.urgent : Commons.Color.urgent
readonly property color accent: Commons.Color.accent
readonly property color dim: Qt.darker(foreground, 1.4)
readonly property string fontFamily: bar ? bar.fontFamily : Style.font.family
readonly property var locale: Qt.locale(Commons.I18n.formatLocale)
property bool centredOnBar: false
visible: true
implicitWidth: button.implicitWidth
readonly property bool vertical: bar ? bar.vertical : false
width: implicitWidth
height: implicitHeight
implicitHeight: vertical ? button.implicitHeight : (bar ? bar.barSize : Style.bar.sizeHorizontal)
// ---- helpers ------------------------------------------------------------
function num(v) { return (typeof v === "number" && isFinite(v)) ? v : null }
function fmt(v, d) {
var n = num(v)
return n === null ? "–" : Commons.I18n.formatNumber(n, d === undefined ? 0 : d)
}
function deg(v) { return num(v) === null ? "–" : fmt(Math.round(v), 0) + "°" }
function glyph(icon) {
var g = {
"clear-day": "󰖙", "clear-night": "󰖔",
"partly-cloudy-day": "󰖕", "partly-cloudy-night": "󰼱",
"cloudy": "󰖐", "foggy": "󰖑", "windy": "󰖝",
"possibly-rainy-day": "󰖖", "possibly-rainy-night": "󰖖",
"rainy": "󰖖", "possibly-sleet-day": "󰙿", "possibly-sleet-night": "󰙿",
"sleet": "󰙿", "possibly-snow-day": "󰼶", "possibly-snow-night": "󰼶",
"snow": "󰼶", "possibly-thunderstorm-day": "󰖓",
"possibly-thunderstorm-night": "󰖓", "thunderstorm": "󰖓"
}
return g[String(icon)] || "󰖐"
}
// Times are shown in the station's own time zone (whole-hour offset taken
// from the forecast's local_hour), not the computer's.
property string timezone: ""
readonly property real stOffset: {
for (var i = 0; i < hourly.length; i++) {
var h = hourly[i]
if (num(h.time) !== null && num(h.local_hour) !== null) {
var off = h.local_hour - new Date(h.time * 1000).getUTCHours()
while (off > 12) off -= 24
while (off < -12) off += 24
return off
}
}
return -new Date().getTimezoneOffset() / 60
}
function stDate(sec) {
var s = new Date(sec * 1000 + stOffset * 3600000)
return new Date(s.getUTCFullYear(), s.getUTCMonth(), s.getUTCDate(), s.getUTCHours(), s.getUTCMinutes())
}
function clockTime(sec, withMin) {
if (!num(sec)) return "–"
return locale.toString(stDate(sec), withMin ? "h:mm ap" : "h ap")
}
function dayLabel(d) {
if (!d || !num(d.day_start_local)) return "–"
return locale.toString(stDate(d.day_start_local + 3600), "ddd d")
}
function sunEvent(t) {
for (var i = 0; i < Math.min(2, daily.length); i++) {
var d = daily[i]
if (num(d.sunrise) !== null && d.sunrise >= t && d.sunrise < t + 3600) return "rise"
if (num(d.sunset) !== null && d.sunset >= t && d.sunset < t + 3600) return "set"
}
return ""
}
function sunTime(t, rise) {
for (var i = 0; i < Math.min(2, daily.length); i++) {
var v = rise ? daily[i].sunrise : daily[i].sunset
if (num(v) !== null && v >= t && v < t + 3600) return v
}
return t
}
function precipGlyph(h) {
var t = String(h && h.precip_type || ""), ic = String(h && h.precip_icon || "")
return (t === "snow" || t === "sleet" || ic.indexOf("snow") >= 0) ? "󰜗" : "󰖌"
}
// Theme-coloured weather icons: warm sun, cool moon and rain.
property color sunColor: "#e0a93b"
property color moonColor: "#5b9bd5"
function glyphColor(icon) {
var i = String(icon || "")
if (i.indexOf("night") >= 0) return moonColor
if (i.indexOf("clear-day") >= 0 || i.indexOf("partly-cloudy-day") >= 0) return sunColor
if (i.indexOf("rain") >= 0 || i.indexOf("thunder") >= 0) return moonColor
return foreground
}
FileView {
path: Quickshell.env("HOME") + "/.local/state/omarchy/current/theme/colors.toml"
watchChanges: true
printErrors: false
onFileChanged: reload()
onLoaded: {
var y = /^\s*yellow\s*=\s*"(#[0-9a-fA-F]{6})"/m.exec(text())
var b = /^\s*blue\s*=\s*"(#[0-9a-fA-F]{6})"/m.exec(text())
if (y) root.sunColor = y[1]
if (b) root.moonColor = b[1]
}
}
function ago(ms) {
var s = Math.max(0, Math.round((nowMs - ms) / 1000))
if (s < 90) return tr("ago.now")
var m = Math.round(s / 60)
if (m < 90) return tr("ago.min").arg(m)
return tr("ago.hour").arg(Math.round(m / 60))
}
function uvWord(u) {
if (u === null) return ""
if (u < 3) return tr("uv.low")
if (u < 6) return tr("uv.moderate")
if (u < 8) return tr("uv.high")
if (u < 11) return tr("uv.veryhigh")
return tr("uv.extreme")
}
function clean(s, n) { return String(s === undefined || s === null ? "" : s).substring(0, n || 80) }
function mphOf(v) { return metric ? v * 2.237 : v }
function windLevel(v) {
var m = mphOf(v), th = [1, 8, 16, 25, 32], n = 0
for (var i = 0; i < th.length; i++) if (m >= th[i]) n++
return n
}
function precipKind(h) {
var ic = String(h && h.icon || ""), t = String(h && h.precip_type || "")
if (ic.indexOf("thunder") >= 0) return tr("precip.storm")
if (ic.indexOf("snow") >= 0 || t === "snow") return tr("precip.snow")
if (ic.indexOf("sleet") >= 0 || t === "sleet") return tr("precip.sleet")
return tr("precip.rain")
}
// Upcoming hours (from the current one) used by the strip and "what's next".
readonly property var upcoming: {
var cut = nowMs / 1000 - 1800, out = []
for (var i = 0; i < hourly.length && out.length < 24; i++)
if (num(hourly[i].time) !== null && hourly[i].time >= cut) out.push(hourly[i])
return out
}
readonly property string nextLine: {
var c = current
if (!c) return ""
var h = upcoming
var lc = num(c.lightning_strike_count_last_3hr)
if (lc !== null && lc > 0) return tr("next.lightning").arg(fmt(lc, 0))
for (var i = 0; i < h.length; i++) {
var p = num(h[i].precip_probability)
if (p !== null && p >= 50)
return i === 0 ? tr("next.precip.now").arg(precipKind(h[i]))
: tr("next.precip.from").arg(precipKind(h[i])).arg(clockTime(h[i].time, false))
}
var best = -1, bp = 0
for (var j = 0; j < h.length; j++) {
var q = num(h[j].precip_probability)
if (q !== null && q >= 30 && q > bp) { bp = q; best = j }
}
if (best >= 0)
return tr("next.chance").arg(precipKind(h[best]).toLowerCase()).arg(clockTime(h[best].time, false)).arg(fmt(bp, 0) + "%")
var now = num(c.air_temperature)
var span = metric ? 4.5 : 8
if (now !== null) {
var lo = null, loAt = -1, hi = null, hiAt = -1
for (var k = 0; k < Math.min(h.length, 13); k++) {
var t = num(h[k].air_temperature)
if (t === null) continue
if (lo === null || t < lo) { lo = t; loAt = k }
if (hi === null || t > hi) { hi = t; hiAt = k }
}
if (lo !== null && now - lo >= span && (hi === null || now - lo >= hi - now))
return tr("next.falling").arg(deg(lo)).arg(clockTime(h[loAt].time, false))
if (hi !== null && hi - now >= span)
return tr("next.rising").arg(deg(hi)).arg(clockTime(h[hiAt].time, false))
}
if (h.length >= 23) return tr("next.dry")
return h.length > 1 ? tr("next.dryshort").arg(h.length) : ""
}
readonly property string barTemp: current && num(current.air_temperature) !== null
? Commons.I18n.formatNumber(Math.round(current.air_temperature), 0) + "°" : ""
readonly property string barGlyph: current ? glyph(current.icon) : "󰖐"
readonly property string barText: tokenState === "missing" || tokenState === "invalid"
? "?" : (barTemp !== "" ? barTemp : "…")
// ---- fetching -----------------------------------------------------------
// curl reads its URL from stdin so the token never appears in a process list.
readonly property string curlScript:
't=$(head -n1 "$HOME/.config/tempestwx/token" 2>/dev/null | tr -d "[:space:]"); ' +
'[ -n "$t" ] || exit 3; ' +
'printf "url = \\"%stoken=%s\\"\\n" "$1" "$t" | curl -sS -m 20 --max-filesize 3000000 -w "\\n%{http_code}" -K -'
function refresh() {
if (fetchProc.running || stationsProc.running) return
if (stationId === "") { discover(); return }
var u = metric ? ["c", "mps", "mb", "mm", "km"] : ["f", "mph", "inhg", "in", "mi"]
fetchProc.command = ["sh", "-c", curlScript, "sh",
apiBase + "better_forecast?station_id=" + stationId + "&units_temp=" + u[0] + "&units_wind=" + u[1] +
"&units_pressure=" + u[2] + "&units_precip=" + u[3] + "&units_distance=" + u[4] + "&"
]
fetchProc.running = true
}
function discover() {
if (stationsProc.running) return
stationsProc.command = ["sh", "-c", curlScript, "sh", apiBase + "stations?"]
stationsProc.running = true
}
function splitCode(text) {
var nl = text.lastIndexOf("\n")
return { code: nl >= 0 ? text.substring(nl + 1).trim() : "", body: nl >= 0 ? text.substring(0, nl) : text }
}
function setupFail(msg) { setupBusy = false; setupOk = false; setupMessage = msg }
function applyStations(text) {
var r = splitCode(text), d
if (r.code === "401" || r.code === "403") { markInvalid(); return }
if (r.code === "429") { if (setupBusy) setupFail(tr("error.rate")); else fail(tr("error.rate")); return }
try { d = JSON.parse(r.body) } catch (e) { if (setupBusy) setupFail(tr("error.bad")); else fail(tr("error.bad")); return }
if (!d || !Array.isArray(d.stations)) { if (setupBusy) setupFail(tr("error.bad")); else fail(tr("error.bad")); return }
var list = []
for (var i = 0; i < d.stations.length && list.length < 20; i++) {
var s = d.stations[i]
if (!s || !/^[0-9]{1,10}$/.test(String(s.station_id))) continue
list.push({ id: String(s.station_id), name: clean(s.name || s.public_name || ("Station " + s.station_id), 60) })
}
stations = list
tokenState = "ok"
statusText = ""
if (list.length === 1) autoStationId = list[0].id
else if (list.length === 0) {
if (setupBusy) setupFail(tr("setup.nostations"))
else fail(tr("setup.nostations"))
return
}
if (setupBusy) {
setupBusy = false
setupOk = true
setupMessage = tr("setup.ok").arg(list.length === 1 ? list[0].name : String(list.length))
okTimer.restart()
}
refresh()
}
function markInvalid() {
if (setupBusy) {
setupFail(tr("error.token"))
tokenState = "invalid"
return
}
tokenState = "invalid"
}
function applyForecast(text) {
var r = splitCode(text), d
if (r.code === "429") { fail(tr("error.rate")); return }
if (r.code === "401" || r.code === "403") { markInvalid(); return }
try { d = JSON.parse(r.body) } catch (e) { fail(tr("error.bad")); return }
if (!d || !d.current_conditions) {
var msg = d && d.status && d.status.status_message ? clean(d.status.status_message, 120) : tr("error.nodata")
fail(msg); return
}
tokenState = "ok"
current = d.current_conditions
var f = d.forecast || {}
daily = Array.isArray(f.daily) ? f.daily.slice(0, 10) : []
hourly = Array.isArray(f.hourly) ? f.hourly.slice(0, 72) : []
timezone = clean(d.timezone, 40)
var nm = ""
for (var i = 0; i < stations.length; i++) if (stations[i].id === stationId) nm = stations[i].name
stationName = nm !== "" ? nm : clean(d.location_name, 60)
fetchedAt = Date.now()
statusText = ""
errorDetail = ""
}
function fail(detail) {
statusText = "error"
errorDetail = detail
}
property string _body: ""
property string _sbody: ""
Process {
id: fetchProc
stdout: StdioCollector { onStreamFinished: root._body = text }
onExited: function(code) {
if (code === 3) { root.tokenState = "missing"; return }
if (code !== 0) { root.fail(root.tr("error.network")); return }
root.applyForecast(root._body)
}
}
Process {
id: stationsProc
stdout: StdioCollector { onStreamFinished: root._sbody = text }
onExited: function(code) {
if (code === 3) { root.tokenState = "missing"; root.setupBusy = false; return }
if (code !== 0) {
if (root.setupBusy) root.setupFail(root.tr("error.network"))
else root.fail(root.tr("error.network"))
return
}
root.applyStations(root._sbody)
}
}
// Reads only the last 4 characters of the saved token, for the settings view.
Process {
id: tailProc
command: ["sh", "-c", 't=$(head -n1 "$HOME/.config/tempestwx/token" 2>/dev/null | tr -d "[:space:]"); printf "%s" "${t: -4}"']
stdout: StdioCollector { onStreamFinished: root.tokenTail = String(text).trim() }
}
// The token arrives on stdin and is written owner-only.
Process {
id: saveProc
stdinEnabled: true
command: ["sh", "-c",
'umask 077; d="$HOME/.config/tempestwx"; mkdir -p "$d" && chmod 700 "$d" && IFS= read -r t && ' +
'printf "%s\\n" "$t" > "$d/token.tmp" && chmod 600 "$d/token.tmp" && mv "$d/token.tmp" "$d/token"']
onExited: function(code) {
if (code !== 0) { root.setupFail(root.tr("setup.savefail")); return }
root.stations = []; root.autoStationId = ""
root.discover()
}
}
Process {
id: removeProc
command: ["rm", "-f", Quickshell.env("HOME") + "/.config/tempestwx/token"]
onExited: {
root.current = null; root.daily = []; root.hourly = []; root.stations = []
root.autoStationId = ""; root.fetchedAt = 0; root.statusText = ""
root.settingsOpen = false; root.removeArmed = false; root.replacing = false
root.setupMessage = ""; root.setupOk = false
root.tokenState = "missing"
}
}
Process {
id: aiCheck
command: ["sh", "-c", "command -v omarchy-agent >/dev/null 2>&1"]
onExited: function(code) { root.aiAvailable = (code === 0) }
}
Process { id: setProc }
function writeSetting(key, value, asJson) {
var cmd = ["omarchy", "bar", "set", pluginId, key, String(value)]
if (asJson) cmd.push("--json")
setProc.command = cmd
setProc.running = true
}
function saveToken(raw) {
var t = String(raw).trim()
if (!/^[A-Za-z0-9-]{8,128}$/.test(t)) { setupOk = false; setupMessage = tr("setup.format"); return }
setupBusy = true; setupOk = false; setupMessage = tr("setup.checking")
saveProc.running = true
saveProc.write(t + "\n")
saveProc.stdinEnabled = false
}
function launchAi() {
Quickshell.execDetached(["omarchy", "agent", "prompt", tr("ai.prompt")])
root.close()
}
function openTokens() { Quickshell.execDetached(["xdg-open", tokensUrl]) }
Timer {
id: okTimer
interval: 1400
onTriggered: { root.replacing = false; root.setupMessage = ""; root.setupOk = false }
}
Timer {
interval: root.refreshMinutes * 60000
running: true
repeat: true
onTriggered: root.refresh()
}
Timer {
interval: 30000
running: true
repeat: true
onTriggered: root.nowMs = Date.now()
}
Component.onCompleted: { aiCheck.running = true; refresh() }
onSettingsChanged: { if (tokenState !== "missing" && tokenState !== "invalid") refresh() }
onTokenStateChanged: if (tokenState === "ok") tailProc.running = true
function openPanel() {
nowMs = Date.now()
settingsOpen = false; replacing = false; removeArmed = false
if (tokenState === "missing") tokenState = "unknown"
if (fetchedAt === 0 || nowMs - fetchedAt > 60000 || statusText !== "" || tokenState === "unknown") refresh()
open()
}
function togglePanel() { opened ? close() : openPanel() }
ShellIpc {
target: root.ipcTarget
function open(): void { root.openPanel() }
function close(): void { root.close() }
function toggle(): void { root.togglePanel() }
function settings(): void { root.openPanel(); root.settingsOpen = true }
}
function inMiddleOfBar() {
var win = button.QsWindow.window
if (!win) return false
var vertical = root.bar && root.bar.vertical
var at = button.mapToItem(null, button.width / 2, button.height / 2)
var span = vertical ? win.height : win.width
var middle = vertical ? at.y : at.x
return Math.abs(middle - span / 2) < span * 0.2
}
onOpenedChanged: if (opened) centredOnBar = inMiddleOfBar()
// ---- bar pill -----------------------------------------------------------
WidgetButton {
id: button
anchors.fill: parent
bar: root.bar
labelVisible: false
hasVisualContent: true
fixedWidth: root.vertical ? -1 : pill.implicitWidth + Style.space(12)
fixedHeight: root.vertical ? pill.implicitHeight + Style.space(8) : -1
tooltipText: root.view === "setup" && root.current === null
? root.tr("tip.setup")
: (root.fetchedAt > 0 ? root.tr("tip.updated").arg(root.ago(root.fetchedAt)) : "TempestWX")
onPressed: function(b) {
if (b === Qt.MiddleButton) root.refresh()
else root.togglePanel()
}
GridLayout {
id: pill
anchors.centerIn: parent
columns: root.vertical ? 1 : 2
rowSpacing: Style.space(1)
columnSpacing: Style.space(3)
Text {
Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
textFormat: Text.PlainText
text: root.barGlyph
color: root.stale || root.failing ? root.dim : button.foreground
font.family: button.fontFamily
font.pixelSize: Style.font.caption
}
Text {
Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
textFormat: Text.PlainText
text: root.barText + (root.stale ? "*" : "")
color: root.stale || root.failing ? root.dim : button.foreground
font.family: button.fontFamily
font.pixelSize: Style.font.bodySmall
font.weight: Font.DemiBold
}
}
}
// ---- panel --------------------------------------------------------------
KeyboardPanel {
id: panel
anchorItem: button
owner: root
bar: root.bar
open: root.opened
centerOnBar: root.centredOnBar
focusTarget: keyCatcher
contentWidth: panel.fittedContentWidth(Style.space(420))
contentHeight: panel.fittedContentHeight(column.implicitHeight, Style.space(900))
PanelKeyCatcher {
id: keyCatcher
anchors.fill: parent
blocked: tokenField.activeFocus
onCloseRequested: {
if (root.replacing && root.tokenState === "ok") root.replacing = false
else if (root.settingsOpen) root.settingsOpen = false
else root.close()
}
onTabRequested: function(direction) { root.switchPanel(direction) }
onTextKey: function(t) { if (t.toLowerCase() === "r" && root.view === "weather") root.refresh() }
Flickable {
id: flick
anchors.fill: parent
contentWidth: width
contentHeight: column.implicitHeight
clip: true
boundsBehavior: Flickable.StopAtBounds
flickableDirection: Flickable.VerticalFlick
interactive: contentHeight > height
ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded }
Column {
id: column
x: Style.space(2)
width: flick.width - Style.space(4)
spacing: Style.space(12)
component T: Text {
textFormat: Text.PlainText
color: root.foreground
font.family: root.fontFamily
font.pixelSize: Style.font.body
elide: Text.ElideRight
}
// =================== WEATHER ===================
Column {
id: weatherView
visible: root.view === "weather"
width: parent.width
spacing: Style.space(12)
T {
visible: root.current === null && root.statusText === ""
width: parent.width
color: root.dim
font.italic: true
text: root.tr("loading")
}
T {
visible: root.current === null && root.statusText === "error"
width: parent.width
wrapMode: Text.WordWrap
elide: Text.ElideNone
color: root.urgent
text: root.tr("error.load").arg(root.errorDetail)
}
// ---- Hero: temperature + feels like | condition icon + text
RowLayout {
visible: root.current !== null
width: parent.width
spacing: Style.space(14)
ColumnLayout {
Layout.fillWidth: true
Layout.preferredWidth: 1
spacing: 0
Row {
spacing: Style.space(2)
LayoutMirroring.enabled: false
T {
id: bigTemp
text: root.fmt(root.current ? root.current.air_temperature : null, 0)
font.pixelSize: Style.space(54)
font.weight: Font.Bold
}
T {
text: root.tUnit
color: root.dim
font.pixelSize: Style.font.heading
anchors.top: bigTemp.top
anchors.topMargin: Style.space(10)
}
}
T {
color: root.dim
text: root.tr("hero.feels").arg(root.deg(root.current ? root.current.feels_like : null))
}
}
ColumnLayout {
Layout.fillWidth: true
Layout.preferredWidth: 1
spacing: Style.space(2)
T {
Layout.alignment: Qt.AlignHCenter
text: root.barGlyph
color: root.current ? root.glyphColor(root.current.icon) : root.foreground
font.pixelSize: Style.space(46)
}
T {
Layout.alignment: Qt.AlignHCenter
Layout.fillWidth: true
horizontalAlignment: Text.AlignHCenter
text: root.current && root.current.conditions ? root.clean(root.current.conditions, 40) : ""
}
}
}
// ---- What's next
Row {
visible: root.current !== null && root.nextLine !== ""
width: parent.width
spacing: Style.space(8)
Rectangle {
width: Style.space(2)
height: nextText.implicitHeight
color: root.accent
}
T {
id: nextText
width: parent.width - Style.space(10)
wrapMode: Text.WordWrap
elide: Text.ElideNone
font.weight: Font.Medium
text: root.nextLine
}
}
// ---- Conditions tiles
GridLayout {
id: tiles
visible: root.current !== null
width: parent.width
columns: 2
columnSpacing: Style.space(12)
rowSpacing: Style.space(10)
property var c: root.current || ({})
component Tile: RowLayout {
id: tile
property string icon: ""
property real iconRotation: 0
property bool ring: false
property string value: ""
property string label: ""
property string detail: ""
property color detailColor: root.dim
property int level: -1
Layout.fillWidth: true
Layout.preferredWidth: 1
Layout.alignment: Qt.AlignTop
spacing: Style.space(10)
Item {
Layout.preferredWidth: Style.space(26)
Layout.preferredHeight: Style.space(26)
Layout.alignment: Qt.AlignTop
Rectangle {
visible: tile.ring
anchors.fill: parent
radius: width / 2
color: "transparent"
border.width: Math.max(1, Style.space(1))
border.color: root.foreground
}
T {
anchors.centerIn: parent
text: tile.icon
elide: Text.ElideNone
font.pixelSize: tile.ring ? Style.font.icon : Style.font.iconLarge + 2
rotation: tile.iconRotation
}
}
ColumnLayout {
Layout.fillWidth: true
spacing: Style.space(2)
Row {
Layout.fillWidth: true
spacing: Style.space(4)
T { id: tv; text: tile.value; font.weight: Font.Bold; elide: Text.ElideNone }
T { width: Math.max(0, parent.width - tv.width - parent.spacing); text: tile.label }
}
Row {
visible: tile.level >= 0
spacing: Style.space(2)
Repeater {
model: 5
Rectangle {
required property int index
width: Style.space(18); height: Style.space(5)
radius: Style.cornerRadius
color: index < tile.level ? root.accent : Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.15)
}
}
}
T {
visible: tile.detail !== ""
Layout.fillWidth: true
color: tile.detailColor
font.pixelSize: Style.font.bodySmall
text: tile.detail
}
}
}
Tile {
icon: "󰖎"
value: root.fmt(tiles.c.relative_humidity, 0) + "%"
label: root.tr("tile.humidity")
}
Tile {
ring: true
icon: "󰁝"
iconRotation: (root.num(tiles.c.wind_direction) !== null ? tiles.c.wind_direction : 0) + 180
value: (tiles.c.wind_direction_cardinal ? root.clean(tiles.c.wind_direction_cardinal, 4) + " " : "")
+ root.fmt(tiles.c.wind_avg, 0)
label: root.wUnit
level: root.num(tiles.c.wind_avg) !== null ? root.windLevel(tiles.c.wind_avg) : -1
detail: root.num(tiles.c.wind_gust) !== null && tiles.c.wind_gust > (tiles.c.wind_avg || 0)
? root.tr("tile.gust").arg(root.fmt(tiles.c.wind_gust, 0)).arg(root.wUnit) : ""
}
Tile {
ring: true
icon: "󰁝"
iconRotation: tiles.c.pressure_trend === "rising" ? 0 : (tiles.c.pressure_trend === "falling" ? 180 : 90)
value: root.fmt(root.num(tiles.c.sea_level_pressure) !== null ? tiles.c.sea_level_pressure : tiles.c.station_pressure, root.metric ? 1 : 2)
label: root.pUnit
detail: tiles.c.pressure_trend ? root.tr("tile.trend." + (["rising", "falling"].indexOf(String(tiles.c.pressure_trend)) >= 0 ? String(tiles.c.pressure_trend) : "steady")) : ""
}
Tile {
icon: "󰖙"
value: root.fmt(tiles.c.uv, 0)
label: root.tr("tile.uv")
detail: root.num(tiles.c.uv) === null ? "" : (root.uvWord(tiles.c.uv)
+ (root.num(tiles.c.solar_radiation) !== null ? " · " + root.tr("tile.solar").arg(root.fmt(tiles.c.solar_radiation, 0)) : ""))
}
Tile {
icon: "󰖗"
value: root.fmt(tiles.c.precip_accum_local_day, 2)
label: root.rUnit + " " + root.tr("tile.rain")
}
Tile {
visible: root.num(tiles.c.lightning_strike_count_last_3hr) !== null
icon: "󱐋"
value: root.fmt(tiles.c.lightning_strike_count_last_3hr, 0)
label: root.tr("tile.lightning.strikes")
detail: (tiles.c.lightning_strike_count_last_3hr || 0) > 0
? root.tr("tile.lightning.last").arg(root.fmt(tiles.c.lightning_strike_last_distance, 0)).arg(root.dUnit)
: root.tr("tile.lightning.none")
detailColor: (tiles.c.lightning_strike_count_last_3hr || 0) > 0 ? root.urgent : root.dim
}
}
// ---- Today row
DayRow {
visible: root.daily.length > 0
width: parent.width
day: root.tr("day.today")
shaded: true
info: root.daily.length ? root.daily[0] : ({})
}
// ---- Next hours (sunrise / sunset markers above the strip)
ListView {
id: hours
visible: root.upcoming.length > 0
width: parent.width
readonly property bool anyPrecipLine: true
readonly property bool anyMarker: root.upcoming.some(function(h) { return root.sunEvent(h.time) !== "" })
height: (anyMarker ? Style.font.caption * 1.5 : 0) + Style.font.bodySmall * 1.35 * 3 + Style.font.iconLarge * 1.4 + Style.font.body * 1.35
orientation: ListView.Horizontal
spacing: 0
clip: true
boundsBehavior: Flickable.StopAtBounds
model: root.upcoming
WheelHandler {
acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad
onWheel: function(ev) {
var d = ev.angleDelta.y !== 0 ? ev.angleDelta.y : ev.angleDelta.x
hours.contentX = Math.max(0, Math.min(hours.contentWidth - hours.width, hours.contentX - d))
}
}
delegate: Column {
required property var modelData
required property int index
width: Style.space(56)
spacing: Style.space(1)
readonly property string sun: root.sunEvent(modelData.time)
T { visible: hours.anyMarker; width: parent.width; horizontalAlignment: Text.AlignHCenter
font.pixelSize: Style.font.caption; color: root.dim; elide: Text.ElideNone
text: parent.sun === "rise" ? "󰖜 " + root.clockTime(root.sunTime(modelData.time, true), true, true)
: (parent.sun === "set" ? "󰖛 " + root.clockTime(root.sunTime(modelData.time, false), true, true) : " ") }
T { width: parent.width; horizontalAlignment: Text.AlignHCenter; font.pixelSize: Style.font.bodySmall
color: root.dim; text: index === 0 ? root.tr("time.now") : root.clockTime(modelData.time, false) }
T { width: parent.width; horizontalAlignment: Text.AlignHCenter; font.pixelSize: Style.font.iconLarge
color: root.glyphColor(modelData.icon); text: root.glyph(modelData.icon) }
T { width: parent.width; horizontalAlignment: Text.AlignHCenter; font.weight: Font.DemiBold
text: root.deg(modelData.air_temperature) }
T { width: parent.width; horizontalAlignment: Text.AlignHCenter; font.pixelSize: Style.font.bodySmall
color: (root.num(modelData.precip_probability) || 0) > 0 ? root.foreground : root.dim; elide: Text.ElideNone
text: root.precipGlyph(modelData) + " " + root.fmt(modelData.precip_probability, 0) + "%" }
Row {
anchors.horizontalCenter: parent.horizontalCenter
spacing: Style.space(3)
T { text: "󰁝"; font.pixelSize: Style.font.bodySmall; color: root.dim
rotation: (root.num(modelData.wind_direction) || 0) + 180 }
T { text: root.fmt(modelData.wind_avg, 0); font.pixelSize: Style.font.bodySmall; color: root.dim }
}
}
}
// ---- Daily rows
Column {
visible: root.daily.length > 1
width: parent.width
spacing: 0
Repeater {
model: root.daily.slice(1, 10)
delegate: DayRow {
required property var modelData
required property int index
width: parent.width
day: root.dayLabel(modelData)
shaded: index % 2 === 1
info: modelData
}
}
}
// ---- Footer
PanelSeparator { foreground: root.foreground }
RowLayout {
width: parent.width
spacing: Style.space(6)
Rectangle {
Layout.alignment: Qt.AlignVCenter
width: Style.space(7); height: width; radius: width / 2
color: (root.stale || root.failing || root.fetchedAt === 0) ? root.urgent : root.accent
}
T {
Layout.fillWidth: true
font.pixelSize: Style.font.bodySmall
color: (root.stale || root.failing) ? root.urgent : root.dim
text: {
var s = root.stationName !== "" ? root.stationName : (root.stationId !== "" ? root.tr("footer.station").arg(root.stationId) : "")
if (root.fetchedAt > 0) s += (s !== "" ? " · " : "") + root.tr("footer.updated").arg(root.ago(root.fetchedAt))
if (root.failing) s += " · " + root.errorDetail
else if (root.stale) s += " · " + root.tr("footer.stale")
return s
}
}
PanelActionButton {
iconText: "󰑐"
tooltipText: root.tr("footer.refresh")
foreground: root.dim
fontFamily: root.fontFamily
onClicked: root.refresh()
}
PanelActionButton {
iconText: "󰒓"
tooltipText: root.tr("footer.settings")
foreground: root.dim
fontFamily: root.fontFamily
onClicked: root.settingsOpen = true
}
}
T {
visible: root.timezone !== ""
width: parent.width
horizontalAlignment: Text.AlignHCenter
font.pixelSize: Style.font.caption
color: root.dim
text: root.tr("footer.tz").arg(root.timezone)
}
}
// One daily forecast row: day + condition, icon, precip, low, high.
component DayRow: Rectangle {
id: dr
property string day: ""
property bool shaded: false
property var info: ({})
height: Style.space(38)
radius: Style.cornerRadius
color: shaded ? Qt.rgba(root.foreground.r, root.foreground.g, root.foreground.b, 0.06) : "transparent"
RowLayout {
anchors.fill: parent
anchors.leftMargin: Style.space(8)
anchors.rightMargin: Style.space(8)
spacing: Style.space(6)
ColumnLayout {
Layout.fillWidth: true
spacing: 0
T { Layout.fillWidth: true; font.weight: Font.DemiBold; text: dr.day }
T { Layout.fillWidth: true; font.pixelSize: Style.font.bodySmall; color: root.dim
text: root.clean(dr.info.conditions, 30) }
}
T { Layout.preferredWidth: Style.space(30); horizontalAlignment: Text.AlignHCenter
font.pixelSize: Style.font.iconLarge; color: root.glyphColor(dr.info.icon); text: root.glyph(dr.info.icon) }
T { Layout.preferredWidth: Style.space(64); horizontalAlignment: Text.AlignRight; elide: Text.ElideNone
color: (root.num(dr.info.precip_probability) || 0) > 0 ? root.foreground : root.dim
text: root.precipGlyph(dr.info) + " " + root.fmt(dr.info.precip_probability, 0) + "%" }
T { Layout.preferredWidth: Style.space(46); horizontalAlignment: Text.AlignRight; elide: Text.ElideNone
color: root.dim; text: "↓" + root.deg(dr.info.air_temp_low) }
T { Layout.preferredWidth: Style.space(46); horizontalAlignment: Text.AlignRight; elide: Text.ElideNone
font.weight: Font.DemiBold; text: "↑" + root.deg(dr.info.air_temp_high) }
}
}
// =================== STATION PICKER ===================
Column {
visible: root.view === "stations"
width: parent.width
spacing: Style.space(8)
T { font.pixelSize: Style.font.heading; font.weight: Font.Bold; text: root.tr("station.pick") }
T { width: parent.width; color: root.dim; wrapMode: Text.WordWrap; elide: Text.ElideNone; text: root.tr("station.pickhint") }
Repeater {
model: root.stations
delegate: Button {
required property var modelData
width: parent.width
text: modelData.name
leftAlign: true
bordered: true
foreground: root.foreground
fontFamily: root.fontFamily
onClicked: root.writeSetting("stationId", modelData.id, false)
}
}
}
// =================== SETUP ===================
Column {
id: setupView
visible: root.view === "setup"
width: parent.width
spacing: Style.space(10)
T { width: parent.width; font.pixelSize: Style.font.heading; font.weight: Font.Bold; text: root.tr("setup.title") }
T { width: parent.width; color: root.dim; wrapMode: Text.WordWrap; elide: Text.ElideNone; text: root.tr("setup.intro") }
T {
visible: root.tokenState === "invalid"
width: parent.width; color: root.urgent; wrapMode: Text.WordWrap; elide: Text.ElideNone
text: root.tr("error.token")
}
Repeater {
model: [root.tr("setup.step1"), root.tr("setup.step2"), root.tr("setup.step3")]
delegate: Row {
required property string modelData
required property int index
width: setupView.width
spacing: Style.space(8)
T { width: Style.space(16); color: root.accent; font.weight: Font.Bold; text: (index + 1) + "." }
T { width: parent.width - Style.space(24); wrapMode: Text.WordWrap; elide: Text.ElideNone; text: modelData }
}
}
Row {
spacing: Style.space(8)
Button {
text: root.tr("setup.open")
iconText: "󰖟"
bordered: true
foreground: root.foreground
fontFamily: root.fontFamily
onClicked: root.openTokens()
}
Button {
visible: root.aiAvailable
text: root.tr("setup.ai")
iconText: "󰚩"
bordered: true
foreground: root.foreground
fontFamily: root.fontFamily
onClicked: root.launchAi()
}
}
TextField {
id: tokenField
width: parent.width
password: true
enabled: !root.setupBusy
placeholderText: root.tr("setup.field")
foreground: root.foreground
font.family: root.fontFamily
maximumLength: 128
Keys.onEscapePressed: { if (root.replacing && root.tokenState === "ok") root.replacing = false; else root.close() }
Keys.onReturnPressed: root.saveToken(text)
Keys.onEnterPressed: root.saveToken(text)
Connections {
target: root
function onSetupOkChanged() { if (root.setupOk) tokenField.text = "" }
}
}
Row {
spacing: Style.space(8)
Button {
text: root.tr("setup.save")
bordered: true
enabled: !root.setupBusy && tokenField.text.length > 0
foreground: root.foreground
accent: root.accent
fontFamily: root.fontFamily
onClicked: root.saveToken(tokenField.text)
}
Button {
visible: root.replacing
text: root.tr("setup.cancel")
bordered: true
foreground: root.foreground
fontFamily: root.fontFamily
onClicked: { root.replacing = false; root.setupMessage = "" }
}
}
T {
visible: root.setupMessage !== ""
width: parent.width
wrapMode: Text.WordWrap
elide: Text.ElideNone
color: root.setupOk ? root.accent : (root.setupBusy ? root.dim : root.urgent)
text: root.setupMessage
}
T { width: parent.width; font.pixelSize: Style.font.bodySmall; color: root.dim; wrapMode: Text.WordWrap; elide: Text.ElideNone
text: root.tr("setup.where") }
}
// =================== SETTINGS ===================
Column {
id: settingsView
visible: root.view === "settings"
width: parent.width
spacing: Style.space(10)
RowLayout {
width: parent.width
PanelActionButton {
iconText: "󰁍"
tooltipText: root.tr("settings.back")
foreground: root.foreground
fontFamily: root.fontFamily
onClicked: root.settingsOpen = false
}
T { Layout.fillWidth: true; font.pixelSize: Style.font.heading; font.weight: Font.Bold; text: root.tr("settings.title") }
}
PanelSeparator { foreground: root.foreground }
PanelSectionHeader { foreground: root.foreground; fontFamily: root.fontFamily; text: root.tr("settings.token") }
T { width: parent.width; text: root.tr("settings.tokenok").arg(root.tokenTail !== "" ? "…" + root.tokenTail : "…") }
Row {
spacing: Style.space(8)
Button {
text: root.tr("settings.replace")
bordered: true
foreground: root.foreground
fontFamily: root.fontFamily
onClicked: { root.setupMessage = ""; root.setupOk = false; root.replacing = true }
}
Button {
text: root.removeArmed ? root.tr("settings.confirm") : root.tr("settings.remove")
bordered: true
foreground: root.removeArmed ? root.urgent : root.foreground
fontFamily: root.fontFamily
onClicked: { if (root.removeArmed) removeProc.running = true; else root.removeArmed = true }
}
}
PanelSectionHeader { foreground: root.foreground; fontFamily: root.fontFamily; text: root.tr("settings.display") }
Dropdown {
width: parent.width
label: root.tr("settings.units")
foreground: root.foreground
fontFamily: root.fontFamily
options: [root.tr("settings.unitsus"), root.tr("settings.unitsmetric")]
value: root.metric ? root.tr("settings.unitsmetric") : root.tr("settings.unitsus")
onChanged: function(v) { root.writeSetting("units", v === root.tr("settings.unitsmetric") ? "metric" : "us", false) }
}
Dropdown {
visible: root.stations.length > 1
width: parent.width
label: root.tr("settings.station")
foreground: root.foreground
fontFamily: root.fontFamily
options: root.stations.map(function(s) { return s.name })
value: { for (var i = 0; i < root.stations.length; i++) if (root.stations[i].id === root.stationId) return root.stations[i].name; return "" }
onChanged: function(v) { for (var i = 0; i < root.stations.length; i++) if (root.stations[i].name === v) root.writeSetting("stationId", root.stations[i].id, false) }
}
PanelSectionHeader { foreground: root.foreground; fontFamily: root.fontFamily; text: root.tr("settings.data") }
NumberField {
label: root.tr("settings.refresh")
from: 1; to: 60
value: root.refreshMinutes
foreground: root.foreground
fontFamily: root.fontFamily
onModified: function(v) { root.writeSetting("refreshMinutes", v, true) }
}
T { width: parent.width; font.pixelSize: Style.font.bodySmall; color: root.dim; wrapMode: Text.WordWrap; elide: Text.ElideNone
text: root.tr("settings.disclose") }
}
}
}
}
}
}