Fill native stat and list widgets from your Despia V3 web app and read their taps.
Source: Home Widgets repository. Read its LICENSE before using or modifying the extension.This extension puts data from your web app into native home-screen widgets. It includes a stat card and a list with buttons and checkboxes. The page sets and reads the widget data, reloads the extension’s widgets, lists installed widgets and reads queued taps.It is for the Despia V3 runtime. You own and maintain the copied native code. First-party V4 support comes through the new package registry. Read V3 Extensions for build verification and rebuild requirements.
Install
Copy the files below into public/despia/widgets/ in your web app, keeping their ios/ and android/ paths.
Add "widgets" to the extensions array in public/despia/extensions.json, keeping your app identity and any other extension names.
For iOS, register the App Group group.<your bundle id>.nx.widgets and enable it on both the app and the widget extension App IDs. The widget extension bundle ID is <your bundle id>.NXWidgets. Regenerate both provisioning profiles.
Rebuild and install your native app with the extension compiled in. Changing native files requires fresh build verification and a new build.
The manifest adds the NXWidgets WidgetKit target on iOS and a custom Glance module on Android. The build policy stays with the trusted build inputs, outside your served public/despia/ folder. The Android module declares the widget receivers and its RemoteViews service.
Call it from your web app
Install the SDK with npm install despia-native. Import despia from despia-native and watch the route’s declared output variable. Call these functions from client events.
import despia from 'despia-native';async function updateWidget() { const widget = { title: "Today's orders", value: '12', caption: 'Ready to dispatch', progress: 0.6, link: '/orders' }; const reply = await despia('extension://widgets/set?template=stat&data=' + encodeURIComponent(JSON.stringify(widget)), ['widgetsSet']); const answer = reply.widgetsSet; if (answer === undefined) { console.error('No native reply within 30 seconds'); return; } if (!answer.ok) { console.error(answer.code, answer.error); return; } console.log(answer.data.template, answer.data.stored);}async function readWidget() { const widgetReply = await despia('extension://widgets/get?template=stat', ['widgetsGet']); const widget = widgetReply.widgetsGet; if (widget === undefined) { console.error('No native reply within 30 seconds'); return; } if (!widget.ok) { console.error(widget.code, widget.error); return; } const queuedReply = await despia('extension://widgets/taps', ['widgetsTaps']); const queued = queuedReply.widgetsTaps; if (queued === undefined) { console.error('No native reply within 30 seconds'); return; } if (!queued.ok) { console.error(queued.code, queued.error); return; } console.log(widget.data.data, queued.data.taps);}
For live taps, register the declared onWidgetTap callback with browser lifecycle cleanup as described in Calling a route. Read taps after loading the page to recover queued taps.Setting data does not place a widget on the screen. The person adds it from the widget gallery, or accepts an Android pin request.
Routes and answers
Each success answer uses {ok: true, data: ...}. Failures use {ok: false, code, error}. The table lists the fields inside data.
Route
Parameters
Answer variable and callback
Answer
set
Required: template (stat or list), data (JSON text)
widgetsSet, onWidgetsSet
template, stored: true
get
Required: template
widgetsGet, onWidgetsGet
template, data (canonical object, or null when empty)
clear
Required: template
widgetsClear, onWidgetsClear
template, cleared: true
reload
Optional: template
widgetsReload, onWidgetsReload
reloaded, an array of template names
installed
None
widgetsInstalled, onWidgetsInstalled
widgets, an array of placed widgets
taps
Optional: ack (integer from 0 to 9007199254740991)
widgetsTaps, onWidgetsTaps
taps, dropped, next
pin
Required: template
widgetsPin, onWidgetsPin
Android: requested: true if the request was shown. iOS: platform_limit
reload touches only this extension’s widget kinds. For installed, each iOS row contains template and family; each Android row contains template, width and height in dp.
Widget data
The JSON text must fit in 4096 UTF-8 bytes. Unknown keys, duplicate keys and invalid types return bad_data with the field path and reason.
Template
Required fields
Optional fields
stat
title (1 to 40 characters), value (1 to 16 characters)
unit (1 to 12), caption (1 to 60), progress (0 to 1), trend (up, down, flat), tint, link, actions (up to 2 buttons)
list
title (1 to 40 characters), items (up to 8)
empty (1 to 60), tint, link, action (one button)
Each list item requires id and title (1 to 60 characters). It may have subtitle (1 to 60), checked (boolean) and link. Each button requires id and label (1 to 20). IDs contain 1 to 32 lowercase letters, digits, underscores or hyphens. IDs must be unique within their list or button array. tint is #RRGGBB. A link is an app path starting with one /, with no backslash or spaces, up to 512 characters.
Taps
onWidgetTap receives {seq, template, kind, id, at}, plus link for an open and checked for a toggle. kind is open, action or toggle. Its event scope is the document: pages that have called this extension receive it.Taps are stored before they are emitted. Call taps after a page loads, then pass the last consumed seq as ack on the next read to remove acknowledged taps. The queue keeps the newest 32 taps and counts older discarded taps in dropped.
Errors
Besides the standard bridge errors, the extension can return bad_data or storage_failed. On iOS, missing App Group access returns group_unavailable for the storage routes. Android pin can return pin_unavailable when the launcher does not support pinning. iOS pin returns platform_limit.
Platform limits
The iOS widget extension requires iOS 17. The user places widgets through the widget gallery; iOS has no app API for placing one. App Group access is required to share the widget data and taps.
Android pinning needs Android 8 or later and a launcher that supports it. requested: true confirms the request was shown, not that a widget was placed. Check installed afterwards.
Widget size, placement and update timing are controlled by the OS and launcher. The extension requests updates of its own widget kinds only.
Android widget taps may fail to open a link when the app is already running.
The extension skill includes a reference for this extension.
Files
Copy each file to its title’s path. The extensions.json block is an example for a new app; merge the extension name into your existing file rather than replacing its app identity.
import Foundationimport WidgetKit/// Home-screen and Lock Screen widgets the page fills: the routes that set, read and clear each/// template's data and reload its timelines, and the widget taps as the `tap` event.////// Where taps come from:/// - a deep link (widgetURL or Link in the widget) opens the app with nxwidgets://tap?...; iOS hands it/// to `openURL` (the scheme is claimed in manifest.json);/// - a button or check box runs an App Intent inside the widget extension, which queues the tap in the/// App Group and posts a Darwin notification; the running app drains the queue./// Every tap is queued first and then emitted, so a page that loads later still reads it with `taps`.////// Only this sample's own kinds are reloaded, never all timelines: the app's built-in image widget/// and the Live Activity widget keep their own reload budget.////// Main actor, as NativeExtension requires.@MainActorfinal class WidgetsExtension: NativeExtension { /// The instance the Darwin notification callback reaches (a C callback cannot capture). static weak var active: WidgetsExtension? private var ctx: NativeExtContext! private var lastEmitted = 0 required init() {} func didLaunch(_ context: NativeExtContext) { ctx = context WidgetsExtension.active = self // Taps queued before this launch are read by the page with `taps`; events cover what follows. lastEmitted = WidgetShared.taps().taps.last?.seq ?? 0 let callback: CFNotificationCallback = { _, _, _, _, _ in Task { @MainActor in WidgetsExtension.active?.drain() } } CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), nil, callback, WidgetShared.tapNotification as CFString, nil, .deliverImmediately) } func sceneDidChange(_ phase: NativeExtScenePhase) { // A Darwin notification is not delivered while the app is suspended: catch up on return. if phase == .didBecomeActive { drain() } } func openURL(_ url: URL) -> Bool { // Ours by scheme. A link that does not parse is dropped here, so no other code reads it. guard let tap = WidgetLink.parse(url.absoluteString) else { ctx?.log("dropped a widget link that does not parse") return true } if WidgetShared.record(tap) != nil { drain() } return true } /// Emits every queued tap newer than the last one emitted. func drain() { guard let ctx = ctx else { return } for t in WidgetShared.taps().taps where t.seq > lastEmitted { ctx.emit("tap", t.dictionary) lastEmitted = t.seq } } func handle(_ call: NativeExtCall) async -> NativeExtResult { let template = (call.params["template"] as? String).flatMap(WidgetTemplate.init(rawValue:)) switch call.route { case "set": return set(template, call.params["data"] as? String ?? "") case "get": return get(template) case "clear": return clear(template) case "reload": return reload(template) case "installed": return await installed(call) case "taps": // A typed int (0 to 2^53-1), checked by the bridge; absent means acknowledge nothing. return taps(call.params["ack"] as? Int ?? 0) case "pin": // Apple offers no API that adds a widget for the user; they add it from the Home Screen // or Lock Screen widget gallery, where both templates are listed. return .error(code: "platform_limit", message: "iOS has no API to add a widget; add it from the widget gallery") default: return .error(code: "not_registered", message: call.route) } } private func set(_ t: WidgetTemplate?, _ text: String) -> NativeExtResult { guard let t = t else { return .error(code: "bad_request", message: "template") } let data: WidgetData do { data = try WidgetValidator.validate(template: t.rawValue, text: text) } catch let e as WidgetDataError { return .error(code: "bad_data", message: e.message) } catch { return .error(code: "bad_data", message: "$: bad json") } guard WidgetShared.directory() != nil else { return groupUnavailable() } guard WidgetShared.store(t, data) else { return .error(code: "storage_failed", message: "the widget data was not saved") } WidgetCenter.shared.reloadTimelines(ofKind: t.kind) return .ok(["template": t.rawValue, "stored": true]) } private func get(_ t: WidgetTemplate?) -> NativeExtResult { guard let t = t else { return .error(code: "bad_request", message: "template") } guard WidgetShared.directory() != nil else { return groupUnavailable() } guard let d = WidgetShared.load(t), let obj = try? JSONSerialization.jsonObject(with: Data(WidgetValidator.canonical(d).utf8)) else { return .ok(["template": t.rawValue, "data": NSNull()]) } return .ok(["template": t.rawValue, "data": obj]) } private func clear(_ t: WidgetTemplate?) -> NativeExtResult { guard let t = t else { return .error(code: "bad_request", message: "template") } guard WidgetShared.directory() != nil else { return groupUnavailable() } guard WidgetShared.store(t, nil) else { return .error(code: "storage_failed", message: "the widget data was not removed") } WidgetCenter.shared.reloadTimelines(ofKind: t.kind) return .ok(["template": t.rawValue, "cleared": true]) } private func reload(_ t: WidgetTemplate?) -> NativeExtResult { let kinds = t.map { [$0] } ?? WidgetTemplate.allCases for k in kinds { WidgetCenter.shared.reloadTimelines(ofKind: k.kind) } return .ok(["reloaded": kinds.map(\.rawValue)]) } private func installed(_ call: NativeExtCall) async -> NativeExtResult { let configs: [WidgetInfo]? = await withCheckedContinuation { cont in WidgetCenter.shared.getCurrentConfigurations { result in cont.resume(returning: try? result.get()) } } guard call.isActive else { return .error(code: "timeout", message: "installed timed out") } guard let configs = configs else { return .error(code: "unavailable", message: "WidgetKit did not list the widgets") } let ours = configs.compactMap { info -> [String: Any]? in guard let t = WidgetTemplate.allCases.first(where: { $0.kind == info.kind }) else { return nil } return ["template": t.rawValue, "family": Self.familyName(info.family)] } return .ok(["widgets": ours]) } private func taps(_ ack: Int) -> NativeExtResult { guard WidgetShared.directory() != nil else { return groupUnavailable() } guard let q = ack > 0 ? WidgetShared.ack(ack) : WidgetShared.taps() else { return .error(code: "storage_failed", message: "the tap queue was not updated") } return .ok(["taps": q.taps.map(\.dictionary), "dropped": q.dropped, "next": q.next]) } private func groupUnavailable() -> NativeExtResult { .error(code: "group_unavailable", message: "the App Group is missing: add it to the app and to the NXWidgets extension in the developer portal") } static func familyName(_ f: WidgetFamily) -> String { switch f { case .systemSmall: return "systemSmall" case .systemMedium: return "systemMedium" case .systemLarge: return "systemLarge" case .systemExtraLarge: return "systemExtraLarge" case .accessoryCircular: return "accessoryCircular" case .accessoryRectangular: return "accessoryRectangular" case .accessoryInline: return "accessoryInline" default: return "other" } }}
import Foundation// Shared by the app (the extension's routes) and the NXWidgets widget extension. Compiled into both,// so it uses nothing newer than the app's own deployment target.//// What it holds:// - the two templates a page fills (stat, list), their typed data and the one validator for it;// - a strict JSON reader and the canonical writer (the same text on iOS and Android);// - the widget deep link (built by the widget, read again by the app as untrusted input);// - the tap queue and the App Group storage both processes share.//// Customise here: the deep-link scheme (also in manifest.json, claims.url_schemes), the limits, and// new fields of a template (add them to the reader, the writer and the widget view together).enum WidgetTemplate: String, CaseIterable { case stat, list /// The WidgetKit kind of the template's widget; `reload` uses it. var kind: String { self == .stat ? "NXStatWidget" : "NXListWidget" }}// MARK: - JSON/// A parsed JSON value. Numbers are Doubles.indirect enum WJSON: Equatable { case object([String: WJSON], [String]) // values, and keys in document order case array([WJSON]) case string(String) case number(Double) case bool(Bool) case null}struct WidgetDataError: Error, Equatable { let path: String let reason: String var message: String { "\(path): \(reason)" }}enum WidgetLimits { static let maxBytes = 4096 static let maxDepth = 8 static let queueCap = 32 static let maxLink = 512}/// RFC 8259 reader over Unicode scalars. Refuses duplicate keys, lone surrogates, raw control/// characters in strings, nesting deeper than eight containers and trailing text.struct WidgetJSONReader { private let s: [Unicode.Scalar] private var i = 0 private static let bad = WidgetDataError(path: "$", reason: "bad json") init(_ text: String) { s = Array(text.unicodeScalars) } static func parse(_ text: String) throws -> WJSON { var r = WidgetJSONReader(text) let v = try r.value(depth: 1) r.skipSpace() if r.i != r.s.count { throw bad } return v } private func peek() -> Unicode.Scalar? { i < s.count ? s[i] : nil } private mutating func skipSpace() { while let c = peek(), c == " " || c == "\t" || c == "\n" || c == "\r" { i += 1 } } private mutating func literal(_ word: String) -> Bool { let w = Array(word.unicodeScalars) guard i + w.count <= s.count, Array(s[i..<(i + w.count)]) == w else { return false } i += w.count return true } private mutating func value(depth: Int) throws -> WJSON { skipSpace() guard let c = peek() else { throw Self.bad } if (c == "{" || c == "[") && depth > WidgetLimits.maxDepth { throw Self.bad } switch c { case "{": i += 1 var out: [String: WJSON] = [:] var order: [String] = [] skipSpace() if peek() == "}" { i += 1; return .object(out, order) } while true { skipSpace() guard peek() == "\"" else { throw Self.bad } let k = try string() skipSpace() guard peek() == ":" else { throw Self.bad } i += 1 let v = try value(depth: depth + 1) if out[k] != nil { throw Self.bad } out[k] = v order.append(k) skipSpace() let e = peek() i += 1 if e == "}" { return .object(out, order) } if e != "," { throw Self.bad } } case "[": i += 1 var out: [WJSON] = [] skipSpace() if peek() == "]" { i += 1; return .array(out) } while true { out.append(try value(depth: depth + 1)) skipSpace() let e = peek() i += 1 if e == "]" { return .array(out) } if e != "," { throw Self.bad } } case "\"": return .string(try string()) default: if literal("true") { return .bool(true) } if literal("false") { return .bool(false) } if literal("null") { return .null } return .number(try number()) } } private func isDigit(_ c: Unicode.Scalar?) -> Bool { guard let c = c else { return false } return c >= "0" && c <= "9" } private mutating func number() throws -> Double { let start = i if peek() == "-" { i += 1 } if peek() == "0" { i += 1 } else if isDigit(peek()) { while isDigit(peek()) { i += 1 } } else { throw Self.bad } if peek() == "." { i += 1 guard isDigit(peek()) else { throw Self.bad } while isDigit(peek()) { i += 1 } } if peek() == "e" || peek() == "E" { i += 1 if peek() == "+" || peek() == "-" { i += 1 } guard isDigit(peek()) else { throw Self.bad } while isDigit(peek()) { i += 1 } } var text = "" text.unicodeScalars.append(contentsOf: s[start..<i]) // Double("1e999") is +inf; the schema then answers "out of range". guard let d = Double(text) else { throw Self.bad } return d } private mutating func hex4() throws -> UInt32 { guard i + 4 <= s.count else { throw Self.bad } var v: UInt32 = 0 for _ in 0..<4 { let c = s[i] let d: UInt32 switch c { case "0"..."9": d = c.value - 48 case "a"..."f": d = c.value - 87 case "A"..."F": d = c.value - 55 default: throw Self.bad } v = v * 16 + d i += 1 } return v } private mutating func string() throws -> String { i += 1 var out = String.UnicodeScalarView() while true { guard let c = peek(), c.value >= 0x20 else { throw Self.bad } i += 1 if c == "\"" { return String(out) } if c != "\\" { out.append(c); continue } guard let e = peek() else { throw Self.bad } i += 1 switch e { case "\"": out.append("\"") case "\\": out.append("\\") case "/": out.append("/") case "b": out.append(Unicode.Scalar(0x08)) case "f": out.append(Unicode.Scalar(0x0C)) case "n": out.append("\n") case "r": out.append("\r") case "t": out.append("\t") case "u": var u = try hex4() if (0xD800...0xDBFF).contains(u) { guard i + 2 <= s.count, s[i] == "\\", s[i + 1] == "u" else { throw Self.bad } i += 2 let lo = try hex4() guard (0xDC00...0xDFFF).contains(lo) else { throw Self.bad } u = 0x10000 + ((u - 0xD800) << 10) + (lo - 0xDC00) } else if (0xDC00...0xDFFF).contains(u) { throw Self.bad } guard let scalar = Unicode.Scalar(u) else { throw Self.bad } out.append(scalar) default: throw Self.bad } } }}/// The canonical text: keys sorted, no whitespace, minimal escapes, progress to four places.enum WidgetJSONWriter { static func write(_ v: WJSON) -> String { switch v { case .object(let o, _): return "{" + o.keys.sorted().map { escape($0) + ":" + write(o[$0]!) }.joined(separator: ",") + "}" case .array(let a): return "[" + a.map(write).joined(separator: ",") + "]" case .string(let s): return escape(s) case .number(let d): return progressText(d) case .bool(let b): return b ? "true" : "false" case .null: return "null" } } static func progressText(_ d: Double) -> String { let n = Int((d * 10000 + 0.5).rounded(.down)) if n >= 10000 { return "1" } if n <= 0 { return "0" } var t = String(n) while t.count < 4 { t = "0" + t } while t.hasSuffix("0") { t.removeLast() } return "0." + t } static func escape(_ s: String) -> String { var out = "\"" for c in s.unicodeScalars { switch c { case "\"": out += "\\\"" case "\\": out += "\\\\" default: if c.value < 0x20 { let h = String(c.value, radix: 16) out += "\\u" + String(repeating: "0", count: 4 - h.count) + h } else { out.unicodeScalars.append(c) } } } return out + "\"" }}// MARK: - Typed template datastruct WidgetButton: Equatable { var id: String var label: String}struct StatData: Equatable { var title: String var value: String var unit: String? var caption: String? var progress: Double? var trend: String? var tint: String? var link: String? var actions: [WidgetButton]?}struct ListItem: Equatable { var id: String var title: String var subtitle: String? var checked: Bool? var link: String?}struct ListData: Equatable { var title: String var items: [ListItem] var empty: String? var tint: String? var link: String? var action: WidgetButton?}enum WidgetData: Equatable { case stat(StatData) case list(ListData)}/// The one validator. The first error in a fixed order is reported: an object's unknown keys first/// (the smallest), then its declared fields in declared order; arrays item by item.enum WidgetValidator { static let statKeys = ["title", "value", "unit", "caption", "progress", "trend", "tint", "link", "actions"] static let listKeys = ["title", "items", "empty", "tint", "link", "action"] static let itemKeys = ["id", "title", "subtitle", "checked", "link"] static func validate(template: String, text: String) throws -> WidgetData { guard let t = WidgetTemplate(rawValue: template) else { throw WidgetDataError(path: "$", reason: "bad template") } if text.utf8.count > WidgetLimits.maxBytes { throw WidgetDataError(path: "$", reason: "too large") } let v = try WidgetJSONReader.parse(text) return t == .stat ? .stat(try stat(v)) : .list(try list(v)) } /// Canonical text of validated data. static func canonical(_ d: WidgetData) -> String { WidgetJSONWriter.write(json(d)) } static func join(_ path: String, _ key: String) -> String { path == "$" ? key : "\(path).\(key)" } static func object(_ v: WJSON, _ path: String, _ allowed: [String]) throws -> [String: WJSON] { guard case .object(let o, _) = v else { throw WidgetDataError(path: path, reason: "not an object") } if let k = o.keys.filter({ !allowed.contains($0) }).sorted().first { throw WidgetDataError(path: join(path, k), reason: "unknown key") } return o } static func text(_ o: [String: WJSON], _ key: String, _ path: String, _ lo: Int, _ hi: Int, required: Bool) throws -> String? { guard let v = o[key] else { if required { throw WidgetDataError(path: path, reason: "missing") } return nil } guard case .string(let s) = v else { throw WidgetDataError(path: path, reason: "not a string") } if s.unicodeScalars.contains(where: { $0.value < 0x20 || $0.value == 0x7F }) { throw WidgetDataError(path: path, reason: "control character") } let n = s.unicodeScalars.count if n < lo { throw WidgetDataError(path: path, reason: "empty") } if n > hi { throw WidgetDataError(path: path, reason: "too long") } return s } static func isID(_ s: String) -> Bool { let n = s.unicodeScalars.count return n >= 1 && n <= 32 && s.unicodeScalars.allSatisfy { ($0 >= "a" && $0 <= "z") || ($0 >= "0" && $0 <= "9") || $0 == "_" || $0 == "-" } } static func id(_ o: [String: WJSON], _ key: String, _ path: String) throws -> String { let s = try text(o, key, path, 1, 32, required: true)! if !isID(s) { throw WidgetDataError(path: path, reason: "bad id") } return s } /// A path inside the page's own app: starts with one "/", printable ASCII, no backslash. static func isLink(_ s: String) -> Bool { let u = Array(s.unicodeScalars) guard u.count >= 1, u.count <= WidgetLimits.maxLink, u[0] == "/" else { return false } if u.count > 1 && u[1] == "/" { return false } return u.allSatisfy { $0.value >= 0x21 && $0.value <= 0x7E && $0 != "\\" } } static func link(_ o: [String: WJSON], _ key: String, _ path: String) throws -> String? { guard let s = try text(o, key, path, 1, WidgetLimits.maxLink, required: false) else { return nil } if !isLink(s) { throw WidgetDataError(path: path, reason: "bad link") } return s } static func color(_ o: [String: WJSON], _ key: String, _ path: String) throws -> String? { guard let s = try text(o, key, path, 1, 7, required: false) else { return nil } let u = Array(s.unicodeScalars) let ok = u.count == 7 && u[0] == "#" && u[1...].allSatisfy { ($0 >= "0" && $0 <= "9") || ($0 >= "a" && $0 <= "f") || ($0 >= "A" && $0 <= "F") } if !ok { throw WidgetDataError(path: path, reason: "bad color") } return s } static func array(_ o: [String: WJSON], _ key: String, _ path: String, _ hi: Int, required: Bool) throws -> [WJSON]? { guard let v = o[key] else { if required { throw WidgetDataError(path: path, reason: "missing") } return nil } guard case .array(let a) = v else { throw WidgetDataError(path: path, reason: "not an array") } if a.count > hi { throw WidgetDataError(path: path, reason: "too many") } return a } static func button(_ v: WJSON, _ path: String) throws -> WidgetButton { let o = try object(v, path, ["id", "label"]) return WidgetButton(id: try id(o, "id", join(path, "id")), label: try text(o, "label", join(path, "label"), 1, 20, required: true)!) } static func stat(_ v: WJSON) throws -> StatData { let o = try object(v, "$", statKeys) var d = StatData(title: try text(o, "title", "title", 1, 40, required: true)!, value: try text(o, "value", "value", 1, 16, required: true)!) d.unit = try text(o, "unit", "unit", 1, 12, required: false) d.caption = try text(o, "caption", "caption", 1, 60, required: false) if let p = o["progress"] { guard case .number(let n) = p else { throw WidgetDataError(path: "progress", reason: "not a number") } guard n >= 0 && n <= 1 else { throw WidgetDataError(path: "progress", reason: "out of range") } d.progress = n } if o["trend"] != nil { let t = try text(o, "trend", "trend", 1, 16, required: true)! guard ["up", "down", "flat"].contains(t) else { throw WidgetDataError(path: "trend", reason: "bad value") } d.trend = t } d.tint = try color(o, "tint", "tint") d.link = try link(o, "link", "link") if let acts = try array(o, "actions", "actions", 2, required: false) { var seen = Set<String>() d.actions = [] for (i, a) in acts.enumerated() { let b = try button(a, "actions[\(i)]") if seen.contains(b.id) { throw WidgetDataError(path: "actions[\(i)].id", reason: "duplicate id") } seen.insert(b.id) d.actions?.append(b) } } return d } static func list(_ v: WJSON) throws -> ListData { let o = try object(v, "$", listKeys) let title = try text(o, "title", "title", 1, 40, required: true)! let raw = try array(o, "items", "items", 8, required: true)! var seen = Set<String>() var items: [ListItem] = [] for (i, x) in raw.enumerated() { let p = "items[\(i)]" let it = try object(x, p, itemKeys) var item = ListItem(id: try id(it, "id", "\(p).id"), title: try text(it, "title", "\(p).title", 1, 60, required: true)!) if seen.contains(item.id) { throw WidgetDataError(path: "\(p).id", reason: "duplicate id") } seen.insert(item.id) item.subtitle = try text(it, "subtitle", "\(p).subtitle", 1, 60, required: false) if let c = it["checked"] { guard case .bool(let b) = c else { throw WidgetDataError(path: "\(p).checked", reason: "not a bool") } item.checked = b } item.link = try link(it, "link", "\(p).link") items.append(item) } var d = ListData(title: title, items: items) d.empty = try text(o, "empty", "empty", 1, 60, required: false) d.tint = try color(o, "tint", "tint") d.link = try link(o, "link", "link") if let a = o["action"] { d.action = try button(a, "action") } return d } // Typed data back to JSON (for the canonical text and `get`). static func json(_ d: WidgetData) -> WJSON { func obj(_ pairs: [(String, WJSON?)]) -> WJSON { var o: [String: WJSON] = [:] for (k, v) in pairs { if let v = v { o[k] = v } } return .object(o, o.keys.sorted()) } func btn(_ b: WidgetButton) -> WJSON { obj([("id", .string(b.id)), ("label", .string(b.label))]) } func str(_ s: String?) -> WJSON? { s.map { .string($0) } } switch d { case .stat(let s): return obj([("title", .string(s.title)), ("value", .string(s.value)), ("unit", str(s.unit)), ("caption", str(s.caption)), ("progress", s.progress.map { .number($0) }), ("trend", str(s.trend)), ("tint", str(s.tint)), ("link", str(s.link)), ("actions", s.actions.map { .array($0.map(btn)) })]) case .list(let l): let items: [WJSON] = l.items.map { obj([("id", .string($0.id)), ("title", .string($0.title)), ("subtitle", str($0.subtitle)), ("checked", $0.checked.map { .bool($0) }), ("link", str($0.link))]) } return obj([("title", .string(l.title)), ("items", .array(items)), ("empty", str(l.empty)), ("tint", str(l.tint)), ("link", str(l.link)), ("action", l.action.map(btn))]) } } /// List data with one item's checked state set; nil when the item is unknown or not checkable. static func toggle(_ l: ListData, item: String, checked: Bool) -> ListData? { guard let i = l.items.firstIndex(where: { $0.id == item }), l.items[i].checked != nil else { return nil } var out = l out.items[i].checked = checked return out }}// MARK: - Deep link/// The URL a widget opens. The scheme is the one manifest.json claims (claims.url_schemes); rename it/// in both places. Any app can open a custom scheme, so the app reads every part again.enum WidgetLink { static let scheme = "nxwidgets" private static let unreserved = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~/".unicodeScalars) static func encode(_ s: String) -> String { var out = "" for b in s.utf8 { let c = Unicode.Scalar(b) if b < 0x80 && unreserved.contains(c) { out.unicodeScalars.append(c) } else { out += String(format: "%%%02X", b) } } return out } static func decode(_ s: String) -> String? { var bytes: [UInt8] = [] let u = Array(s.unicodeScalars) var i = 0 func hex(_ c: Unicode.Scalar) -> UInt8? { switch c { case "0"..."9": return UInt8(c.value - 48) case "a"..."f": return UInt8(c.value - 87) case "A"..."F": return UInt8(c.value - 55) default: return nil } } while i < u.count { let c = u[i] if c == "%" { guard i + 2 < u.count, let h = hex(u[i + 1]), let l = hex(u[i + 2]) else { return nil } bytes.append(h * 16 + l) i += 3 } else if c.value < 0x21 || c.value > 0x7E { return nil } else { bytes.append(UInt8(c.value)) i += 1 } } return String(bytes: bytes, encoding: .utf8) } static func url(template: WidgetTemplate, id: String, link: String?) -> String { var q = "t=\(template.rawValue)&k=open" if !id.isEmpty { q += "&id=" + encode(id) } if let link = link, !link.isEmpty { q += "&l=" + encode(link) } return "\(scheme)://tap?\(q)" } /// The open tap a deep link stands for, or nil. static func parse(_ url: String) -> WidgetTap? { let head = "\(scheme)://tap?" guard url.unicodeScalars.count <= 2048, url.unicodeScalars.count >= head.unicodeScalars.count, String(String.UnicodeScalarView(url.unicodeScalars.prefix(head.unicodeScalars.count))).lowercased() == head else { return nil } let query = String(String.UnicodeScalarView(url.unicodeScalars.dropFirst(head.unicodeScalars.count))) var fields: [String: String] = [:] for part in query.split(separator: "&", omittingEmptySubsequences: false) { guard let eq = part.firstIndex(of: "=") else { return nil } let k = String(part[..<eq]) let raw = String(part[part.index(after: eq)...]) guard ["t", "k", "id", "l"].contains(k), fields[k] == nil, let v = decode(raw) else { return nil } fields[k] = v } guard let t = fields["t"], WidgetTemplate(rawValue: t) != nil, fields["k"] == "open" else { return nil } var tap = WidgetTap(template: t, kind: "open", id: "") if let id = fields["id"] { guard WidgetValidator.isID(id) else { return nil } tap.id = id } if let l = fields["l"] { guard WidgetValidator.isLink(l) else { return nil } tap.link = l } return tap }}// MARK: - Taps/// One widget tap: "open" (a deep link), "action" (a stat button or the list's header button) or/// "toggle" (a list item's check button).struct WidgetTap: Equatable { var seq: Int = 0 var template: String var kind: String var id: String var link: String? var checked: Bool? var at: Int64 = 0 /// The event and route form. var dictionary: [String: Any] { var d: [String: Any] = ["seq": seq, "template": template, "kind": kind, "id": id, "at": at] if let l = link { d["link"] = l } if let c = checked { d["checked"] = c } return d }}/// Taps not yet acknowledged by the page, capped (oldest dropped and counted).struct WidgetTapQueue: Equatable { var next = 1 var dropped = 0 var taps: [WidgetTap] = [] mutating func push(_ tap: WidgetTap) -> WidgetTap { var t = tap t.seq = next next += 1 taps.append(t) while taps.count > WidgetLimits.queueCap { taps.removeFirst() dropped += 1 } return t } mutating func ack(_ upto: Int) { taps.removeAll { $0.seq <= upto } } // Stored as JSON in the App Group. Integers only, so they never meet the progress formatter. func encoded() -> Data { let list = taps.map { t -> [String: Any] in t.dictionary } let obj: [String: Any] = ["next": next, "dropped": dropped, "taps": list] return (try? JSONSerialization.data(withJSONObject: obj, options: [.sortedKeys])) ?? Data() } static func decoded(_ data: Data?) -> WidgetTapQueue { guard let data = data, let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return WidgetTapQueue() } var q = WidgetTapQueue() q.next = max(1, obj["next"] as? Int ?? 1) q.dropped = max(0, obj["dropped"] as? Int ?? 0) for t in obj["taps"] as? [[String: Any]] ?? [] { guard let seq = t["seq"] as? Int, let tpl = t["template"] as? String, let kind = t["kind"] as? String, let id = t["id"] as? String else { continue } q.taps.append(WidgetTap(seq: seq, template: tpl, kind: kind, id: id, link: t["link"] as? String, checked: t["checked"] as? Bool, at: (t["at"] as? NSNumber)?.int64Value ?? 0)) } q.taps = Array(q.taps.filter { $0.seq < q.next }.suffix(WidgetLimits.queueCap)) return q }}// MARK: - Shared storage (App Group)/// Files in the App Group container the build provisions for the logical name "widgets"/// (group.<bundle id>.nx.widgets, published to both bundles as NXAppGroups). Every read-modify-write/// goes through NSFileCoordinator, so the app and the widget extension never lose each other's write.enum WidgetShared { static let logicalGroup = "widgets" static func groupIdentifier() -> String? { (Bundle.main.object(forInfoDictionaryKey: "NXAppGroups") as? [String: String])?[logicalGroup] } static func directory() -> URL? { guard let id = groupIdentifier(), let base = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: id) else { return nil } let dir = base.appendingPathComponent("nxwidgets", isDirectory: true) try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) return dir } /// The Darwin notification the widget posts after it queued a tap; the running app drains the queue. static var tapNotification: String { (groupIdentifier() ?? "nxwidgets") + ".tap" } static func dataURL(_ t: WidgetTemplate) -> URL? { directory()?.appendingPathComponent("\(t.rawValue).json") } static func tapsURL() -> URL? { directory()?.appendingPathComponent("taps.json") } /// Coordinated read-modify-write. `body` gets the current bytes (nil when absent) and returns the /// new bytes (nil to delete) and a result. False when the group or the file cannot be used. static func update<R>(_ url: URL, _ body: (Data?) -> (Data?, R)) -> R? { var result: R? var coordError: NSError? NSFileCoordinator(filePresenter: nil).coordinate(writingItemAt: url, options: .forMerging, error: &coordError) { u in let current = try? Data(contentsOf: u) let (next, r) = body(current) do { if let next = next { try next.write(to: u, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) } else if current != nil { try FileManager.default.removeItem(at: u) } result = r } catch { result = nil } } return coordError == nil ? result : nil } static func read(_ url: URL) -> Data? { var out: Data? var coordError: NSError? NSFileCoordinator(filePresenter: nil).coordinate(readingItemAt: url, options: [], error: &coordError) { u in out = try? Data(contentsOf: u) } return out } /// The stored, validated data of a template, or nil. Stored text is validated again on read: a /// file that does not validate shows the empty state, never half a widget. static func load(_ t: WidgetTemplate) -> WidgetData? { guard let url = dataURL(t), let data = read(url), let text = String(data: data, encoding: .utf8) else { return nil } return try? WidgetValidator.validate(template: t.rawValue, text: text) } @discardableResult static func store(_ t: WidgetTemplate, _ d: WidgetData?) -> Bool { guard let url = dataURL(t) else { return false } let bytes = d.map { Data(WidgetValidator.canonical($0).utf8) } return update(url) { _ in (bytes, true) } ?? false } /// Queues a tap; returns it with its sequence number, or nil when storage failed. static func record(_ tap: WidgetTap) -> WidgetTap? { guard let url = tapsURL() else { return nil } var t = tap t.at = Int64((Date().timeIntervalSince1970 * 1000).rounded()) return update(url) { cur -> (Data?, WidgetTap?) in var q = WidgetTapQueue.decoded(cur) let stored = q.push(t) return (q.encoded(), stored) } ?? nil } static func taps() -> WidgetTapQueue { guard let url = tapsURL() else { return WidgetTapQueue() } return WidgetTapQueue.decoded(read(url)) } static func ack(_ upto: Int) -> WidgetTapQueue? { guard let url = tapsURL() else { return nil } return update(url) { cur -> (Data?, WidgetTapQueue) in var q = WidgetTapQueue.decoded(cur) q.ack(upto) return (q.encoded(), q) } } /// Sets one list item's checked state in the stored list (the widget's check button). static func toggle(item: String, checked: Bool) -> Bool { guard let url = dataURL(.list) else { return false } return update(url) { cur -> (Data?, Bool) in guard let cur = cur, let text = String(data: cur, encoding: .utf8), case .list(let l)? = try? WidgetValidator.validate(template: "list", text: text), let next = WidgetValidator.toggle(l, item: item, checked: checked) else { return (cur, false) } return (Data(WidgetValidator.canonical(.list(next)).utf8), true) } ?? false } static func postTap() { let name = CFNotificationName(tapNotification as CFString) CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), name, nil, nil, true) }}
// Engineer-owned module build. It runs only in the offline, credential-free NX compile job.// Jetpack Glance 1.2.0 is the latest stable release (read 2026-11-20:// https://developer.android.com/jetpack/androidx/releases/glance, 1.2.0 of August 26, 2026). The newer// 1.3.0-alpha02 needs AGP 9.2 (its Compose compileSdk is 37); the base app builds with AGP 8.9.1.// Glance 1.2.0 asks only for versions the base app already meets or raises (compose runtime 1.7.8,// work-runtime-ktx 2.7.1, core-ktx 1.7.0, kotlin-stdlib 2.0.21), so no base coordinate changes.// Kotlin and the Compose compiler plugin come from the base app's root build (Kotlin 2.3.10).apply plugin: 'com.android.library'apply plugin: 'kotlin-android'apply plugin: 'org.jetbrains.kotlin.plugin.compose'android { namespace 'despia.ext.widgets' compileSdk 36 defaultConfig { minSdk 24 } compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } kotlinOptions { jvmTarget = '17' } buildFeatures { compose true }}dependencies { implementation project(':nativeext-api') implementation 'androidx.glance:glance-appwidget:1.2.0' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1'}
package despia.ext.widgets;import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeMap;/** * The widgets sample's shared rules on Android, the same as WidgetModel.swift on iOS: the two * templates (stat, list) and their one validator, a strict JSON reader and the canonical writer, the * widget deep link and the tap queue. Plain Java with no Android types, so it also runs on a JVM. * * <p>Customise here: the deep-link scheme (also in manifest.json, claims.intent_schemes), the limits * and the fields of a template (add them to the reader, the writer and WidgetUi.kt together). */public final class WidgetModel { private WidgetModel() { } public static final int MAX_BYTES = 4096; public static final int MAX_DEPTH = 8; public static final int QUEUE_CAP = 32; public static final int MAX_LINK = 512; public static final String SCHEME = "nxwidgets"; public static final String STAT = "stat"; public static final String LIST = "list"; public static boolean isTemplate(String t) { return STAT.equals(t) || LIST.equals(t); } /** A data error: the path of the first wrong field and the reason. */ public static final class DataError extends Exception { public final String path; public final String reason; DataError(String path, String reason) { super(path + ": " + reason); this.path = path; this.reason = reason; } } /** JSON null, distinct from an absent key. */ public static final Object NULL = new Object(); // ------------------------------------------------------------------ JSON reader static final class Reader { private final int[] s; private int i; Reader(String text) { s = text.codePoints().toArray(); } static DataError bad() { return new DataError("$", "bad json"); } static Object parse(String text) throws DataError { Reader r = new Reader(text); Object v = r.value(1); r.space(); if (r.i != r.s.length) throw bad(); return v; } private int peek() { return i < s.length ? s[i] : -1; } private void space() { while (peek() == ' ' || peek() == '\t' || peek() == '\n' || peek() == '\r') i++; } private boolean literal(String w) { int[] u = w.codePoints().toArray(); if (i + u.length > s.length) return false; for (int k = 0; k < u.length; k++) if (s[i + k] != u[k]) return false; i += u.length; return true; } private Object value(int depth) throws DataError { space(); int c = peek(); if ((c == '{' || c == '[') && depth > MAX_DEPTH) throw bad(); if (c == '{') { i++; Map<String, Object> out = new LinkedHashMap<>(); space(); if (peek() == '}') { i++; return out; } while (true) { space(); if (peek() != '"') throw bad(); String k = string(); space(); if (peek() != ':') throw bad(); i++; Object v = value(depth + 1); if (out.containsKey(k)) throw bad(); out.put(k, v); space(); int e = peek(); i++; if (e == '}') return out; if (e != ',') throw bad(); } } if (c == '[') { i++; List<Object> out = new ArrayList<>(); space(); if (peek() == ']') { i++; return out; } while (true) { out.add(value(depth + 1)); space(); int e = peek(); i++; if (e == ']') return out; if (e != ',') throw bad(); } } if (c == '"') return string(); if (literal("true")) return Boolean.TRUE; if (literal("false")) return Boolean.FALSE; if (literal("null")) return NULL; return number(); } private boolean digit(int c) { return c >= '0' && c <= '9'; } private Double number() throws DataError { int start = i; if (peek() == '-') i++; if (peek() == '0') { i++; } else if (digit(peek())) { while (digit(peek())) i++; } else { throw bad(); } if (peek() == '.') { i++; if (!digit(peek())) throw bad(); while (digit(peek())) i++; } if (peek() == 'e' || peek() == 'E') { i++; if (peek() == '+' || peek() == '-') i++; if (!digit(peek())) throw bad(); while (digit(peek())) i++; } // Only ASCII digits, signs, '.' and 'e' reach here; 1e999 parses as Infinity. return Double.parseDouble(new String(s, start, i - start)); } private int hex4() throws DataError { if (i + 4 > s.length) throw bad(); int v = 0; for (int k = 0; k < 4; k++) { int c = s[i++]; int d; if (c >= '0' && c <= '9') d = c - '0'; else if (c >= 'a' && c <= 'f') d = c - 'a' + 10; else if (c >= 'A' && c <= 'F') d = c - 'A' + 10; else throw bad(); v = v * 16 + d; } return v; } private String string() throws DataError { i++; StringBuilder out = new StringBuilder(); while (true) { int c = peek(); if (c < 0x20) throw bad(); i++; if (c == '"') return out.toString(); if (c != '\\') { // A lone surrogate code unit in the Java string itself. if (c >= 0xD800 && c <= 0xDFFF) throw bad(); out.appendCodePoint(c); continue; } int e = peek(); i++; switch (e) { case '"': out.append('"'); break; case '\\': out.append('\\'); break; case '/': out.append('/'); break; case 'b': out.append('\b'); break; case 'f': out.append('\f'); break; case 'n': out.append('\n'); break; case 'r': out.append('\r'); break; case 't': out.append('\t'); break; case 'u': { int u = hex4(); if (u >= 0xD800 && u <= 0xDBFF) { if (i + 2 > s.length || s[i] != '\\' || s[i + 1] != 'u') throw bad(); i += 2; int lo = hex4(); if (lo < 0xDC00 || lo > 0xDFFF) throw bad(); u = 0x10000 + ((u - 0xD800) << 10) + (lo - 0xDC00); } else if (u >= 0xDC00 && u <= 0xDFFF) { throw bad(); } out.appendCodePoint(u); break; } default: throw bad(); } } } } // ------------------------------------------------------------------ canonical writer static String write(Object v) { StringBuilder b = new StringBuilder(); write(v, b); return b.toString(); } @SuppressWarnings("unchecked") private static void write(Object v, StringBuilder b) { if (v instanceof Map) { Map<String, Object> m = new TreeMap<>((Map<String, Object>) v); b.append('{'); boolean first = true; for (Map.Entry<String, Object> e : m.entrySet()) { if (!first) b.append(','); first = false; escape(e.getKey(), b); b.append(':'); write(e.getValue(), b); } b.append('}'); } else if (v instanceof List) { b.append('['); boolean first = true; for (Object x : (List<Object>) v) { if (!first) b.append(','); first = false; write(x, b); } b.append(']'); } else if (v instanceof String) { escape((String) v, b); } else if (v instanceof Double) { b.append(progressText((Double) v)); } else if (v instanceof Boolean) { b.append(((Boolean) v) ? "true" : "false"); } else if (v instanceof Long || v instanceof Integer) { b.append(v.toString()); } else { b.append("null"); } } public static String progressText(double d) { long n = (long) Math.floor(d * 10000 + 0.5); if (n >= 10000) return "1"; if (n <= 0) return "0"; StringBuilder t = new StringBuilder(Long.toString(n)); while (t.length() < 4) t.insert(0, '0'); while (t.charAt(t.length() - 1) == '0') t.setLength(t.length() - 1); return "0." + t; } private static void escape(String s, StringBuilder b) { b.append('"'); s.codePoints().forEach(c -> { if (c == '"') b.append("\\\""); else if (c == '\\') b.append("\\\\"); else if (c < 0x20) b.append(String.format("\\u%04x", c)); else b.appendCodePoint(c); }); b.append('"'); } // ------------------------------------------------------------------ typed data public static final class Button { public final String id; public final String label; Button(String id, String label) { this.id = id; this.label = label; } Map<String, Object> json() { Map<String, Object> m = new LinkedHashMap<>(); m.put("id", id); m.put("label", label); return m; } } public static final class Stat { public String title; public String value; public String unit; public String caption; public Double progress; public String trend; public String tint; public String link; public List<Button> actions; Map<String, Object> json() { Map<String, Object> m = new LinkedHashMap<>(); m.put("title", title); m.put("value", value); put(m, "unit", unit); put(m, "caption", caption); put(m, "progress", progress); put(m, "trend", trend); put(m, "tint", tint); put(m, "link", link); if (actions != null) { List<Object> a = new ArrayList<>(); for (Button x : actions) a.add(x.json()); m.put("actions", a); } return m; } } public static final class Item { public String id; public String title; public String subtitle; public Boolean checked; public String link; Item copy() { Item c = new Item(); c.id = id; c.title = title; c.subtitle = subtitle; c.checked = checked; c.link = link; return c; } Map<String, Object> json() { Map<String, Object> m = new LinkedHashMap<>(); m.put("id", id); m.put("title", title); put(m, "subtitle", subtitle); put(m, "checked", checked); put(m, "link", link); return m; } } public static final class ListData { public String title; public List<Item> items = new ArrayList<>(); public String empty; public String tint; public String link; public Button action; Map<String, Object> json() { Map<String, Object> m = new LinkedHashMap<>(); m.put("title", title); List<Object> a = new ArrayList<>(); for (Item x : items) a.add(x.json()); m.put("items", a); put(m, "empty", empty); put(m, "tint", tint); put(m, "link", link); if (action != null) m.put("action", action.json()); return m; } } private static void put(Map<String, Object> m, String k, Object v) { if (v != null) m.put(k, v); } /** Stat or ListData. */ public static Object validate(String template, String text) throws DataError { if (!isTemplate(template)) throw new DataError("$", "bad template"); if (text.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) throw new DataError("$", "too large"); Object v = Reader.parse(text); return STAT.equals(template) ? stat(v) : list(v); } public static String canonical(Object data) { if (data instanceof Stat) return write(((Stat) data).json()); return write(((ListData) data).json()); } static String join(String path, String key) { return "$".equals(path) ? key : path + "." + key; } @SuppressWarnings("unchecked") static Map<String, Object> object(Object v, String path, List<String> allowed) throws DataError { if (!(v instanceof Map)) throw new DataError(path, "not an object"); Map<String, Object> o = (Map<String, Object>) v; List<String> unknown = new ArrayList<>(); for (String k : o.keySet()) if (!allowed.contains(k)) unknown.add(k); if (!unknown.isEmpty()) { Collections.sort(unknown); throw new DataError(join(path, unknown.get(0)), "unknown key"); } return o; } static String text(Map<String, Object> o, String key, String path, int lo, int hi, boolean required) throws DataError { if (!o.containsKey(key)) { if (required) throw new DataError(path, "missing"); return null; } Object v = o.get(key); if (!(v instanceof String)) throw new DataError(path, "not a string"); String s = (String) v; if (s.codePoints().anyMatch(c -> c < 0x20 || c == 0x7F)) throw new DataError(path, "control character"); int n = s.codePointCount(0, s.length()); if (n < lo) throw new DataError(path, "empty"); if (n > hi) throw new DataError(path, "too long"); return s; } public static boolean isId(String s) { if (s == null || s.length() < 1 || s.length() > 32) return false; for (int k = 0; k < s.length(); k++) { char c = s.charAt(k); if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '-')) return false; } return true; } static String id(Map<String, Object> o, String key, String path) throws DataError { String s = text(o, key, path, 1, 32, true); if (!isId(s)) throw new DataError(path, "bad id"); return s; } /** A path inside the page's own app: starts with one "/", printable ASCII, no backslash. */ public static boolean isLink(String s) { if (s == null || s.isEmpty() || s.length() > MAX_LINK || s.charAt(0) != '/') return false; if (s.length() > 1 && s.charAt(1) == '/') return false; for (int k = 0; k < s.length(); k++) { char c = s.charAt(k); if (c < 0x21 || c > 0x7E || c == '\\') return false; } return true; } static String link(Map<String, Object> o, String key, String path) throws DataError { String s = text(o, key, path, 1, MAX_LINK, false); if (s != null && !isLink(s)) throw new DataError(path, "bad link"); return s; } static String color(Map<String, Object> o, String key, String path) throws DataError { String s = text(o, key, path, 1, 7, false); if (s == null) return null; boolean ok = s.length() == 7 && s.charAt(0) == '#'; for (int k = 1; ok && k < 7; k++) { char c = s.charAt(k); ok = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } if (!ok) throw new DataError(path, "bad color"); return s; } @SuppressWarnings("unchecked") static List<Object> array(Map<String, Object> o, String key, String path, int hi, boolean required) throws DataError { if (!o.containsKey(key)) { if (required) throw new DataError(path, "missing"); return null; } Object v = o.get(key); if (!(v instanceof List)) throw new DataError(path, "not an array"); List<Object> a = (List<Object>) v; if (a.size() > hi) throw new DataError(path, "too many"); return a; } static final List<String> BUTTON_KEYS = java.util.Arrays.asList("id", "label"); static final List<String> STAT_KEYS = java.util.Arrays.asList( "title", "value", "unit", "caption", "progress", "trend", "tint", "link", "actions"); static final List<String> LIST_KEYS = java.util.Arrays.asList("title", "items", "empty", "tint", "link", "action"); static final List<String> ITEM_KEYS = java.util.Arrays.asList("id", "title", "subtitle", "checked", "link"); static Button button(Object v, String path) throws DataError { Map<String, Object> o = object(v, path, BUTTON_KEYS); String id = id(o, "id", join(path, "id")); return new Button(id, text(o, "label", join(path, "label"), 1, 20, true)); } static Stat stat(Object v) throws DataError { Map<String, Object> o = object(v, "$", STAT_KEYS); Stat d = new Stat(); d.title = text(o, "title", "title", 1, 40, true); d.value = text(o, "value", "value", 1, 16, true); d.unit = text(o, "unit", "unit", 1, 12, false); d.caption = text(o, "caption", "caption", 1, 60, false); if (o.containsKey("progress")) { Object p = o.get("progress"); if (!(p instanceof Double)) throw new DataError("progress", "not a number"); double n = (Double) p; if (!(n >= 0 && n <= 1)) throw new DataError("progress", "out of range"); d.progress = n; } if (o.containsKey("trend")) { String t = text(o, "trend", "trend", 1, 16, true); if (!t.equals("up") && !t.equals("down") && !t.equals("flat")) throw new DataError("trend", "bad value"); d.trend = t; } d.tint = color(o, "tint", "tint"); d.link = link(o, "link", "link"); List<Object> acts = array(o, "actions", "actions", 2, false); if (acts != null) { Set<String> seen = new HashSet<>(); d.actions = new ArrayList<>(); for (int k = 0; k < acts.size(); k++) { Button b = button(acts.get(k), "actions[" + k + "]"); if (!seen.add(b.id)) throw new DataError("actions[" + k + "].id", "duplicate id"); d.actions.add(b); } } return d; } static ListData list(Object v) throws DataError { Map<String, Object> o = object(v, "$", LIST_KEYS); ListData d = new ListData(); d.title = text(o, "title", "title", 1, 40, true); List<Object> raw = array(o, "items", "items", 8, true); Set<String> seen = new HashSet<>(); for (int k = 0; k < raw.size(); k++) { String p = "items[" + k + "]"; Map<String, Object> it = object(raw.get(k), p, ITEM_KEYS); Item item = new Item(); item.id = id(it, "id", p + ".id"); item.title = text(it, "title", p + ".title", 1, 60, true); if (!seen.add(item.id)) throw new DataError(p + ".id", "duplicate id"); item.subtitle = text(it, "subtitle", p + ".subtitle", 1, 60, false); if (it.containsKey("checked")) { Object c = it.get("checked"); if (!(c instanceof Boolean)) throw new DataError(p + ".checked", "not a bool"); item.checked = (Boolean) c; } item.link = link(it, "link", p + ".link"); d.items.add(item); } d.empty = text(o, "empty", "empty", 1, 60, false); d.tint = color(o, "tint", "tint"); d.link = link(o, "link", "link"); if (o.containsKey("action")) d.action = button(o.get("action"), "action"); return d; } /** List data with one item's checked state set; null when the item is unknown or not checkable. */ public static ListData toggle(ListData l, String item, boolean checked) { ListData out = new ListData(); out.title = l.title; out.empty = l.empty; out.tint = l.tint; out.link = l.link; out.action = l.action; boolean found = false; for (Item it : l.items) { Item c = it.copy(); if (c.id.equals(item) && c.checked != null) { c.checked = checked; found = true; } out.items.add(c); } return found ? out : null; } // ------------------------------------------------------------------ deep link private static final String UNRESERVED = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~/"; public static String encode(String s) { StringBuilder b = new StringBuilder(); for (byte x : s.getBytes(StandardCharsets.UTF_8)) { int u = x & 0xFF; if (u < 0x80 && UNRESERVED.indexOf(u) >= 0) b.append((char) u); else b.append(String.format("%%%02X", u)); } return b.toString(); } static int hex(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } public static String decode(String s) { java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); for (int k = 0; k < s.length(); ) { char c = s.charAt(k); if (c == '%') { if (k + 2 >= s.length()) return null; int h = hex(s.charAt(k + 1)); int l = hex(s.charAt(k + 2)); if (h < 0 || l < 0) return null; out.write(h * 16 + l); k += 3; } else if (c < 0x21 || c > 0x7E) { return null; } else { out.write(c); k++; } } java.nio.charset.CharsetDecoder dec = StandardCharsets.UTF_8.newDecoder() .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT); try { return dec.decode(java.nio.ByteBuffer.wrap(out.toByteArray())).toString(); } catch (java.nio.charset.CharacterCodingException e) { return null; } } public static String linkUrl(String template, String id, String link) { StringBuilder q = new StringBuilder("t=").append(template).append("&k=open"); if (id != null && !id.isEmpty()) q.append("&id=").append(encode(id)); if (link != null && !link.isEmpty()) q.append("&l=").append(encode(link)); return SCHEME + "://tap?" + q; } /** The open tap a deep link stands for, or null. Any app can open a custom scheme: all is checked. */ public static Tap parseLink(String url) { String head = SCHEME + "://tap?"; if (url == null || url.length() > 2048 || url.length() < head.length() || !url.substring(0, head.length()).toLowerCase(java.util.Locale.ROOT).equals(head)) { return null; } Map<String, String> fields = new LinkedHashMap<>(); for (String part : url.substring(head.length()).split("&", -1)) { int eq = part.indexOf('='); if (eq < 0) return null; String k = part.substring(0, eq); String v = decode(part.substring(eq + 1)); if (!(k.equals("t") || k.equals("k") || k.equals("id") || k.equals("l")) || fields.containsKey(k) || v == null) { return null; } fields.put(k, v); } if (!isTemplate(fields.get("t")) || !"open".equals(fields.get("k"))) return null; Tap t = new Tap(fields.get("t"), "open", ""); if (fields.containsKey("id")) { if (!isId(fields.get("id"))) return null; t.id = fields.get("id"); } if (fields.containsKey("l")) { if (!isLink(fields.get("l"))) return null; t.link = fields.get("l"); } return t; } // ------------------------------------------------------------------ taps /** One widget tap: open (a deep link), action (a button) or toggle (a list item's check box). */ public static final class Tap { public long seq; public String template; public String kind; public String id; public String link; public Boolean checked; public long at; public Tap(String template, String kind, String id) { this.template = template; this.kind = kind; this.id = id; } Map<String, Object> json() { Map<String, Object> m = new LinkedHashMap<>(); m.put("seq", seq); m.put("template", template); m.put("kind", kind); m.put("id", id); m.put("at", at); put(m, "link", link); put(m, "checked", checked); return m; } public String toJson() { return write(json()); } } /** Taps not yet acknowledged by the page, capped (oldest dropped and counted). */ public static final class TapQueue { public long next = 1; public long dropped = 0; public final List<Tap> taps = new ArrayList<>(); public Tap push(Tap tap) { tap.seq = next++; taps.add(tap); while (taps.size() > QUEUE_CAP) { taps.remove(0); dropped++; } return tap; } public void ack(long upto) { taps.removeIf(t -> t.seq <= upto); } public String encode() { Map<String, Object> m = new LinkedHashMap<>(); m.put("next", next); m.put("dropped", dropped); List<Object> a = new ArrayList<>(); for (Tap t : taps) a.add(t.json()); m.put("taps", a); return write(m); } /** The stored queue; an unreadable one starts empty. Numbers here are integers. */ @SuppressWarnings("unchecked") public static TapQueue decode(String text) { TapQueue q = new TapQueue(); if (text == null) return q; try { Object v = Reader.parse(text); if (!(v instanceof Map)) return q; Map<String, Object> m = (Map<String, Object>) v; q.next = Math.max(1, num(m.get("next"))); q.dropped = Math.max(0, num(m.get("dropped"))); Object list = m.get("taps"); if (list instanceof List) { for (Object x : (List<Object>) list) { if (!(x instanceof Map)) continue; Map<String, Object> t = (Map<String, Object>) x; if (!(t.get("template") instanceof String) || !(t.get("kind") instanceof String) || !(t.get("id") instanceof String) || !(t.get("seq") instanceof Double)) continue; Tap tap = new Tap((String) t.get("template"), (String) t.get("kind"), (String) t.get("id")); tap.seq = num(t.get("seq")); tap.at = num(t.get("at")); if (t.get("link") instanceof String) tap.link = (String) t.get("link"); if (t.get("checked") instanceof Boolean) tap.checked = (Boolean) t.get("checked"); if (tap.seq < q.next) q.taps.add(tap); } } while (q.taps.size() > QUEUE_CAP) q.taps.remove(0); } catch (DataError e) { return new TapQueue(); } return q; } private static long num(Object o) { return o instanceof Double ? (long) (double) (Double) o : 0; } }}
package despia.ext.widgets;import android.content.Context;import android.content.SharedPreferences;/** * Shared storage of the widgets sample on Android: one SharedPreferences file, "nx_widgets", read by * the Glance widgets and written by the routes and the widget callbacks. Everything runs in the app's * main process (Glance renders and runs its callbacks there), so one lock orders every * read-modify-write and commit() makes each write durable before it returns. * * <p>Values are WidgetModel's canonical text; a stored value is validated again when it is read, so a * value that does not validate shows the empty state, never half a widget. */public final class WidgetStore { private WidgetStore() { } static final String PREFS = "nx_widgets"; private static final String TAPS = "taps"; private static final Object LOCK = new Object(); private static volatile Listener listener; /** Told about every tap after it is stored (the extension emits it to the page). */ public interface Listener { void onTap(WidgetModel.Tap tap); } /** A yes or no answer from asynchronous work (pin). */ public interface Done { void done(boolean ok); } static void setListener(Listener l) { listener = l; } private static SharedPreferences prefs(Context c) { return c.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); } private static String dataKey(String template) { return "data." + template; } /** Stat, ListData or null. */ public static Object load(Context c, String template) { String text; synchronized (LOCK) { text = prefs(c).getString(dataKey(template), null); } if (text == null) return null; try { return WidgetModel.validate(template, text); } catch (WidgetModel.DataError e) { return null; } } public static WidgetModel.Stat stat(Context c) { Object d = load(c, WidgetModel.STAT); return d instanceof WidgetModel.Stat ? (WidgetModel.Stat) d : null; } public static WidgetModel.ListData list(Context c) { Object d = load(c, WidgetModel.LIST); return d instanceof WidgetModel.ListData ? (WidgetModel.ListData) d : null; } /** The canonical text of validated data, or null to remove it. False when the write failed. */ static boolean store(Context c, String template, String canonical) { synchronized (LOCK) { SharedPreferences.Editor e = prefs(c).edit(); if (canonical == null) e.remove(dataKey(template)); else e.putString(dataKey(template), canonical); return e.commit(); } } static String text(Context c, String template) { synchronized (LOCK) { return prefs(c).getString(dataKey(template), null); } } public static WidgetModel.TapQueue taps(Context c) { synchronized (LOCK) { return WidgetModel.TapQueue.decode(prefs(c).getString(TAPS, null)); } } /** The queue after acknowledging every tap up to {@code upto}, or null when the write failed. */ static WidgetModel.TapQueue ack(Context c, long upto) { synchronized (LOCK) { WidgetModel.TapQueue q = WidgetModel.TapQueue.decode(prefs(c).getString(TAPS, null)); q.ack(upto); return prefs(c).edit().putString(TAPS, q.encode()).commit() ? q : null; } } /** Queues a tap and tells the listener; returns it with its sequence number, or null. */ public static WidgetModel.Tap record(Context c, WidgetModel.Tap tap) { WidgetModel.Tap stored; synchronized (LOCK) { WidgetModel.TapQueue q = WidgetModel.TapQueue.decode(prefs(c).getString(TAPS, null)); tap.at = System.currentTimeMillis(); stored = q.push(tap); if (!prefs(c).edit().putString(TAPS, q.encode()).commit()) return null; } Listener l = listener; if (l != null) l.onTap(stored); return stored; } /** A stat button or the list's header button, recorded only when the stored data declares it. */ public static boolean recordAction(Context c, String template, String button) { Object d = load(c, template); boolean declared = false; if (d instanceof WidgetModel.Stat && ((WidgetModel.Stat) d).actions != null) { for (WidgetModel.Button b : ((WidgetModel.Stat) d).actions) declared |= b.id.equals(button); } else if (d instanceof WidgetModel.ListData && ((WidgetModel.ListData) d).action != null) { declared = ((WidgetModel.ListData) d).action.id.equals(button); } return declared && record(c, new WidgetModel.Tap(template, "action", button)) != null; } /** A list item's check box: sets the stored state, then queues the toggle tap. */ public static boolean toggle(Context c, String item, boolean checked) { synchronized (LOCK) { String text = prefs(c).getString(dataKey(WidgetModel.LIST), null); if (text == null) return false; WidgetModel.ListData next; try { next = WidgetModel.toggle((WidgetModel.ListData) WidgetModel.validate(WidgetModel.LIST, text), item, checked); } catch (WidgetModel.DataError e) { return false; } if (next == null || !prefs(c).edit().putString(dataKey(WidgetModel.LIST), WidgetModel.canonical(next)).commit()) { return false; } } WidgetModel.Tap tap = new WidgetModel.Tap(WidgetModel.LIST, "toggle", item); tap.checked = checked; return record(c, tap) != null; }}
package despia.ext.widgets;import android.app.Activity;import android.appwidget.AppWidgetManager;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import com.despia.nativeext.ExtCall;import com.despia.nativeext.ExtContext;import com.despia.nativeext.ExtResult;import com.despia.nativeext.NativeExtension;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;/** * Home-screen widgets the page fills, built with Jetpack Glance (WidgetUi.kt): routes that set, read * and clear each template's data and update its widgets, list the placed widgets, ask the launcher to * pin one, and read the widget taps. Taps (a deep link, a button, a check box) are stored first and * then emitted as the "tap" event, so a page that loads later still reads them with "taps". */public final class WidgetsExtension implements NativeExtension { private ExtContext ctx; private final Handler main = new Handler(Looper.getMainLooper()); @Override public void onCreate(ExtContext context) { ctx = context; WidgetStore.setListener(tap -> main.post(() -> emit(tap))); WidgetUpdater.publishPreviews(context.app()); } private void emit(WidgetModel.Tap tap) { try { ctx.emit("tap", new JSONObject(tap.toJson())); } catch (JSONException e) { ctx.log("tap not emitted: " + e.getMessage()); } } /** nxwidgets://tap?... from a widget (claimed in manifest.json). Any app can send this scheme, so * WidgetModel.parseLink checks every part; a link that does not parse is dropped. */ @Override public boolean onIntent(Activity activity, Intent intent) { WidgetModel.Tap tap = WidgetModel.parseLink(intent.getDataString()); if (tap == null) { ctx.log("dropped a widget link that does not parse"); } else { WidgetStore.record(ctx.app(), tap); } return true; } @Override public void handle(ExtCall call, ExtResult.Callback reply) { Context app = ctx.app(); Object t = call.params.get("template"); String template = t instanceof String && WidgetModel.isTemplate((String) t) ? (String) t : null; try { switch (call.route) { case "set": reply.reply(set(app, template, (String) call.params.get("data"))); return; case "get": reply.reply(get(app, template)); return; case "clear": if (template == null) { reply.reply(ExtResult.error("bad_request", "template")); return; } if (!WidgetStore.store(app, template, null)) { reply.reply(ExtResult.error("storage_failed", "the widget data was not removed")); return; } WidgetUpdater.update(app, template); reply.reply(ExtResult.ok(new JSONObject().put("template", template).put("cleared", true))); return; case "reload": { JSONArray done = new JSONArray(); for (String x : template == null ? new String[]{WidgetModel.STAT, WidgetModel.LIST} : new String[]{template}) { WidgetUpdater.update(app, x); done.put(x); } reply.reply(ExtResult.ok(new JSONObject().put("reloaded", done))); return; } case "installed": reply.reply(ExtResult.ok(new JSONObject().put("widgets", installed(app)))); return; case "taps": reply.reply(taps(app, call.params.get("ack"))); return; case "pin": pin(app, template, call, reply); return; default: reply.reply(ExtResult.error("not_registered", call.route)); } } catch (JSONException e) { reply.reply(ExtResult.error("handler_error", "reply is not JSON")); } } private ExtResult set(Context app, String template, String text) throws JSONException { if (template == null) return ExtResult.error("bad_request", "template"); Object data; try { data = WidgetModel.validate(template, text == null ? "" : text); } catch (WidgetModel.DataError e) { return ExtResult.error("bad_data", e.getMessage()); } if (!WidgetStore.store(app, template, WidgetModel.canonical(data))) { return ExtResult.error("storage_failed", "the widget data was not saved"); } WidgetUpdater.update(app, template); return ExtResult.ok(new JSONObject().put("template", template).put("stored", true)); } private ExtResult get(Context app, String template) throws JSONException { if (template == null) return ExtResult.error("bad_request", "template"); Object d = WidgetStore.load(app, template); Object data = d == null ? JSONObject.NULL : new JSONObject(WidgetModel.canonical(d)); return ExtResult.ok(new JSONObject().put("template", template).put("data", data)); } /** Each placed widget of this sample with its portrait size as the launcher reports it, in dp * (minimum width and maximum height, the AppWidgetManager convention). */ private JSONArray installed(Context app) throws JSONException { AppWidgetManager m = AppWidgetManager.getInstance(app); JSONArray out = new JSONArray(); String[][] receivers = {{WidgetModel.STAT, StatWidgetReceiver.class.getName()}, {WidgetModel.LIST, ListWidgetReceiver.class.getName()}}; for (String[] r : receivers) { for (int id : m.getAppWidgetIds(new ComponentName(app, r[1]))) { Bundle o = m.getAppWidgetOptions(id); out.put(new JSONObject().put("template", r[0]) .put("width", o.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)) .put("height", o.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT))); } } return out; } private ExtResult taps(Context app, Object ack) throws JSONException { // A typed int (0 to 2^53-1), checked by the bridge; absent means acknowledge nothing. long upto = ack instanceof Number ? ((Number) ack).longValue() : 0; WidgetModel.TapQueue q = upto > 0 ? WidgetStore.ack(app, upto) : WidgetStore.taps(app); if (q == null) return ExtResult.error("storage_failed", "the tap queue was not updated"); JSONArray list = new JSONArray(); for (WidgetModel.Tap tap : q.taps) list.put(new JSONObject(tap.toJson())); return ExtResult.ok(new JSONObject().put("taps", list).put("dropped", q.dropped).put("next", q.next)); } /** Asks the launcher to place the widget. The answer says the request was shown, not that the * user placed it: read "installed" afterwards. */ private void pin(Context app, String template, ExtCall call, ExtResult.Callback reply) { if (template == null) { reply.reply(ExtResult.error("bad_request", "template")); return; } AppWidgetManager m = AppWidgetManager.getInstance(app); if (android.os.Build.VERSION.SDK_INT < 26 || !m.isRequestPinAppWidgetSupported()) { reply.reply(ExtResult.error("pin_unavailable", "this launcher does not let apps place widgets")); return; } WidgetUpdater.pin(app, template, ok -> main.post(() -> { if (!call.isActive()) return; try { reply.reply(ok ? ExtResult.ok(new JSONObject().put("template", template).put("requested", true)) : ExtResult.error("pin_unavailable", "the launcher refused the request")); } catch (JSONException e) { reply.reply(ExtResult.error("handler_error", "reply is not JSON")); } })); }}
<?xml version="1.0" encoding="utf-8"?><resources> <string name="nx_widgets_stat_label">Stat</string> <string name="nx_widgets_stat_description">A number with its trend and progress.</string> <string name="nx_widgets_list_label">List</string> <string name="nx_widgets_list_description">A short list with check boxes.</string> <string name="nx_widgets_empty_title">No data yet</string> <string name="nx_widgets_empty_body">Open the app to fill this widget.</string> <string name="nx_widgets_list_empty">Nothing here</string></resources>
<?xml version="1.0" encoding="utf-8"?><!-- List: 4x2 by default, resizable down to 3x2 and up to the full screen width. --><appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:description="@string/nx_widgets_list_description" android:initialLayout="@layout/glance_default_loading_layout" android:minWidth="250dp" android:minHeight="110dp" android:minResizeWidth="180dp" android:minResizeHeight="110dp" android:maxResizeWidth="530dp" android:maxResizeHeight="530dp" android:targetCellWidth="4" android:targetCellHeight="2" android:resizeMode="horizontal|vertical" android:updatePeriodMillis="0" android:widgetCategory="home_screen" />
<?xml version="1.0" encoding="utf-8"?><!-- Stat: 2x2 by default, resizable from 1x1 to wide. No periodic update: the page's set and the buttons redraw it. --><appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:description="@string/nx_widgets_stat_description" android:initialLayout="@layout/glance_default_loading_layout" android:minWidth="110dp" android:minHeight="110dp" android:minResizeWidth="57dp" android:minResizeHeight="51dp" android:maxResizeWidth="530dp" android:maxResizeHeight="450dp" android:targetCellWidth="2" android:targetCellHeight="2" android:resizeMode="horizontal|vertical" android:updatePeriodMillis="0" android:widgetCategory="home_screen|keyguard" />