repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by admin
quickshell/nuguland/features/connectivity/Network.qml
Rawimport QtQuick
import Quickshell.Io
import "network.js" as Network
// Service / native boundary for iwd WiFi management, plus the wired link state
// the bar's offline needs (read-only: `ip -j -d link show`, sysfs uevent).
//
// iwd exposes a full D-Bus API (net.connman.iwd). We talk to it via
// `busctl --json=short`, which emits structured JSON — so there is NO text/ANSI
// parsing. Native objects (Process) stay here; all JSON shaping lives in
// network.js. Two reads drive the model:
// ObjectManager.GetManagedObjects -> devices / stations / networks / known
// Station.GetOrderedNetworks -> [path, signal] strongest-first
//
// Writes are D-Bus method calls (Scan / Connect / Forget / Disconnect) and a
// set-property (Powered) — except connecting to a NEW secured network, which
// needs iwd to call back to an agent for the passphrase; for that one case we
// use `iwctl --passphrase` (a registered agent), as a DISCRETE ARGV array.
//
// SECURITY: every external call uses a discrete argv array — never sh -c with
// interpolation, because SSIDs may contain spaces / quotes / shell metachars.
// The passphrase is a transient argument to the connect call only; it NEVER
// enters stateJson / lastAction / error / any log line.
Item {
id: root
// --- reactive state, fed by the read Processes ---
property bool autoRefresh: true
property string deviceName: ""
property string devicePath: ""
property bool wifiEnabled: true
property bool scanning: false
property bool actionPending: false
property string lastError: ""
property string actionError: ""
// Parsed GetManagedObjects payload (device/station/networks/knownBySsid).
property var managed: ({})
property var mergedModel: []
property var lastAction: ({})
property int scanRetriesLeft: 0
// StationDiagnostic.GetDiagnostics detail for the CONNECTED BSS only
// (bssid/band/channel/rssi/rates/mode), fetched lazily on expand. {} = none.
property var connectionDetail: ({})
// Whether iwd answered with a station device, and that station's state.
// `loaded` stays false until the first reply, so startup never flags offline.
property bool loaded: false
property bool deviceAvailable: false
property string stationState: ""
// Wired Ethernet: "connected" while a port has carrier, "unplugged" while
// ports exist without one, "" without a port. `linksLoaded` stays false
// until the first read, so startup never flags offline.
property string wiredState: ""
property bool linksLoaded: false
property var wiredPortList: []
// A wireless network joined or being joined.
readonly property bool wifiJoined: deviceAvailable && wifiEnabled && ["connected", "connecting", "roaming"].indexOf(stationState) >= 0
// The bar's attention: no working link of any kind, neither a joined
// wireless network nor a wired one. Every iwd signal (iwdWatch) and every
// link change (linkWatch) re-reads it.
readonly property bool offline: loaded && linksLoaded && !wifiJoined && wiredState !== "connected"
// The panel binds these with the state above; stateObject() reports the
// same values over IPC. networks: rows from buildModel(), strongest first.
readonly property var networks: mergedModel
readonly property string error: actionError || lastError
// D-Bus constants.
readonly property string svc: "net.connman.iwd"
readonly property string ifaceStation: "net.connman.iwd.Station"
readonly property string ifaceDevice: "net.connman.iwd.Device"
readonly property string ifaceNetwork: "net.connman.iwd.Network"
readonly property string ifaceKnown: "net.connman.iwd.KnownNetwork"
readonly property string ifaceDiag: "net.connman.iwd.StationDiagnostic"
function busctlCall(objectPath, iface, method) {
return ["busctl", "--json=short", "call", svc, objectPath, iface, method];
}
function activeRow() {
for (let i = 0; i < mergedModel.length; i++)
if (mergedModel[i].connected) {
return mergedModel[i];
}
return null;
}
function rowForId(id) {
const name = String(id);
for (let i = 0; i < mergedModel.length; i++)
if (mergedModel[i].id === name || mergedModel[i].ssid === name) {
return mergedModel[i];
}
return null;
}
function role() {
if (actionError.length > 0 || lastError.length > 0)
return "error";
if (!wifiEnabled)
return "ui.minor";
const active = activeRow();
if (active && active.state === "connecting")
return "warning";
return active ? "ui.accent" : "ui.minor";
}
// Build the view model from parsed managed objects + ordered list. Decorates
// the pure network.js rows with label/percent/glyph/role/state view fields.
function buildModel(ordered) {
const rows = Network.networkRows(managed, ordered);
const station = managed.station || {};
const connecting = station.state === "connecting";
const out = [];
for (let i = 0; i < rows.length; i++) {
const n = rows[i];
const isConnecting = connecting && station.connectedNetwork === n.path;
out.push({
"id": n.id,
"ssid": n.ssid,
"security": n.security,
"securityLabel": Network.securityLabel(n.security),
"signalLabel": Network.signalLabel(n.signal),
"signal": n.signal,
"signalDbm": n.signalDbm,
"signalPercent": n.signal * 25,
"signalRole": Network.signalRole(n.signal),
"signalGlyph": Network.signalGlyph(n.signal),
"known": n.known,
"connected": n.connected,
"needsPassphrase": n.needsPassphrase,
"path": n.path,
"state": n.connected ? "connected" : (isConnecting ? "connecting" : "available")
});
}
mergedModel = out;
// Drop stale per-BSS detail if nothing is connected anymore.
if (!activeRow())
connectionDetail = ({});
}
function stateObject() {
const active = activeRow();
const compactSignal = wifiEnabled && active ? active.signal * 25 : 0;
return {
"scanning": scanning,
"pending": actionPending,
"error": error,
"device": deviceName,
"deviceAvailable": deviceAvailable,
"loaded": loaded,
"offline": offline,
"wired": wiredState,
"wifi": {
"enabled": wifiEnabled
},
"active": active,
"connectionDetail": connectionDetail,
"networks": networks,
"knownNetworks": networks,
"compact": {
"label": "network",
"role": role(),
"signal": compactSignal
},
"lastAction": lastAction
};
}
function stateJson() {
return JSON.stringify(stateObject());
}
// --- read cadence ------------------------------------------------------
// refresh(): one call returns every iwd object + properties; its handler
// then reads the ordered list (which needs the discovered device path).
function refresh() {
gmoProc.exec(busctlCall("/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"));
}
// readLinks(): the physical Ethernet-type links, then their sysfs DEVTYPE,
// which tells a wireless device from a cable port.
function readLinks() {
linkProc.exec(["ip", "-j", "-d", "link", "show"]);
}
function settleLinks(typed) {
wiredState = Network.wiredState(wiredPortList, typed);
linksLoaded = true;
}
// --- actions -----------------------------------------------------------
function actionFailure(exitCode) {
return Number(exitCode) === 0 ? "" : "action-failed";
}
function executeAction(command) {
actionError = "";
actionPending = true;
actionProc.exec(command);
}
function unavailableAction() {
actionPending = false;
actionError = "action-unavailable";
}
function scan() {
if (!devicePath) {
refresh();
return stateJson();
}
scanning = true;
lastError = "";
actionError = "";
scanRetriesLeft = 2;
scanProc.exec(busctlCall(devicePath, ifaceStation, "Scan"));
scanTimer.start();
return stateJson();
}
// connect(ssid, passphrase) — in-process secured/open/known connect. NOT an
// IPC handler. open/known go over D-Bus Network.Connect (no agent needed).
// A NEW secured network needs the passphrase handed to iwd via an agent, so
// it uses `iwctl --passphrase`. The passphrase is a transient argv only.
function connect(ssid, passphrase) {
const name = String(ssid);
const pp = (passphrase === undefined || passphrase === null) ? "" : String(passphrase);
const row = rowForId(name);
lastError = "";
actionError = "";
lastAction = {
"kind": "connect",
"ssid": name
};
if (pp.length > 0) {
// New secured network: iwctl registers an agent and supplies the key.
if (deviceName)
executeAction(["iwctl", "--passphrase", pp, "station", deviceName, "connect", name]);
else
unavailableAction();
} else if (row && row.path) {
executeAction(busctlCall(row.path, ifaceNetwork, "Connect"));
} else {
unavailableAction();
}
return stateJson();
}
// select(id) — IPC entry: connect a known/open network by id (= ssid).
function select(id) {
return connect(String(id), "");
}
function forget(id) {
const name = String(id);
lastAction = {
"kind": "forget",
"id": name
};
const knownPath = (managed.knownBySsid || {})[name];
if (knownPath)
executeAction(busctlCall(knownPath, ifaceKnown, "Forget"));
else
unavailableAction();
return stateJson();
}
function toggleWifi(enabled) {
const on = !!enabled;
lastAction = {
"kind": "toggle-wifi",
"enabled": on
};
if (devicePath) {
wifiEnabled = on;
executeAction(["busctl", "set-property", svc, devicePath, ifaceDevice, "Powered", "b", on ? "true" : "false"]);
} else {
unavailableAction();
}
return stateJson();
}
function disconnect() {
lastAction = {
"kind": "disconnect"
};
if (devicePath)
executeAction(busctlCall(devicePath, ifaceStation, "Disconnect"));
else
unavailableAction();
return stateJson();
}
// diagnostics() — lazy fetch of the connected BSS detail. The view calls
// this when the connected row is expanded; diagProc.onStreamFinished folds
// the result into connectionDetail, which the open drawer binds.
function diagnostics() {
if (devicePath && activeRow())
diagProc.exec(busctlCall(devicePath, ifaceDiag, "GetDiagnostics"));
return stateJson();
}
function checkConnectivity() {
lastAction = {
"kind": "check-connectivity"
};
refresh();
readLinks();
return stateJson();
}
Component.onCompleted: if (autoRefresh) {
refresh();
readLinks();
}
// --- read Processes ----------------------------------------------------
Process {
id: gmoProc
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: {
root.managed = Network.parseManaged(this.text);
const m = root.managed;
root.loaded = true;
root.stationState = m.station ? m.station.state : "";
if (!m.device || !m.devicePath) {
root.lastError = "no-wifi-device";
root.deviceAvailable = false;
root.deviceName = "";
root.devicePath = "";
root.buildModel([]);
return;
}
root.deviceAvailable = true;
root.deviceName = m.device.name;
root.devicePath = m.devicePath;
root.wifiEnabled = m.device.powered;
root.lastError = "";
if (m.device.powered) {
gonProc.exec(root.busctlCall(m.devicePath, root.ifaceStation, "GetOrderedNetworks"));
} else {
root.buildModel([]);
}
}
}
}
Process {
id: gonProc
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: {
root.buildModel(Network.parseOrdered(this.text));
}
}
}
// Lazy StationDiagnostic read (connected BSS only). On reply, shape via
// network.js#connectionDetail; the open drawer binds it.
Process {
id: diagProc
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: {
root.connectionDetail = Network.connectionDetail(this.text) || ({});
}
}
}
// --- action Processes --------------------------------------------------
Process {
id: scanProc
running: false
stderr: StdioCollector {
id: scanErr
waitForEnd: true
}
// "Operation already in progress" = scan already running, NOT a hard
// error: keep scanning, let the retry timer re-read the list.
onExited: exitCode => {
const err = String(scanErr.text || "");
if (exitCode !== 0 && err.indexOf("already in progress") < 0)
root.lastError = "scan-failed";
}
}
// Shared action runner. Re-reads state when done so the model reflects the
// effect. stderr is intentionally NOT surfaced verbatim (belt-and-suspenders:
// a connect arg must never leak via an error string).
Process {
id: actionProc
running: false
onExited: exitCode => {
actionProc.command = [];
root.actionPending = false;
root.actionError = root.actionFailure(exitCode);
root.refresh();
}
}
// Event-driven liveness for the bar's offline state, without polling: one
// idle `gdbus monitor` prints a line per iwd signal (a joined or lost
// network, a powered device, iwd starting or stopping) and each burst of
// lines re-reads the managed objects once. glib2 ships gdbus with qt6-base.
Process {
id: iwdWatch
running: root.autoRefresh
command: ["gdbus", "monitor", "--system", "--dest", root.svc]
stdout: SplitParser {
onRead: watchSettle.restart()
}
}
Timer {
id: watchSettle
interval: 500
onTriggered: root.refresh()
}
Process {
id: linkProc
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: {
root.wiredPortList = Network.wiredPorts(this.text);
if (root.wiredPortList.length === 0)
root.settleLinks({});
else
typeProc.exec(["grep", "-sH", "^DEVTYPE="].concat(root.wiredPortList.map(port => "/sys/class/net/" + port.name + "/uevent")));
}
}
}
Process {
id: typeProc
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: root.settleLinks(Network.typedLinks(this.text))
}
}
// Event-driven wired state, without polling: one idle `ip monitor link`
// prints a record per link change (carrier, up, down, added, removed) and
// each burst re-reads the links once.
Process {
id: linkWatch
running: root.autoRefresh
command: ["ip", "monitor", "link"]
stdout: SplitParser {
onRead: linkSettle.restart()
}
}
Timer {
id: linkSettle
interval: 500
onTriggered: root.readLinks()
}
// Delayed/polled re-read after an async scan (results lag ~1-4 s).
Timer {
id: scanTimer
interval: 2000
repeat: true
running: false
onTriggered: {
root.refresh();
root.scanRetriesLeft -= 1;
if (root.scanRetriesLeft <= 0) {
root.scanning = false;
running = false;
}
}
}
}