Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions packages/omamobile-shell/plugins/omamobile.home/BoundedProcess.qml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: MIT
import QtQuick
import Quickshell.Io

// Both widget formats share the same command-output bound. Once a pipe
// reaches 64 KiB, detaching its collector makes QProcess discard further
// output without interrupting the command. Collect raw bytes until then:
// decoding arbitrary SplitParser chunks would corrupt split UTF-8.
Process {
id: proc
property var done: null
property string out: ""
property string err: ""

stdout: StdioCollector {
id: stdoutCollector
waitForEnd: false
onDataChanged: if (data.byteLength >= 65536) { proc.out = proc.prefix(text); proc.stdout = null }
}
stderr: StdioCollector {
id: stderrCollector
waitForEnd: false
onDataChanged: if (data.byteLength >= 65536) { proc.err = proc.prefix(text); proc.stderr = null }
}

// Trim on a character boundary, counting UTF-8 bytes, not UTF-16 units.
function prefix(text) {
let end = 0, remaining = 65536
while (end < text.length) {
const point = text.codePointAt(end)
const bytes = point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4
if (bytes > remaining) break
remaining -= bytes
end += point > 0xffff ? 2 : 1
}
return text.slice(0, end)
}

function stop() {
proc.done = null
// GNU timeout forwards TERM to the command's process group, with its
// existing -k grace period. Keep the Process alive until it exits.
proc.running = false
}
onExited: function(code) {
const finish = proc.done
proc.done = null
if (proc.stdout) proc.out = proc.prefix(stdoutCollector.text)
if (proc.stderr) proc.err = proc.prefix(stderrCollector.text)
if (finish) finish(code, proc.out, proc.err)
proc.destroy()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ Item {
themeColors: owlCell.home ? owlCell.home.owlPalette : ({})
approval: owlCell.card.approval
active: owlCell.running && owlCell.shown && !!owlCell.home && !!owlCell.entry
paused: !owlCell.home || owlCell.home.owlPaused
// While its screen is open, the screen's size is the view's own.
tileVars: Phone.tileVars(owlCell.width, owlCell.height, owlCell.dp,
owl.screenOpen ? view.width : owlCell.home ? owlCell.home.owlScreenWidth : owlCell.width,
Expand Down
60 changes: 31 additions & 29 deletions packages/omamobile-shell/plugins/omamobile.home/OwlPhoneHost.qml
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,12 @@ QtObject {
function runSource(widget, spec, arg, headers, done) {
if (spec.kind === "http") {
if (!host.networkAllowed(widget)) { done({ error: "the internet is off for this widget" }); return }
host.get(arg, headers, Phone.sourceLimits(spec, false).timeout, spec, done)
return
return host.get(arg, headers, Phone.sourceLimits(spec, false).timeout, spec, done)
}
if (spec.kind === "file") { host.readFile(arg, done); return }
if (spec.kind === "cmd") {
if (host.usesNetwork(arg) && !host.networkAllowed(widget)) { done({ error: "the internet is off for this widget" }); return }
host.command(widget, arg, Phone.sourceLimits(spec, false).timeout, done)
return
return host.command(widget, arg, Phone.sourceLimits(spec, false).timeout, done)
}
done({ error: "unknown source " + spec.kind })
}
Expand All @@ -63,35 +61,52 @@ QtObject {
command: ["timeout", "-k", "2", String(Math.max(1, Math.min(Phone.LIMITS.timeoutMax, seconds))), "bash", "-c", String(text)]
})
proc.done = function(code, out, err) {
done({ code: code, ok: code === 0, out: out.slice(0, Phone.LIMITS.cmdOutput), err: err.slice(0, Phone.LIMITS.cmdOutput) })
done({ code: code, ok: code === 0, out: out, err: err })
}
proc.running = true
return { stop: function() { proc.stop() } }
}

function get(url, headers, seconds, spec, done) {
const xhr = new XMLHttpRequest()
let finished = false
const timer = timerComponent.createObject(host, { interval: seconds * 1000 })
timer.triggered.connect(function() {
const stop = function() {
if (finished) return
finished = true
timer.stop()
xhr.abort()
timer.destroy()
}
timer.triggered.connect(function() {
if (finished) return
stop()
done(spec.status ? { code: 124, ok: false, out: "", err: "timed out" } : { error: "timed out" })
})
xhr.onreadystatechange = function() {
if (xhr.readyState !== XMLHttpRequest.DONE || finished) return
if (finished || xhr.readyState < XMLHttpRequest.LOADING) return
// Qt emits LOADING on each received chunk. Check raw bytes there,
// before a chunked or compressed reply can grow without a bound.
if (xhr.response.byteLength > Phone.LIMITS.bodyBytes) {
stop()
done({ error: "the answer is over 1 MB" })
return
}
if (xhr.readyState !== XMLHttpRequest.DONE) return
finished = true
timer.stop()
timer.destroy()
const body = String(xhr.responseText || "")
if (body.length > Phone.LIMITS.bodyBytes) { done({ error: "the answer is over 1 MB" }); return }
const ok = xhr.status >= 200 && xhr.status < 300
done({ code: xhr.status, ok: ok, out: body, err: ok ? "" : "HTTP " + xhr.status })
}
xhr.open("GET", url)
// Qt still supplies responseText for decoding at DONE.
xhr.responseType = "arraybuffer"
for (const name in headers) xhr.setRequestHeader(name, String(headers[name]))
timer.start()
xhr.send()
return { stop: stop }
}

function readFile(path, done) {
Expand Down Expand Up @@ -145,28 +160,26 @@ QtObject {
// and mako's modes, system from /proc and df.
function android(widget, kind, done) {
const fromCommand = function(text, parse) {
host.command(widget, text, 5, function(r) { done({ value: parse(String(r.out || "")) }) })
return host.command(widget, text, 5, function(r) { done({ value: parse(String(r.out || "")) }) })
}
if (kind === "volume") { fromCommand("wpctl get-volume @DEFAULT_AUDIO_SINK@", Phone.volumeFrom); return }
if (kind === "media") { fromCommand("playerctl metadata --format " + JSON.stringify(Phone.MEDIA_FORMAT) + " 2>/dev/null", Phone.mediaFrom); return }
if (kind === "modes") { fromCommand("brightnessctl --device=white:torch get 2>/dev/null || echo; makoctl mode 2>/dev/null", Phone.modesFrom); return }
if (kind === "volume") return fromCommand("wpctl get-volume @DEFAULT_AUDIO_SINK@", Phone.volumeFrom)
if (kind === "media") return fromCommand("playerctl metadata --format " + JSON.stringify(Phone.MEDIA_FORMAT) + " 2>/dev/null", Phone.mediaFrom)
if (kind === "modes") return fromCommand("brightnessctl --device=white:torch get 2>/dev/null || echo; makoctl mode 2>/dev/null", Phone.modesFrom)
if (kind === "system") {
fromCommand("cat /proc/meminfo; echo '@@'; cat /proc/uptime; echo '@@'; uname -r; echo '@@'; df -B1 --output=size,used / | tail -1; echo '@@@'; " + Phone.DEVICE_COMMAND, function(t) {
return fromCommand("cat /proc/meminfo; echo '@@'; cat /proc/uptime; echo '@@'; uname -r; echo '@@'; df -B1 --output=size,used / | tail -1; echo '@@@'; " + Phone.DEVICE_COMMAND, function(t) {
const halves = t.split("@@@\n")
const parts = halves[0].split("@@\n")
return Phone.systemFrom(parts[0], parts[1], parts[2], parts[3], Phone.boardFrom(halves[1]))
})
return
}
if (kind === "battery") { fromCommand(Phone.BATTERY_COMMAND, Phone.batteryFrom); return }
if (kind === "battery") return fromCommand(Phone.BATTERY_COMMAND, Phone.batteryFrom)
if (kind === "alarm") { done({ value: { set: false, time: null, app: null } }); return }
if (kind === "notifications") { done({ value: { available: false, count: 0, items: [] } }); return }
if (kind === "device") {
fromCommand(Phone.DEVICE_COMMAND, function(t) {
return fromCommand(Phone.DEVICE_COMMAND, function(t) {
const b = Phone.boardFrom(t)
return { model: b.model, maker: b.maker, android: null, sdk: null, soc: b.soc }
})
return
}
done({ value: null })
}
Expand Down Expand Up @@ -274,18 +287,7 @@ QtObject {
// ---------------------------------------------------------------- parts

property Component processComponent: Component {
Process {
id: proc
property var done: null
stdout: StdioCollector { id: out; waitForEnd: true }
stderr: StdioCollector { id: err; waitForEnd: true }
onExited: function(code) {
const finish = proc.done
proc.done = null
if (finish) finish(code, String(out.text || ""), String(err.text || ""))
proc.destroy()
}
}
BoundedProcess { }
}

property Component timerComponent: Component { Timer { } }
Expand Down
20 changes: 4 additions & 16 deletions packages/omamobile-shell/plugins/omamobile.home/WidgetHost.qml
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,10 @@ QtObject {
var seconds = UserWidgets.runTimeout(options)
lastStart = Date.now()
var proc = processComponent.createObject(host, { command: UserWidgets.timeoutArgv(argv, seconds) })
proc.done = function(result) {
proc.done = function(code, out, err) {
host.running = null
if (typeof callback === "function") {
try { callback(result) } catch (e) { console.warn("omamobile.home: widget " + host.widgetId + ": " + e) }
try { callback(UserWidgets.runResult(code, out, err)) } catch (e) { console.warn("omamobile.home: widget " + host.widgetId + ": " + e) }
}
}
running = proc
Expand Down Expand Up @@ -102,23 +102,11 @@ QtObject {
}

property Component processComponent: Component {
Process {
id: proc
property var done: null
stdout: StdioCollector { id: out; waitForEnd: true }
stderr: StdioCollector { id: err; waitForEnd: true }
onExited: function(code) {
var result = UserWidgets.runResult(code, out.text, err.text)
var finish = proc.done
proc.done = null
if (finish) finish(result)
proc.destroy()
}
}
BoundedProcess { }
}

// A widget that goes away takes its command with it.
Component.onDestruction: {
if (running) { running.done = null; running.running = false }
if (running) running.stop()
}
}
70 changes: 54 additions & 16 deletions packages/omamobile-shell/plugins/omamobile.home/owl/OwlWidget.qml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ Item {
// seen: its page shows (a neighbour too while the pages move) and nothing
// covers the home screen. The host sets it.
property bool active: false
// Global pause wins even over an expanded widget screen.
property bool paused: false
// State to start with when nothing is saved yet: { name: value }.
property var seedState: ({})
// The approval this widget runs under ({ commands, network }), for the host.
Expand All @@ -56,6 +58,8 @@ Item {
Component.onCompleted: Qt.callLater(widget.load)

function load() {
widget.saveNow()
widget.stopSources()
widget.stopLive()
widget.screenOpen = false
widget.screenTree = null
Expand All @@ -74,9 +78,12 @@ Item {
return
}
const saved = Object.assign({}, widget.seedState || {}, widget.host && widget.stateKey ? widget.host.loadState(widget.stateKey) || {} : {})
widget.instance = new Runtime.Instance(widget.program, widget.bridge, saved)
const next = new Runtime.Instance(widget.program, widget.bridge, saved)
widget.lastSaved = JSON.stringify(next.persisted())
// Publishing the instance lets OwlCell seed location/state immediately.
widget.instance = next
widget.render()
if (widget.active) { widget.refresh(); widget.startLive() }
if (widget.live) { widget.refresh(); widget.startLive() }
}

// What the instance calls back into.
Expand All @@ -88,7 +95,8 @@ Item {
tile: function(name) { return widget.tileVars ? widget.tileVars[name] : null },
act: function(name, args) { widget.act(name, args) },
runInto: function(command, slot) {
if (widget.host) widget.host.runInto(widget, command, function(out) { if (widget.instance) widget.instance.setState(slot, out) })
const owner = widget.instance
if (widget.host) widget.host.runInto(widget, command, function(out) { if (owner && widget.instance === owner) owner.setState(slot, out) })
},
report: function(message) { widget.report(message) },
changed: function() { widget.changed() },
Expand All @@ -98,15 +106,15 @@ Item {
onThemeColorsChanged: if (widget.instance) { widget.instance.invalidate(); widget.render() }
onTileVarsChanged: if (widget.instance) { widget.instance.invalidate(); widget.render() }
// Sources keep running while the screen is open, whatever page shows.
readonly property bool live: widget.active || widget.screenOpen
readonly property bool live: !widget.paused && (widget.active || widget.screenOpen)
// Shown again, it catches up once: what fell due while it was hidden runs
// now (a source whose period turned over, an `every` that passed), and
// nothing else; the frame clock picks up at the current `time`.
onLiveChanged: {
if (widget.live) { widget.catchUp(); widget.startLive() }
else widget.stopLive()
else { widget.stopSources(); widget.stopLive() }
}
Component.onDestruction: { widget.stopLive(); widget.saveNow() }
Component.onDestruction: { widget.stopSources(); widget.stopLive(); widget.saveNow(); widget.instance = null }

// ---------------------------------------------------------------- drawing

Expand Down Expand Up @@ -220,10 +228,13 @@ Item {
return
}
if (!widget.host || widget.running[s.slot]) return
widget.running[s.slot] = true
const owner = widget.instance
const pending = { stop: null }
widget.running[s.slot] = pending
const finish = function(result) {
widget.running[s.slot] = false
if (!widget.instance || !result) return
if (widget.instance !== owner || widget.running[s.slot] !== pending) return
delete widget.running[s.slot]
if (!result) return
if (result.error) { widget.report(s.name + ": " + result.error); return }
if (result.value !== undefined) { widget.instance.setSource(s.slot, V.fromPlain(result.value)); return }
if (s.status) {
Expand All @@ -237,8 +248,19 @@ Item {
if (!result.ok && result.err) widget.report(s.name + ": " + String(result.err).split("\n")[0])
widget.instance.setSource(s.slot, String(result.out === undefined ? "" : result.out))
}
if (s.kind.indexOf("android.") === 0) widget.host.android(widget, s.kind.slice(8), finish)
else widget.host.runSource(widget, s, s.arg(), s.headers(), finish)
const handle = s.kind.indexOf("android.") === 0 ? widget.host.android(widget, s.kind.slice(8), finish)
: widget.host.runSource(widget, s, s.arg(), s.headers(), finish)
if (handle) pending.stop = handle.stop
}

function stopSources() {
const pending = widget.running
widget.running = ({})
for (const slot in pending) {
// A cancelled read has no value: try again when shown.
delete widget.lastRun[slot]
if (pending[slot].stop) pending[slot].stop()
}
}

// A state's value by name (undefined: no such state), and setting one as
Expand All @@ -259,22 +281,28 @@ Item {
// `stream(...)` (a line is a value) and `file(...)` (read again when it
// changes): started while the widget shows, stopped when it doesn't.
property var liveHandles: []
property int liveGeneration: 0
function startLive() {
if (!widget.instance || !widget.host || widget.liveHandles.length) return
if (!widget.live || !widget.instance || !widget.host || widget.liveHandles.length) return
const owner = widget.instance
const generation = ++widget.liveGeneration
const specs = widget.instance.sources()
const handles = []
for (let i = 0; i < specs.length; i++) {
const s = specs[i]
if (s.kind !== "stream" && s.kind !== "file") continue
const slot = s.slot
const onValue = function(text) { if (widget.instance) widget.instance.setSource(slot, String(text)) }
const onValue = function(text) {
if (widget.instance === owner && widget.liveGeneration === generation) owner.setSource(slot, String(text))
}
const h = s.kind === "stream" ? widget.host.stream(widget, s, s.arg(), onValue)
: widget.host.watch(widget, s, s.arg(), onValue)
if (h) handles.push(h)
}
widget.liveHandles = handles
}
function stopLive() {
widget.liveGeneration++
const handles = widget.liveHandles
widget.liveHandles = []
for (let i = 0; i < handles.length; i++) handles[i].stop()
Expand All @@ -291,13 +319,23 @@ Item {

// ---------------------------------------------------------------- persisted state

function saveSoon() { if (widget.stateKey) saveTimer.restart() }
property string lastSaved: ""
function saveSoon() {
if (widget.instance && widget.stateKey && !saveTimer.running
&& JSON.stringify(widget.instance.persisted()) !== widget.lastSaved) saveTimer.start()
}
Timer {
id: saveTimer
interval: 1000
onTriggered: if (widget.instance && widget.host && widget.stateKey) widget.host.saveState(widget.stateKey, widget.instance.persisted())
onTriggered: widget.saveNow()
}
function saveNow() {
if (widget.instance && widget.host && widget.stateKey && saveTimer.running) widget.host.saveState(widget.stateKey, widget.instance.persisted())
saveTimer.stop()
if (!widget.instance || !widget.host || !widget.stateKey) return
const data = widget.instance.persisted()
const json = JSON.stringify(data)
if (json === widget.lastSaved) return
widget.host.saveState(widget.stateKey, data)
widget.lastSaved = json
}
}
Loading