Network module: Wi-Fi and wired status, connect to Wi-Fi networks, Wi-Fi and airplane switches
CI / test (push) Failing after 18s
CI / test (push) Failing after 18s
- New `network` panel module (in the default panel, before the battery and the clock): signal bars and the
Wi-Fi network's name, a plug when wired, crossed-out bars offline or in airplane mode. Its
popup shows the status and the last action's outcome ("Couldn't connect to X: wrong
password?"), switches for Wi-Fi and airplane mode, and the networks in range (strongest
access point per name, the one in use first). Click a saved or open network to connect, a new
secured one to type its password in a field under it (Enter or Connect), the one in use to
disconnect, or "Forget" on a saved one. Opening the popup asks for a scan.
- compositor/network: NetworkManager over D-Bus through a small D-Bus client of our own
(wire format, EXTERNAL auth, async calls) on the existing @sys socket calls, so neither host
needed new imports. One ObjectManager.GetManagedObjects + GetAll every 2 s; GetSettings once
per saved connection; RequestScan, Device.Disconnect, WirelessEnabled / WwanEnabled,
ActivateConnection (saved), AddAndActivateConnection (new: open, WPA/WPA2 PSK, WPA3 SAE) and
Settings.Connection.Delete. Without NetworkManager it falls back to read-only status from
/proc/net/dev, /proc/net/wireless and /sys/class/net (no network names there), and looks for
NetworkManager again every 30 s.
- New `network` capability (wit/capabilities.wit): status, wifi-networks, scan, connect,
disconnect, forget, set-wifi-enabled, set-airplane-mode. Served from host tables 8/9 and a
`network(network-request)` request by the wasmer/wasmtime stub (compositor/wasm), host-wasm
and the MoonBit wasmhost. The stub's build_list learned bool fields; request strings are
wiped after use (Wi-Fi passwords).
- Running out of module instances now says "too many modules loaded".
- Deferred: VPN, hotspot, hidden networks, WEP and 802.1X (enterprise) networks, IP settings,
mobile broadband beyond the airplane switch, D-Bus signals (state is polled).
- Tests: D-Bus wire format (incl. the well-known Hello bytes), NetworkManager objects -> status
and list, security settings, /proc parsing; the module through the shell against a fake
backend (list, connect/forget/disconnect, password entry, switches, read-only); a host-wasm
test; and scripts/test-network-dbus.sh, which runs the backend against python-dbusmock's
NetworkManager on a private bus.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hizqNXcNDuef3gxa7D
This commit is contained in:
43 files changed
+4100
-31
No files matched your search
@@ -0,0 +1,82 @@
|
|||||||
|
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn mbt_ffi_cabi_realloc(
|
||||||
|
src_offset : Int,
|
||||||
|
src_size : Int,
|
||||||
|
_dst_alignment : Int,
|
||||||
|
dst_size : Int,
|
||||||
|
) -> Int {
|
||||||
|
// malloc
|
||||||
|
if src_offset == 0 && src_size == 0 {
|
||||||
|
return mbt_ffi_malloc(dst_size)
|
||||||
|
}
|
||||||
|
// free
|
||||||
|
if dst_size == 0 {
|
||||||
|
mbt_ffi_free(src_offset)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
// realloc
|
||||||
|
let dst = mbt_ffi_malloc(dst_size)
|
||||||
|
mbt_ffi_copy(dst, src_offset, if src_size < dst_size { src_size } else { dst_size })
|
||||||
|
mbt_ffi_free(src_offset)
|
||||||
|
dst
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_copy(dest : Int, src : Int, len : Int) =
|
||||||
|
#|(func (param i32) (param i32) (param i32) local.get 0 local.get 1 local.get 2 memory.copy)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
||||||
|
#|(func (param i32) (result i32) (local i32)
|
||||||
|
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
|
||||||
|
#| local.tee 1 i32.const 0 call $moonbit.init_array8
|
||||||
|
#| local.get 1)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_free(position : Int) =
|
||||||
|
#|(func (param i32) local.get 0 call $moonbit.decref)
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
|
||||||
|
@plasmoid.wasmExportInfoPostReturn(p0)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
|
||||||
|
@plasmoid.wasmExportRender(p0, p1)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportPopup() -> Int {
|
||||||
|
@plasmoid.wasmExportPopup()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
|
||||||
|
@plasmoid.wasmExportRenderPostReturn(p0)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
|
||||||
|
@plasmoid.wasmExportPopupPostReturn(p0)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
|
||||||
|
@plasmoid.wasmExportOnEvent(p0, p1, p2, p3)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportInfo() -> Int {
|
||||||
|
@plasmoid.wasmExportInfo()
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
The widget (plasmoid) contract.
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportInfo() -> Int {
|
||||||
|
|
||||||
|
let (result) : (PlasmoidInfo) = info();
|
||||||
|
let return_area = mbt_ffi_malloc(32)
|
||||||
|
|
||||||
|
let ptr = mbt_ffi_str2ptr((result).id)
|
||||||
|
mbt_ffi_store32((return_area) + 4, (result).id.length())
|
||||||
|
mbt_ffi_store32((return_area) + 0, ptr)
|
||||||
|
|
||||||
|
let ptr0 = mbt_ffi_str2ptr((result).name)
|
||||||
|
mbt_ffi_store32((return_area) + 12, (result).name.length())
|
||||||
|
mbt_ffi_store32((return_area) + 8, ptr0)
|
||||||
|
mbt_ffi_store32((return_area) + 16, (((result).preferred).w).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((return_area) + 20, (((result).preferred).h).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((return_area) + 24, ((result).min_width).reinterpret_as_int())
|
||||||
|
mbt_ffi_store8((return_area) + 28, (if (result).stretch { 1 } else { 0 }))
|
||||||
|
let ret = return_area
|
||||||
|
return ret
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportInfoPostReturn(p0 : Int) -> Unit {
|
||||||
|
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
|
||||||
|
mbt_ffi_free(mbt_ffi_load32((p0) + 8))
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportRender(p0 : Int, p1 : Int) -> Int {
|
||||||
|
|
||||||
|
let (result) : (Array[@types.DrawOp]) = render(@types.Size::{w : (p0).reinterpret_as_uint(), h : (p1).reinterpret_as_uint()});
|
||||||
|
let return_area = mbt_ffi_malloc(8)
|
||||||
|
|
||||||
|
let address = mbt_ffi_malloc((result).length() * 32);
|
||||||
|
for index = 0; index < (result).length(); index = index + 1 {
|
||||||
|
let iter_elem : @types.DrawOp = (result)[(index)]
|
||||||
|
let iter_base = address + (index * 32);
|
||||||
|
|
||||||
|
match iter_elem {
|
||||||
|
FillRect(payload) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (0))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload).rect).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload).rect).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, (((payload).rect).w).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 16, (((payload).rect).h).reinterpret_as_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 20, (((payload).color).r).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 21, (((payload).color).g).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 22, (((payload).color).b).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 23, (((payload).color).a).to_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 24, ((payload).radius).reinterpret_as_int())
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
StrokeRect(payload0) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (1))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload0).rect).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload0).rect).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, (((payload0).rect).w).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 16, (((payload0).rect).h).reinterpret_as_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 20, (((payload0).color).r).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 21, (((payload0).color).g).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 22, (((payload0).color).b).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 23, (((payload0).color).a).to_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 24, ((payload0).width).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 28, ((payload0).radius).reinterpret_as_int())
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
Line(payload1) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (2))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload1).start).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload1).start).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, ((payload1).end).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 16, ((payload1).end).y)
|
||||||
|
mbt_ffi_store8((iter_base) + 20, (((payload1).color).r).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 21, (((payload1).color).g).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 22, (((payload1).color).b).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 23, (((payload1).color).a).to_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 24, ((payload1).width).reinterpret_as_int())
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
Circle(payload2) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (3))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload2).center).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload2).center).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, ((payload2).radius).reinterpret_as_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 16, (((payload2).color).r).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 17, (((payload2).color).g).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 18, (((payload2).color).b).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 19, (((payload2).color).a).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 20, (if (payload2).filled { 1 } else { 0 }))
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
Text(payload3) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (4))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload3).origin).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload3).origin).y)
|
||||||
|
|
||||||
|
let ptr = mbt_ffi_str2ptr((payload3).text)
|
||||||
|
mbt_ffi_store32((iter_base) + 16, (payload3).text.length())
|
||||||
|
mbt_ffi_store32((iter_base) + 12, ptr)
|
||||||
|
mbt_ffi_store32((iter_base) + 20, (((payload3).style).size).reinterpret_as_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 24, ((((payload3).style).color).r).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 25, ((((payload3).style).color).g).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 26, ((((payload3).style).color).b).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 27, ((((payload3).style).color).a).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 28, ((payload3).style).align.ordinal())
|
||||||
|
mbt_ffi_store8((iter_base) + 29, (if ((payload3).style).bold { 1 } else { 0 }))
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
PushClip(payload4) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (5))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, (payload4).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, (payload4).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, ((payload4).w).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 16, ((payload4).h).reinterpret_as_int())
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
PopClip => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (6))
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
Image(payload6) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (7))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload6).rect).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload6).rect).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, (((payload6).rect).w).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 16, (((payload6).rect).h).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 20, ((payload6).image).reinterpret_as_int())
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
mbt_ffi_store32((return_area) + 4, (result).length())
|
||||||
|
mbt_ffi_store32((return_area) + 0, address)
|
||||||
|
let ret = return_area
|
||||||
|
return ret
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportRenderPostReturn(p0 : Int) -> Unit {
|
||||||
|
|
||||||
|
for index = 0; index < (mbt_ffi_load32((p0) + 4)); index = index + 1 {
|
||||||
|
let iter_base = (mbt_ffi_load32((p0) + 0)) + (index * 32)
|
||||||
|
|
||||||
|
match (mbt_ffi_load8_u((iter_base) + 0)) {
|
||||||
|
0 => ()
|
||||||
|
1 => ()
|
||||||
|
2 => ()
|
||||||
|
3 => ()
|
||||||
|
4 => {
|
||||||
|
mbt_ffi_free(mbt_ffi_load32((iter_base) + 12))
|
||||||
|
|
||||||
|
}
|
||||||
|
5 => ()
|
||||||
|
6 => ()
|
||||||
|
7 => ()
|
||||||
|
_ => panic()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
mbt_ffi_free(mbt_ffi_load32((p0) + 0))
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportPopup() -> Int {
|
||||||
|
|
||||||
|
let (result) : (PopupSurface?) = popup();
|
||||||
|
let return_area = mbt_ffi_malloc(20)
|
||||||
|
|
||||||
|
match (result) {
|
||||||
|
None => {
|
||||||
|
mbt_ffi_store8((return_area) + 0, (0))
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
Some(payload0) => {
|
||||||
|
mbt_ffi_store8((return_area) + 0, (1))
|
||||||
|
mbt_ffi_store32((return_area) + 4, (((payload0).size).w).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((return_area) + 8, (((payload0).size).h).reinterpret_as_int())
|
||||||
|
|
||||||
|
let address = mbt_ffi_malloc(((payload0).ops).length() * 32);
|
||||||
|
for index = 0; index < ((payload0).ops).length(); index = index + 1 {
|
||||||
|
let iter_elem : @types.DrawOp = ((payload0).ops)[(index)]
|
||||||
|
let iter_base = address + (index * 32);
|
||||||
|
|
||||||
|
match iter_elem {
|
||||||
|
FillRect(payload1) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (0))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload1).rect).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload1).rect).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, (((payload1).rect).w).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 16, (((payload1).rect).h).reinterpret_as_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 20, (((payload1).color).r).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 21, (((payload1).color).g).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 22, (((payload1).color).b).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 23, (((payload1).color).a).to_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 24, ((payload1).radius).reinterpret_as_int())
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
StrokeRect(payload2) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (1))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload2).rect).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload2).rect).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, (((payload2).rect).w).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 16, (((payload2).rect).h).reinterpret_as_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 20, (((payload2).color).r).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 21, (((payload2).color).g).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 22, (((payload2).color).b).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 23, (((payload2).color).a).to_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 24, ((payload2).width).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 28, ((payload2).radius).reinterpret_as_int())
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
Line(payload3) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (2))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload3).start).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload3).start).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, ((payload3).end).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 16, ((payload3).end).y)
|
||||||
|
mbt_ffi_store8((iter_base) + 20, (((payload3).color).r).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 21, (((payload3).color).g).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 22, (((payload3).color).b).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 23, (((payload3).color).a).to_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 24, ((payload3).width).reinterpret_as_int())
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
Circle(payload4) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (3))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload4).center).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload4).center).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, ((payload4).radius).reinterpret_as_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 16, (((payload4).color).r).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 17, (((payload4).color).g).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 18, (((payload4).color).b).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 19, (((payload4).color).a).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 20, (if (payload4).filled { 1 } else { 0 }))
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
Text(payload5) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (4))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload5).origin).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload5).origin).y)
|
||||||
|
|
||||||
|
let ptr = mbt_ffi_str2ptr((payload5).text)
|
||||||
|
mbt_ffi_store32((iter_base) + 16, (payload5).text.length())
|
||||||
|
mbt_ffi_store32((iter_base) + 12, ptr)
|
||||||
|
mbt_ffi_store32((iter_base) + 20, (((payload5).style).size).reinterpret_as_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 24, ((((payload5).style).color).r).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 25, ((((payload5).style).color).g).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 26, ((((payload5).style).color).b).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 27, ((((payload5).style).color).a).to_int())
|
||||||
|
mbt_ffi_store8((iter_base) + 28, ((payload5).style).align.ordinal())
|
||||||
|
mbt_ffi_store8((iter_base) + 29, (if ((payload5).style).bold { 1 } else { 0 }))
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
PushClip(payload6) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (5))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, (payload6).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, (payload6).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, ((payload6).w).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 16, ((payload6).h).reinterpret_as_int())
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
PopClip => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (6))
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
Image(payload8) => {
|
||||||
|
mbt_ffi_store8((iter_base) + 0, (7))
|
||||||
|
mbt_ffi_store32((iter_base) + 4, ((payload8).rect).x)
|
||||||
|
mbt_ffi_store32((iter_base) + 8, ((payload8).rect).y)
|
||||||
|
mbt_ffi_store32((iter_base) + 12, (((payload8).rect).w).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 16, (((payload8).rect).h).reinterpret_as_int())
|
||||||
|
mbt_ffi_store32((iter_base) + 20, ((payload8).image).reinterpret_as_int())
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
mbt_ffi_store32((return_area) + 16, ((payload0).ops).length())
|
||||||
|
mbt_ffi_store32((return_area) + 12, address)
|
||||||
|
|
||||||
|
()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let ret = return_area
|
||||||
|
return ret
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportPopupPostReturn(p0 : Int) -> Unit {
|
||||||
|
|
||||||
|
match (mbt_ffi_load8_u((p0) + 0)) {
|
||||||
|
0 => ()
|
||||||
|
1 => {
|
||||||
|
|
||||||
|
for index = 0; index < (mbt_ffi_load32((p0) + 16)); index = index + 1 {
|
||||||
|
let iter_base = (mbt_ffi_load32((p0) + 12)) + (index * 32)
|
||||||
|
|
||||||
|
match (mbt_ffi_load8_u((iter_base) + 0)) {
|
||||||
|
0 => ()
|
||||||
|
1 => ()
|
||||||
|
2 => ()
|
||||||
|
3 => ()
|
||||||
|
4 => {
|
||||||
|
mbt_ffi_free(mbt_ffi_load32((iter_base) + 12))
|
||||||
|
|
||||||
|
}
|
||||||
|
5 => ()
|
||||||
|
6 => ()
|
||||||
|
7 => ()
|
||||||
|
_ => panic()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
mbt_ffi_free(mbt_ffi_load32((p0) + 12))
|
||||||
|
|
||||||
|
}
|
||||||
|
_ => panic()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
#doc(hidden)
|
||||||
|
pub fn wasmExportOnEvent(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
|
||||||
|
|
||||||
|
let lifted = match (p1) {
|
||||||
|
0 => {
|
||||||
|
|
||||||
|
@types.InputEvent::PointerMove(@types.Point::{x : p2, y : p3})
|
||||||
|
}
|
||||||
|
1 => {
|
||||||
|
|
||||||
|
@types.InputEvent::PointerDown(@types.Point::{x : p2, y : p3})
|
||||||
|
}
|
||||||
|
2 => {
|
||||||
|
|
||||||
|
@types.InputEvent::PointerUp(@types.Point::{x : p2, y : p3})
|
||||||
|
}
|
||||||
|
3 => {
|
||||||
|
|
||||||
|
@types.InputEvent::PointerLeave
|
||||||
|
}
|
||||||
|
4 => {
|
||||||
|
|
||||||
|
@types.InputEvent::FocusLost
|
||||||
|
}
|
||||||
|
5 => {
|
||||||
|
|
||||||
|
let result = mbt_ffi_ptr2str(p2, p3)
|
||||||
|
|
||||||
|
@types.InputEvent::KeyDown(result)
|
||||||
|
}
|
||||||
|
_ => panic()
|
||||||
|
}
|
||||||
|
|
||||||
|
let (result0) : (Bool) = on_event(Surface::from(p0), lifted);
|
||||||
|
let ret = (if result0 { 1 } else { 0 })
|
||||||
|
return ret
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
|
||||||
|
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_free(position : Int) =
|
||||||
|
#|(func (param i32) local.get 0 call $moonbit.decref)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
|
||||||
|
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
||||||
|
#|(func (param i32) (result i32) (local i32)
|
||||||
|
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
|
||||||
|
#| local.tee 1 i32.const 0 call $moonbit.init_array8
|
||||||
|
#| local.get 1)
|
||||||
|
|
||||||
|
///|
|
||||||
|
#owned(str)
|
||||||
|
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
|
||||||
|
#|(func (param i32) (result i32) local.get 0)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
|
||||||
|
#|(func (param i32) (result i32) local.get 0 i32.load)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
|
||||||
|
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
|
||||||
|
#|(func (param i32) (param i32) (result i32)
|
||||||
|
#| local.get 0
|
||||||
|
#| local.get 1 call $moonbit.init_array16
|
||||||
|
#| local.get 0)
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import {
|
||||||
|
"chandra/desktop/interface/chandra/desktop/types" @types,
|
||||||
|
"chandra/desktop/interface/chandra/desktop/theme" @theme,
|
||||||
|
"chandra/desktop/interface/chandra/desktop/network" @net,
|
||||||
|
"chandra/desktop/lib/ui" @ui,
|
||||||
|
}
|
||||||
|
|
||||||
|
warnings = "-44"
|
||||||
@@ -0,0 +1,481 @@
|
|||||||
|
///| Implementation of `chandra:desktop/plasmoid` for the network module. The panel button shows the
|
||||||
|
/// connection: Wi-Fi signal bars and the network's name, a plug for a wired connection, crossed-out
|
||||||
|
/// bars offline or in airplane mode. A click opens a popup with the status (and the outcome of the
|
||||||
|
/// last action), switches for Wi-Fi and airplane mode, and the Wi-Fi networks in range: click one to
|
||||||
|
/// connect (a saved or open network at once; a new secured one asks for its password in a field
|
||||||
|
/// that opens under it), click the one in use to disconnect, or "Forget" a saved one. Opening the
|
||||||
|
/// popup asks for a scan. All of it goes through the `network` capability; without NetworkManager
|
||||||
|
/// the popup only shows the status. Up/Down move the highlight, Enter picks, Escape closes.
|
||||||
|
|
||||||
|
///| One popup row.
|
||||||
|
priv enum Row {
|
||||||
|
Status
|
||||||
|
Message(String)
|
||||||
|
WifiSwitch(Bool)
|
||||||
|
AirplaneSwitch(Bool)
|
||||||
|
Heading(String)
|
||||||
|
Network(@net.WifiNetwork)
|
||||||
|
Password
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Popup geometry.
|
||||||
|
let popup_w : Int = 320
|
||||||
|
|
||||||
|
///|
|
||||||
|
let row_h : Int = 30
|
||||||
|
|
||||||
|
///|
|
||||||
|
let margin : Int = 6
|
||||||
|
|
||||||
|
///| The most networks listed.
|
||||||
|
let max_networks : Int = 10
|
||||||
|
|
||||||
|
///| Width of the "Forget" / "Disconnect" zone at the right of a network row.
|
||||||
|
let action_w : Int = 84
|
||||||
|
|
||||||
|
///|
|
||||||
|
let open_ : Ref[Bool] = { val: false }
|
||||||
|
|
||||||
|
///| The highlighted row, by `row_key` ("" for none: rows come and go as networks do), and where
|
||||||
|
/// the pointer is in it.
|
||||||
|
let hover_key : Ref[String] = { val: "" }
|
||||||
|
|
||||||
|
///|
|
||||||
|
let hover_x : Ref[Int] = { val: 0 }
|
||||||
|
|
||||||
|
///| The secured network whose password is being typed ("" for none), and the password so far.
|
||||||
|
let entering : Ref[String] = { val: "" }
|
||||||
|
|
||||||
|
///|
|
||||||
|
let password : Ref[String] = { val: "" }
|
||||||
|
|
||||||
|
///| The popup's rows for the current state.
|
||||||
|
fn rows() -> Array[Row] {
|
||||||
|
let s = @net.status()
|
||||||
|
let out : Array[Row] = [Status]
|
||||||
|
if s.message != "" {
|
||||||
|
out.push(Message(s.message))
|
||||||
|
}
|
||||||
|
if !s.can_manage {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
if s.has_wifi {
|
||||||
|
out.push(WifiSwitch(s.wifi_enabled))
|
||||||
|
}
|
||||||
|
out.push(AirplaneSwitch(s.airplane))
|
||||||
|
if s.has_wifi && s.wifi_enabled {
|
||||||
|
let nets = @net.wifi_networks()
|
||||||
|
out.push(Heading(if nets.length() == 0 { "Looking for networks..." } else { "Wi-Fi networks" }))
|
||||||
|
for i = 0; i < nets.length() && i < max_networks; i = i + 1 {
|
||||||
|
out.push(Network(nets[i]))
|
||||||
|
if nets[i].ssid == entering.val {
|
||||||
|
out.push(Password)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
///| What identifies a row across frames.
|
||||||
|
fn row_key(r : Row) -> String {
|
||||||
|
match r {
|
||||||
|
Status => "status"
|
||||||
|
Message(_) => "message"
|
||||||
|
WifiSwitch(_) => "wifi"
|
||||||
|
AirplaneSwitch(_) => "airplane"
|
||||||
|
Heading(_) => "heading"
|
||||||
|
Network(n) => "net:" + n.ssid
|
||||||
|
Password => "password"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Index of the highlighted row in `rs`, or -1.
|
||||||
|
fn hover_index(rs : Array[Row]) -> Int {
|
||||||
|
for i = 0; i < rs.length(); i = i + 1 {
|
||||||
|
if hover_key.val != "" && row_key(rs[i]) == hover_key.val {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
-1
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn set_hover(rs : Array[Row], i : Int) -> Unit {
|
||||||
|
hover_key.val = if i >= 0 && i < rs.length() { row_key(rs[i]) } else { "" }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn popup_h(n : Int) -> Int {
|
||||||
|
margin * 2 + n * row_h
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Whether row `r` can be picked.
|
||||||
|
fn pickable(r : Row) -> Bool {
|
||||||
|
match r {
|
||||||
|
WifiSwitch(_) | AirplaneSwitch(_) | Network(_) | Password => true
|
||||||
|
_ => false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Row under a popup-local point, or -1.
|
||||||
|
fn row_at(rs : Array[Row], x : Int, y : Int) -> Int {
|
||||||
|
if x < margin || x >= popup_w - margin || y < margin {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
let i = (y - margin) / row_h
|
||||||
|
if i < rs.length() && pickable(rs[i]) { i } else { -1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn clear_entry() -> Unit {
|
||||||
|
entering.val = ""
|
||||||
|
password.val = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn close() -> Unit {
|
||||||
|
open_.val = false
|
||||||
|
hover_key.val = ""
|
||||||
|
clear_entry()
|
||||||
|
}
|
||||||
|
|
||||||
|
///| What a 0..100 signal is in bars (1-4).
|
||||||
|
fn bars_of(signal : Int) -> Int {
|
||||||
|
if signal >= 75 {
|
||||||
|
4
|
||||||
|
} else if signal >= 50 {
|
||||||
|
3
|
||||||
|
} else if signal >= 25 {
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Four signal bars, bottom-aligned at `by`, `lit` of them in `on`, the rest in `off`.
|
||||||
|
fn bars(x : Int, by : Int, lit : Int, on : @types.Color, off : @types.Color) -> Array[@types.DrawOp] {
|
||||||
|
let ops : Array[@types.DrawOp] = []
|
||||||
|
for i = 0; i < 4; i = i + 1 {
|
||||||
|
let h = 4 + i * 3
|
||||||
|
ops.push(@ui.fill_rect(@ui.rect(x + i * 5, by - h, 3, h), if i < lit { on } else { off }, radius=1))
|
||||||
|
}
|
||||||
|
ops
|
||||||
|
}
|
||||||
|
|
||||||
|
///| An Ethernet plug centred on (cx, cy).
|
||||||
|
fn plug(cx : Int, cy : Int, c : @types.Color) -> Array[@types.DrawOp] {
|
||||||
|
[
|
||||||
|
@ui.stroke_rect(@ui.rect(cx - 6, cy - 6, 12, 9), c, width=1, radius=1),
|
||||||
|
@ui.fill_rect(@ui.rect(cx - 3, cy - 3, 2, 3), c),
|
||||||
|
@ui.fill_rect(@ui.rect(cx + 1, cy - 3, 2, 3), c),
|
||||||
|
@ui.line(cx, cy + 3, cx, cy + 7, c, width=2),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The connection's icon centred on (cx, cy).
|
||||||
|
fn status_icon(s : @net.NetStatus, cx : Int, cy : Int, fg : @types.Color) -> Array[@types.DrawOp] {
|
||||||
|
let dim = @ui.with_alpha(fg, 70)
|
||||||
|
match s.state {
|
||||||
|
1 => plug(cx, cy, fg)
|
||||||
|
2 => bars(cx - 9, cy + 7, bars_of(s.signal.reinterpret_as_int()), fg, dim)
|
||||||
|
3 => bars(cx - 9, cy + 7, 0, fg, @ui.with_alpha(fg, 140))
|
||||||
|
_ => {
|
||||||
|
let ops = bars(cx - 9, cy + 7, 0, fg, dim)
|
||||||
|
ops.push(@ui.line(cx - 9, cy + 7, cx + 9, cy - 7, fg, width=2))
|
||||||
|
ops
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| What the button says.
|
||||||
|
fn label(s : @net.NetStatus) -> String {
|
||||||
|
match s.state {
|
||||||
|
1 => "Wired"
|
||||||
|
2 => s.name
|
||||||
|
3 => "Connecting"
|
||||||
|
_ => if s.airplane { "Airplane mode" } else { "Offline" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The popup's status line.
|
||||||
|
fn status_line(s : @net.NetStatus) -> String {
|
||||||
|
match s.state {
|
||||||
|
1 => if s.name == "" { "Wired" } else { "Wired: " + s.name }
|
||||||
|
2 => "Connected to " + s.name + " (" + s.signal.to_string() + "%)"
|
||||||
|
3 => if s.name == "" { "Connecting..." } else { "Connecting to " + s.name + "..." }
|
||||||
|
_ => if s.airplane { "Airplane mode" } else { "Not connected" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| `s` cut to fit `w` pixels at font size `fs`.
|
||||||
|
fn fit(s : String, w : Int, fs : Int) -> String {
|
||||||
|
let cw = (fs * 6 + 9) / 10
|
||||||
|
let n = if cw > 0 { w / cw } else { s.length() }
|
||||||
|
if s.length() <= n {
|
||||||
|
s
|
||||||
|
} else if n <= 1 {
|
||||||
|
""
|
||||||
|
} else {
|
||||||
|
s[:n - 1].to_string() + "…"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn info() -> PlasmoidInfo {
|
||||||
|
{
|
||||||
|
id: "org.chandra.network",
|
||||||
|
name: "Network",
|
||||||
|
preferred: { w: 130, h: 34 },
|
||||||
|
min_width: 34,
|
||||||
|
stretch: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn render(size : @types.Size) -> Array[@types.DrawOp] {
|
||||||
|
let t = @theme.get_tokens()
|
||||||
|
let w = size.w.reinterpret_as_int()
|
||||||
|
let h = size.h.reinterpret_as_int()
|
||||||
|
let r = t.radius.reinterpret_as_int()
|
||||||
|
let fs = t.font_size.reinterpret_as_int()
|
||||||
|
let bg = if open_.val { t.palette.accent } else { t.palette.surface_hover }
|
||||||
|
let fg = if open_.val { t.palette.accent_foreground } else { t.palette.foreground }
|
||||||
|
let s = @net.status()
|
||||||
|
let ops = [@ui.fill_rect(@ui.rect(0, 0, w, h), bg, radius=r)]
|
||||||
|
ops.append(status_icon(s, 17, h / 2, fg))
|
||||||
|
if w >= 70 {
|
||||||
|
ops.push(@ui.text(32, h / 2, fit(label(s), w - 38, fs - 2), fs - 2, fg))
|
||||||
|
}
|
||||||
|
ops
|
||||||
|
}
|
||||||
|
|
||||||
|
///| A switch at the right of a row whose middle is `mid`.
|
||||||
|
fn switch(w : Int, mid : Int, on : Bool, p : @theme.Palette) -> Array[@types.DrawOp] {
|
||||||
|
let sw = 34
|
||||||
|
let sh = 18
|
||||||
|
let sx = w - margin - 10 - sw
|
||||||
|
let sy = mid - sh / 2
|
||||||
|
let knob = sh / 2 - 3
|
||||||
|
if on {
|
||||||
|
[
|
||||||
|
@ui.fill_rect(@ui.rect(sx, sy, sw, sh), p.accent, radius=sh / 2),
|
||||||
|
@ui.circle(sx + sw - sh / 2, mid, knob, p.accent_foreground),
|
||||||
|
]
|
||||||
|
} else {
|
||||||
|
[
|
||||||
|
@ui.stroke_rect(@ui.rect(sx, sy, sw, sh), p.foreground_muted, width=1, radius=sh / 2),
|
||||||
|
@ui.circle(sx + sh / 2, mid, knob, p.foreground_muted),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn popup() -> PopupSurface? {
|
||||||
|
if !open_.val {
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let t = @theme.get_tokens()
|
||||||
|
let rs = rows()
|
||||||
|
let w = popup_w
|
||||||
|
let h = popup_h(rs.length())
|
||||||
|
let r = t.radius.reinterpret_as_int()
|
||||||
|
let fs = t.font_size.reinterpret_as_int()
|
||||||
|
let p = t.palette
|
||||||
|
let s = @net.status()
|
||||||
|
let hi = hover_index(rs)
|
||||||
|
let ops : Array[@types.DrawOp] = [
|
||||||
|
@ui.fill_rect(@ui.rect(0, 0, w, h), p.surface_popup, radius=r),
|
||||||
|
@ui.stroke_rect(@ui.rect(0, 0, w, h), p.border, width=1, radius=r),
|
||||||
|
]
|
||||||
|
for i = 0; i < rs.length(); i = i + 1 {
|
||||||
|
let y = margin + i * row_h
|
||||||
|
let mid = y + (row_h - 2) / 2
|
||||||
|
let hovered = i == hi
|
||||||
|
if hovered && pickable(rs[i]) && !(rs[i] is Password) {
|
||||||
|
ops.push(@ui.fill_rect(@ui.rect(margin, y, w - 2 * margin, row_h - 2), p.surface_hover, radius=r))
|
||||||
|
}
|
||||||
|
match rs[i] {
|
||||||
|
Status => {
|
||||||
|
ops.append(status_icon(s, margin + 17, mid, p.foreground))
|
||||||
|
ops.push(@ui.text(margin + 34, mid, fit(status_line(s), w - 2 * margin - 40, fs - 1), fs - 1, p.foreground, bold=true))
|
||||||
|
}
|
||||||
|
Message(m) => ops.push(@ui.text(margin + 34, mid, fit(m, w - 2 * margin - 40, fs - 3), fs - 3, p.foreground_muted))
|
||||||
|
WifiSwitch(on) => {
|
||||||
|
ops.push(@ui.text(margin + 18, mid, "Wi-Fi", fs - 1, p.foreground))
|
||||||
|
ops.append(switch(w, mid, on, p))
|
||||||
|
}
|
||||||
|
AirplaneSwitch(on) => {
|
||||||
|
ops.push(@ui.text(margin + 18, mid, "Airplane mode", fs - 1, p.foreground))
|
||||||
|
ops.append(switch(w, mid, on, p))
|
||||||
|
}
|
||||||
|
Heading(text) => ops.push(@ui.text(margin + 8, mid + 2, text, fs - 3, p.foreground_muted, bold=true))
|
||||||
|
Network(n) => {
|
||||||
|
let lit = bars_of(n.signal.reinterpret_as_int())
|
||||||
|
ops.append(bars(margin + 10, mid + 6, lit, p.foreground, @ui.with_alpha(p.foreground, 70)))
|
||||||
|
let right = if n.active && hovered {
|
||||||
|
"Disconnect"
|
||||||
|
} else if n.active {
|
||||||
|
"Connected"
|
||||||
|
} else if n.saved && hovered && hover_x.val >= w - margin - action_w {
|
||||||
|
"Forget"
|
||||||
|
} else if n.saved {
|
||||||
|
"Saved"
|
||||||
|
} else if n.secured {
|
||||||
|
"Secured"
|
||||||
|
} else {
|
||||||
|
"Open"
|
||||||
|
}
|
||||||
|
ops.push(@ui.text(margin + 36, mid, fit(n.ssid, w - 2 * margin - 36 - action_w, fs - 1), fs - 1, p.foreground, bold=n.active))
|
||||||
|
ops.push(@ui.text(w - margin - 10, mid, right, fs - 3, if right == "Forget" || right == "Disconnect" { p.accent } else { p.foreground_muted }, align=RIGHT))
|
||||||
|
}
|
||||||
|
Password => {
|
||||||
|
let bx = margin + 36
|
||||||
|
let bw = w - 2 * margin - 36 - action_w
|
||||||
|
ops.push(@ui.fill_rect(@ui.rect(bx, y + 2, bw, row_h - 6), p.surface, radius=r))
|
||||||
|
ops.push(@ui.stroke_rect(@ui.rect(bx, y + 2, bw, row_h - 6), p.accent, width=1, radius=r))
|
||||||
|
let shown = if password.val == "" {
|
||||||
|
"Password"
|
||||||
|
} else {
|
||||||
|
let sb = StringBuilder::new()
|
||||||
|
for _ in password.val {
|
||||||
|
sb.write_char('•')
|
||||||
|
}
|
||||||
|
sb.to_string()
|
||||||
|
}
|
||||||
|
let fg = if password.val == "" { p.foreground_muted } else { p.foreground }
|
||||||
|
ops.push(@ui.text(bx + 8, mid, fit(shown, bw - 16, fs - 2) + "|", fs - 2, fg))
|
||||||
|
let cx = w - margin - action_w + 6
|
||||||
|
ops.push(@ui.fill_rect(@ui.rect(cx, y + 2, action_w - 16, row_h - 6), p.accent, radius=r))
|
||||||
|
ops.push(@ui.text(cx + (action_w - 16) / 2, mid, "Connect", fs - 3, p.accent_foreground, align=CENTER))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some({ size: { w: w.reinterpret_as_uint(), h: h.reinterpret_as_uint() }, ops })
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Connect to the network whose password is being typed.
|
||||||
|
fn submit_password() -> Unit {
|
||||||
|
if entering.val != "" && password.val != "" {
|
||||||
|
@net.connect(entering.val, password.val)
|
||||||
|
clear_entry()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Carry out row `i` (`x`: where in it, popup-local).
|
||||||
|
fn pick(rs : Array[Row], i : Int, x : Int) -> Unit {
|
||||||
|
if i < 0 || i >= rs.length() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
match rs[i] {
|
||||||
|
WifiSwitch(on) => @net.set_wifi_enabled(!on)
|
||||||
|
AirplaneSwitch(on) => @net.set_airplane_mode(!on)
|
||||||
|
Network(n) =>
|
||||||
|
if n.active {
|
||||||
|
@net.disconnect()
|
||||||
|
} else if n.saved && x >= popup_w - margin - action_w {
|
||||||
|
@net.forget(n.ssid)
|
||||||
|
} else if n.saved || !n.secured {
|
||||||
|
clear_entry()
|
||||||
|
@net.connect(n.ssid, "")
|
||||||
|
} else if entering.val == n.ssid {
|
||||||
|
clear_entry()
|
||||||
|
} else {
|
||||||
|
entering.val = n.ssid
|
||||||
|
password.val = ""
|
||||||
|
}
|
||||||
|
Password => if x >= popup_w - margin - action_w { submit_password() }
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The next pickable row from `i` in direction `d`, or `i` when there is none.
|
||||||
|
fn step(rs : Array[Row], i : Int, d : Int) -> Int {
|
||||||
|
let mut j = i + d
|
||||||
|
while j >= 0 && j < rs.length() {
|
||||||
|
if pickable(rs[j]) {
|
||||||
|
return j
|
||||||
|
}
|
||||||
|
j = j + d
|
||||||
|
}
|
||||||
|
i
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool {
|
||||||
|
match (target, event) {
|
||||||
|
(WIDGET, PointerDown(_)) => {
|
||||||
|
if open_.val {
|
||||||
|
close()
|
||||||
|
} else {
|
||||||
|
open_.val = true
|
||||||
|
hover_key.val = ""
|
||||||
|
@net.scan()
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
(POPUP, PointerMove(p)) => {
|
||||||
|
let rs = rows()
|
||||||
|
let i = row_at(rs, p.x, p.y)
|
||||||
|
let zone = fn(x : Int) { x >= popup_w - margin - action_w }
|
||||||
|
let changed = i != hover_index(rs) || (i >= 0 && zone(p.x) != zone(hover_x.val))
|
||||||
|
set_hover(rs, i)
|
||||||
|
hover_x.val = p.x
|
||||||
|
changed
|
||||||
|
}
|
||||||
|
(POPUP, PointerDown(p)) => {
|
||||||
|
let rs = rows()
|
||||||
|
let i = row_at(rs, p.x, p.y)
|
||||||
|
if i >= 0 {
|
||||||
|
set_hover(rs, i)
|
||||||
|
hover_x.val = p.x
|
||||||
|
pick(rs, i, p.x)
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
(_, FocusLost) =>
|
||||||
|
if open_.val {
|
||||||
|
close()
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
(_, KeyDown(k)) =>
|
||||||
|
if !open_.val {
|
||||||
|
false
|
||||||
|
} else if entering.val != "" {
|
||||||
|
// Typing a password.
|
||||||
|
if k == "Escape" {
|
||||||
|
clear_entry()
|
||||||
|
} else if k == "Enter" {
|
||||||
|
submit_password()
|
||||||
|
} else if k == "Backspace" {
|
||||||
|
if password.val.length() > 0 {
|
||||||
|
password.val = password.val[:password.val.length() - 1].to_string()
|
||||||
|
}
|
||||||
|
} else if k == "Space" {
|
||||||
|
password.val = password.val + " "
|
||||||
|
} else if k.length() == 1 && password.val.length() < 63 {
|
||||||
|
password.val = password.val + k
|
||||||
|
}
|
||||||
|
true
|
||||||
|
} else if k == "Escape" {
|
||||||
|
close()
|
||||||
|
true
|
||||||
|
} else if k == "Enter" || k == " " || k == "Space" {
|
||||||
|
let rs = rows()
|
||||||
|
pick(rs, hover_index(rs), margin + 10)
|
||||||
|
true
|
||||||
|
} else if k == "ArrowDown" || k == "Down" {
|
||||||
|
let rs = rows()
|
||||||
|
set_hover(rs, step(rs, hover_index(rs), 1))
|
||||||
|
true
|
||||||
|
} else if k == "ArrowUp" || k == "Up" {
|
||||||
|
let rs = rows()
|
||||||
|
set_hover(rs, step(rs, hover_index(rs), -1))
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
_ => false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||||
|
///|
|
||||||
|
pub(all) struct PlasmoidInfo {
|
||||||
|
id : String; name : String; preferred : @types.Size; min_width : UInt; stretch : Bool
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
pub(all) struct PopupSurface {
|
||||||
|
size : @types.Size; ops : Array[@types.DrawOp]
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
pub(all) enum Surface {
|
||||||
|
WIDGET; POPUP
|
||||||
|
} derive()
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn Surface::ordinal(self : Surface) -> Int {
|
||||||
|
match self {
|
||||||
|
WIDGET => 0
|
||||||
|
POPUP => 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn Surface::from(self : Int) -> Surface {
|
||||||
|
match self {
|
||||||
|
0 => WIDGET
|
||||||
|
1 => POPUP
|
||||||
|
_ => panic()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
declare pub fn info() -> PlasmoidInfo
|
||||||
|
///|
|
||||||
|
/// Draw the widget into a `size` box (local coordinates).
|
||||||
|
declare pub fn render(size : @types.Size) -> Array[@types.DrawOp]
|
||||||
|
///|
|
||||||
|
/// Present when the widget wants a popup surface (e.g. a launcher menu).
|
||||||
|
declare pub fn popup() -> PopupSurface?
|
||||||
|
///|
|
||||||
|
/// Returns true when the widget's visuals changed and a redraw is needed.
|
||||||
|
declare pub fn on_event(target : Surface, event : @types.InputEvent) -> Bool
|
||||||
|
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import {
|
||||||
|
"chandra/desktop/components/network/gen/interface/chandra/desktop/plasmoid" @plasmoid,
|
||||||
|
}
|
||||||
|
|
||||||
|
warnings = "-44"
|
||||||
|
|
||||||
|
pkgtype(kind: "foreign_library")
|
||||||
|
|
||||||
|
options(
|
||||||
|
link: {
|
||||||
|
"wasm": {
|
||||||
|
"export-memory-name": "memory",
|
||||||
|
"heap-start-address": 16,
|
||||||
|
"exports": [
|
||||||
|
"mbt_ffi_cabi_realloc:cabi_realloc",
|
||||||
|
"wasmExportInfo:chandra:desktop/plasmoid@0.1.0#info",
|
||||||
|
"wasmExportInfoPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#info",
|
||||||
|
"wasmExportOnEvent:chandra:desktop/plasmoid@0.1.0#on-event",
|
||||||
|
"wasmExportPopup:chandra:desktop/plasmoid@0.1.0#popup",
|
||||||
|
"wasmExportPopupPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#popup",
|
||||||
|
"wasmExportRender:chandra:desktop/plasmoid@0.1.0#render",
|
||||||
|
"wasmExportRenderPostReturn:cabi_post_chandra:desktop/plasmoid@0.1.0#render"
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
// Generated using `moon info`, DON'T EDIT IT
|
||||||
|
package "chandra/desktop/components/network/gen"
|
||||||
|
|
||||||
|
// Values
|
||||||
|
pub fn mbt_ffi_cabi_realloc(Int32, Int32, Int32, Int32) -> Int32
|
||||||
|
|
||||||
|
// Errors
|
||||||
|
|
||||||
|
// Types and methods
|
||||||
|
|
||||||
|
// Type aliases
|
||||||
|
|
||||||
|
// Traits
|
||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
"chandra/desktop/compositor/renderer" @renderer,
|
"chandra/desktop/compositor/renderer" @renderer,
|
||||||
"chandra/desktop/compositor/wayland" @wayland,
|
"chandra/desktop/compositor/wayland" @wayland,
|
||||||
"chandra/desktop/compositor/gfx" @gfx,
|
"chandra/desktop/compositor/gfx" @gfx,
|
||||||
|
"chandra/desktop/compositor/network" @network,
|
||||||
}
|
}
|
||||||
|
|
||||||
supported_targets = "+native+wasm"
|
supported_targets = "+native+wasm"
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
///| The network panel module (components/network) driven through the shell, against a fake
|
||||||
|
/// network backend: the status it shows, its Wi-Fi list, and the actions its clicks and keys ask
|
||||||
|
/// for. Needs the modules: run scripts/build-modules.sh.
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn net_status() -> @network.NetStatus {
|
||||||
|
{
|
||||||
|
state: Wifi,
|
||||||
|
name: "Home",
|
||||||
|
signal: 72,
|
||||||
|
message: "",
|
||||||
|
wifi_enabled: true,
|
||||||
|
airplane: false,
|
||||||
|
managed: true,
|
||||||
|
has_wifi: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn net_comp(tag : String) -> (@host.ChandraCompositor, @network.FakeNet) {
|
||||||
|
let comp = new_comp(tag)
|
||||||
|
let fake = @network.FakeNet::new(net_status(), [
|
||||||
|
{ ssid: "Home", signal: 72, secured: true, active: true, saved: true },
|
||||||
|
{ ssid: "Office", signal: 55, secured: true, active: false, saved: false },
|
||||||
|
{ ssid: "Cafe", signal: 30, secured: false, active: false, saved: false },
|
||||||
|
{ ssid: "Lab", signal: 20, secured: true, active: false, saved: true },
|
||||||
|
])
|
||||||
|
comp.shell.set_network_backend(fake as &@network.NetBackend)
|
||||||
|
ignore(comp.compose_frame())
|
||||||
|
(comp, fake)
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The middle of popup row `i` (6 px margin, 30 px rows), `dx` from its left edge.
|
||||||
|
fn net_row(comp : @host.ChandraCompositor, i : Int, dx? : Int = 60) -> (Int, Int) {
|
||||||
|
let pr = comp.shell.slot_popup_rect(comp.shell.slot_of("network"))
|
||||||
|
(pr.x + dx, pr.y + 6 + i * 30 + 14)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn click_row(comp : @host.ChandraCompositor, i : Int, t : UInt, dx? : Int = 60) -> Unit {
|
||||||
|
let (x, y) = net_row(comp, i, dx~)
|
||||||
|
click_at(comp, x, y, t)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn last_action(fake : @network.FakeNet) -> @network.NetAction? {
|
||||||
|
fake.actions.last()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "the network module lists Wi-Fi networks and asks to connect, disconnect and forget" {
|
||||||
|
let (comp, fake) = net_comp("net-list")
|
||||||
|
let slot = comp.shell.slot_of("network")
|
||||||
|
assert_true(comp.shell.slot_rect(slot).w > 0) // it is in the default panel
|
||||||
|
assert_true(fake.ticks > 0)
|
||||||
|
click_module(comp, "network", 1U)
|
||||||
|
assert_eq(last_action(fake), Some(Scan)) // opening the popup scans
|
||||||
|
// Status, Wi-Fi, Airplane mode, the heading, four networks.
|
||||||
|
let pr = comp.shell.slot_popup_rect(slot)
|
||||||
|
assert_eq(pr.h, 12 + 8 * 30)
|
||||||
|
// An open network connects at once; so does a saved one.
|
||||||
|
click_row(comp, 6, 10U)
|
||||||
|
assert_eq(last_action(fake), Some(Connect("Cafe", "")))
|
||||||
|
click_row(comp, 7, 15U)
|
||||||
|
assert_eq(last_action(fake), Some(Connect("Lab", "")))
|
||||||
|
// "Forget" at the right of a saved network.
|
||||||
|
click_row(comp, 7, 20U, dx=pr.w - 30)
|
||||||
|
assert_eq(last_action(fake), Some(Forget("Lab")))
|
||||||
|
// The one in use disconnects.
|
||||||
|
click_row(comp, 4, 25U)
|
||||||
|
assert_eq(last_action(fake), Some(Disconnect))
|
||||||
|
assert_eq(fake.actions.length(), 5)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "a new secured network asks for its password in the popup" {
|
||||||
|
let (comp, fake) = net_comp("net-password")
|
||||||
|
let slot = comp.shell.slot_of("network")
|
||||||
|
click_module(comp, "network", 1U)
|
||||||
|
click_row(comp, 5, 5U) // Office: a password field opens under it
|
||||||
|
assert_eq(comp.shell.slot_popup_rect(slot).h, 12 + 9 * 30)
|
||||||
|
assert_eq(last_action(fake), Some(Scan))
|
||||||
|
for k in ["s", "3", "c", "r", "e", "t", "x", "Backspace", "Space", "1"] {
|
||||||
|
comp.shell.key_down(k)
|
||||||
|
}
|
||||||
|
comp.shell.key_down("Enter")
|
||||||
|
ignore(comp.compose_frame())
|
||||||
|
assert_eq(last_action(fake), Some(Connect("Office", "s3cret 1")))
|
||||||
|
assert_eq(comp.shell.slot_popup_rect(slot).h, 12 + 8 * 30) // the field is gone
|
||||||
|
// Escape leaves the field first, then the popup.
|
||||||
|
click_row(comp, 5, 10U)
|
||||||
|
comp.shell.key_down("p")
|
||||||
|
comp.shell.key_down("Escape")
|
||||||
|
ignore(comp.compose_frame())
|
||||||
|
assert_eq(comp.shell.slot_popup_rect(slot).h, 12 + 8 * 30)
|
||||||
|
comp.shell.key_down("Escape")
|
||||||
|
ignore(comp.compose_frame())
|
||||||
|
assert_eq(comp.shell.slot_popup_rect(slot).w, 0)
|
||||||
|
assert_eq(last_action(fake), Some(Connect("Office", "s3cret 1"))) // nothing sent for "p"
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "the Wi-Fi and airplane switches, and status only without NetworkManager" {
|
||||||
|
let (comp, fake) = net_comp("net-switch")
|
||||||
|
let slot = comp.shell.slot_of("network")
|
||||||
|
click_module(comp, "network", 1U)
|
||||||
|
click_row(comp, 1, 5U) // Wi-Fi off: the list goes
|
||||||
|
assert_eq(last_action(fake), Some(SetWifi(false)))
|
||||||
|
assert_eq(comp.shell.slot_popup_rect(slot).h, 12 + 3 * 30)
|
||||||
|
click_row(comp, 1, 10U)
|
||||||
|
assert_eq(last_action(fake), Some(SetWifi(true)))
|
||||||
|
click_row(comp, 2, 15U)
|
||||||
|
assert_eq(last_action(fake), Some(SetAirplane(true)))
|
||||||
|
// A message shows under the status.
|
||||||
|
fake.status = { ..fake.status, message: "Couldn't connect to Office: wrong password?" }
|
||||||
|
ignore(comp.compose_frame())
|
||||||
|
assert_eq(comp.shell.slot_popup_rect(slot).h, 12 + 4 * 30)
|
||||||
|
// Read-only (no NetworkManager): the status and why, nothing to switch.
|
||||||
|
fake.status = {
|
||||||
|
..net_status(),
|
||||||
|
state: Wired,
|
||||||
|
name: "enp3s0",
|
||||||
|
managed: false,
|
||||||
|
message: "NetworkManager isn't running: status only",
|
||||||
|
}
|
||||||
|
ignore(comp.compose_frame())
|
||||||
|
assert_eq(comp.shell.slot_popup_rect(slot).h, 12 + 2 * 30)
|
||||||
|
let n = fake.actions.length()
|
||||||
|
click_row(comp, 1, 20U)
|
||||||
|
assert_eq(fake.actions.length(), n)
|
||||||
|
}
|
||||||
@@ -0,0 +1,818 @@
|
|||||||
|
///| A minimal D-Bus client: the wire format (marshalling, messages) and a connection to the system
|
||||||
|
/// bus over the compositor's own socket calls (@sys.unix_connect / sendmsg / recvmsg / poll_read),
|
||||||
|
/// so it needs nothing new from either host. Enough for NetworkManager (nm.mbt): method calls and
|
||||||
|
/// their replies, no signals, no fd passing. Calls are asynchronous: `call` sends, `pump` reads what
|
||||||
|
/// has arrived without blocking and runs each reply's handler.
|
||||||
|
|
||||||
|
///| A D-Bus value. Arrays carry their element signature (needed to marshal an empty one); a dict
|
||||||
|
/// is an array of `Entry`.
|
||||||
|
pub(all) enum DValue {
|
||||||
|
Byte(Int)
|
||||||
|
Bool(Bool)
|
||||||
|
I32(Int)
|
||||||
|
U32(UInt)
|
||||||
|
I64(Int64)
|
||||||
|
U64(UInt64)
|
||||||
|
F64(Double)
|
||||||
|
Str(String)
|
||||||
|
Path(String)
|
||||||
|
Sig(String)
|
||||||
|
Fd(Int)
|
||||||
|
Arr(String, Array[DValue])
|
||||||
|
Struct(Array[DValue])
|
||||||
|
Entry(DValue, DValue)
|
||||||
|
Variant(DValue)
|
||||||
|
} derive(Eq, Debug)
|
||||||
|
|
||||||
|
///| The signature of one value.
|
||||||
|
pub fn DValue::sig(self : DValue) -> String {
|
||||||
|
match self {
|
||||||
|
Byte(_) => "y"
|
||||||
|
Bool(_) => "b"
|
||||||
|
I32(_) => "i"
|
||||||
|
U32(_) => "u"
|
||||||
|
I64(_) => "x"
|
||||||
|
U64(_) => "t"
|
||||||
|
F64(_) => "d"
|
||||||
|
Str(_) => "s"
|
||||||
|
Path(_) => "o"
|
||||||
|
Sig(_) => "g"
|
||||||
|
Fd(_) => "h"
|
||||||
|
Arr(e, _) => "a" + e
|
||||||
|
Struct(fs) => {
|
||||||
|
let sb = StringBuilder::new()
|
||||||
|
sb.write_char('(')
|
||||||
|
for f in fs {
|
||||||
|
sb.write_string(f.sig())
|
||||||
|
}
|
||||||
|
sb.write_char(')')
|
||||||
|
sb.to_string()
|
||||||
|
}
|
||||||
|
Entry(k, v) => "{" + k.sig() + v.sig() + "}"
|
||||||
|
Variant(_) => "v"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| A string-keyed dict (a{s?}) from pairs; `vsig` is the value signature.
|
||||||
|
pub fn dict(vsig : String, pairs : Array[(String, DValue)]) -> DValue {
|
||||||
|
Arr("{s" + vsig + "}", pairs.map(p => Entry(Str(p.0), p.1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Bytes (ay) from a string's UTF-8.
|
||||||
|
pub fn byte_array(s : String) -> DValue {
|
||||||
|
let b = utf8_bytes(s)
|
||||||
|
let items : Array[DValue] = []
|
||||||
|
for i = 0; i < b.length(); i = i + 1 {
|
||||||
|
items.push(Byte(b[i].to_int()))
|
||||||
|
}
|
||||||
|
Arr("y", items)
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The string an `ay` holds (lossy UTF-8), "" for anything else.
|
||||||
|
pub fn DValue::bytes_text(self : DValue) -> String {
|
||||||
|
match self {
|
||||||
|
Arr("y", items) => {
|
||||||
|
let b : Array[Byte] = []
|
||||||
|
for it in items {
|
||||||
|
if it is Byte(x) {
|
||||||
|
b.push(x.to_byte())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@utf8.decode_lossy(Bytes::from_array(b))
|
||||||
|
}
|
||||||
|
_ => ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn utf8_bytes(s : String) -> Bytes {
|
||||||
|
@utf8.encode(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Alignment of the type starting with `c`.
|
||||||
|
fn align_of(c : Char) -> Int {
|
||||||
|
match c {
|
||||||
|
'y' | 'g' | 'v' => 1
|
||||||
|
'n' | 'q' => 2
|
||||||
|
'x' | 't' | 'd' | '(' | '{' => 8
|
||||||
|
_ => 4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- marshalling ----
|
||||||
|
|
||||||
|
///|
|
||||||
|
priv struct Writer {
|
||||||
|
buf : Array[Byte]
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Writer::pad(self : Writer, n : Int) -> Unit {
|
||||||
|
while self.buf.length() % n != 0 {
|
||||||
|
self.buf.push(b'\x00')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Writer::u8(self : Writer, v : Int) -> Unit {
|
||||||
|
self.buf.push((v & 0xFF).to_byte())
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Writer::u32(self : Writer, v : Int) -> Unit {
|
||||||
|
self.pad(4)
|
||||||
|
for k = 0; k < 4; k = k + 1 {
|
||||||
|
self.buf.push(((v >> (8 * k)) & 0xFF).to_byte())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Writer::u64(self : Writer, v : UInt64) -> Unit {
|
||||||
|
self.pad(8)
|
||||||
|
for k = 0; k < 8; k = k + 1 {
|
||||||
|
self.buf.push(((v >> (8 * k)) & 0xFFUL).to_byte())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Writer::raw(self : Writer, b : Bytes) -> Unit {
|
||||||
|
for i = 0; i < b.length(); i = i + 1 {
|
||||||
|
self.buf.push(b[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Writer::value(self : Writer, v : DValue) -> Unit {
|
||||||
|
match v {
|
||||||
|
Byte(x) => self.u8(x)
|
||||||
|
Bool(b) => self.u32(if b { 1 } else { 0 })
|
||||||
|
I32(x) => self.u32(x)
|
||||||
|
U32(x) => self.u32(x.reinterpret_as_int())
|
||||||
|
Fd(x) => self.u32(x)
|
||||||
|
I64(x) => self.u64(x.reinterpret_as_uint64())
|
||||||
|
U64(x) => self.u64(x)
|
||||||
|
F64(d) => self.u64(d.reinterpret_as_uint64())
|
||||||
|
Str(s) | Path(s) => {
|
||||||
|
let b = utf8_bytes(s)
|
||||||
|
self.u32(b.length())
|
||||||
|
self.raw(b)
|
||||||
|
self.u8(0)
|
||||||
|
}
|
||||||
|
Sig(s) => {
|
||||||
|
let b = utf8_bytes(s)
|
||||||
|
self.u8(b.length())
|
||||||
|
self.raw(b)
|
||||||
|
self.u8(0)
|
||||||
|
}
|
||||||
|
Arr(esig, items) => {
|
||||||
|
self.pad(4)
|
||||||
|
let at = self.buf.length()
|
||||||
|
self.u32(0)
|
||||||
|
let mut first = 'y'
|
||||||
|
for c in esig {
|
||||||
|
first = c
|
||||||
|
break
|
||||||
|
}
|
||||||
|
self.pad(align_of(first))
|
||||||
|
let start = self.buf.length()
|
||||||
|
for it in items {
|
||||||
|
self.value(it)
|
||||||
|
}
|
||||||
|
let n = self.buf.length() - start
|
||||||
|
for k = 0; k < 4; k = k + 1 {
|
||||||
|
self.buf[at + k] = ((n >> (8 * k)) & 0xFF).to_byte()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Struct(fs) => {
|
||||||
|
self.pad(8)
|
||||||
|
for f in fs {
|
||||||
|
self.value(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Entry(k, x) => {
|
||||||
|
self.pad(8)
|
||||||
|
self.value(k)
|
||||||
|
self.value(x)
|
||||||
|
}
|
||||||
|
Variant(inner) => {
|
||||||
|
self.value(Sig(inner.sig()))
|
||||||
|
self.value(inner)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Message types.
|
||||||
|
pub let method_call : Int = 1
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub let method_return : Int = 2
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub let error_reply : Int = 3
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub let signal_msg : Int = 4
|
||||||
|
|
||||||
|
///| A message, received or to send.
|
||||||
|
pub(all) struct DMessage {
|
||||||
|
mtype : Int
|
||||||
|
serial : Int
|
||||||
|
reply_serial : Int
|
||||||
|
path : String
|
||||||
|
iface : String
|
||||||
|
meth : String
|
||||||
|
error_name : String
|
||||||
|
dest : String
|
||||||
|
sig : String
|
||||||
|
body : Array[DValue]
|
||||||
|
} derive(Debug)
|
||||||
|
|
||||||
|
///| A method call to send.
|
||||||
|
pub fn DMessage::call(
|
||||||
|
dest : String,
|
||||||
|
path : String,
|
||||||
|
iface : String,
|
||||||
|
meth : String,
|
||||||
|
args : Array[DValue],
|
||||||
|
) -> DMessage {
|
||||||
|
let sb = StringBuilder::new()
|
||||||
|
for a in args {
|
||||||
|
sb.write_string(a.sig())
|
||||||
|
}
|
||||||
|
{
|
||||||
|
mtype: method_call,
|
||||||
|
serial: 0,
|
||||||
|
reply_serial: 0,
|
||||||
|
path,
|
||||||
|
iface,
|
||||||
|
meth,
|
||||||
|
error_name: "",
|
||||||
|
dest,
|
||||||
|
sig: sb.to_string(),
|
||||||
|
body: args,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The wire bytes of `m` with serial `serial` (little-endian).
|
||||||
|
pub fn DMessage::encode(self : DMessage, serial : Int) -> Bytes {
|
||||||
|
let body = { buf: [] }
|
||||||
|
for a in self.body {
|
||||||
|
body.value(a)
|
||||||
|
}
|
||||||
|
let fields : Array[DValue] = []
|
||||||
|
let field = fn(code : Int, v : DValue) { fields.push(Struct([Byte(code), Variant(v)])) }
|
||||||
|
if self.path != "" {
|
||||||
|
field(1, Path(self.path))
|
||||||
|
}
|
||||||
|
if self.iface != "" {
|
||||||
|
field(2, Str(self.iface))
|
||||||
|
}
|
||||||
|
if self.meth != "" {
|
||||||
|
field(3, Str(self.meth))
|
||||||
|
}
|
||||||
|
if self.error_name != "" {
|
||||||
|
field(4, Str(self.error_name))
|
||||||
|
}
|
||||||
|
if self.reply_serial != 0 {
|
||||||
|
field(5, U32(self.reply_serial.reinterpret_as_uint()))
|
||||||
|
}
|
||||||
|
if self.dest != "" {
|
||||||
|
field(6, Str(self.dest))
|
||||||
|
}
|
||||||
|
if self.sig != "" {
|
||||||
|
field(8, Sig(self.sig))
|
||||||
|
}
|
||||||
|
let w = { buf: [] }
|
||||||
|
w.u8('l'.to_int())
|
||||||
|
w.u8(self.mtype)
|
||||||
|
w.u8(0)
|
||||||
|
w.u8(1)
|
||||||
|
w.u32(body.buf.length())
|
||||||
|
w.u32(serial)
|
||||||
|
w.value(Arr("(yv)", fields))
|
||||||
|
w.pad(8)
|
||||||
|
for b in body.buf {
|
||||||
|
w.buf.push(b)
|
||||||
|
}
|
||||||
|
Bytes::from_array(w.buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- unmarshalling ----
|
||||||
|
|
||||||
|
///| Reads values out of a whole message (offsets are from its start, as alignment is).
|
||||||
|
priv struct Reader {
|
||||||
|
data : Array[Byte]
|
||||||
|
mut pos : Int
|
||||||
|
le : Bool
|
||||||
|
mut bad : Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Reader::align(self : Reader, n : Int) -> Unit {
|
||||||
|
while self.pos % n != 0 {
|
||||||
|
self.pos = self.pos + 1
|
||||||
|
}
|
||||||
|
if self.pos > self.data.length() {
|
||||||
|
self.bad = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Reader::bytes(self : Reader, n : Int) -> Int {
|
||||||
|
if n < 0 || self.pos + n > self.data.length() {
|
||||||
|
self.bad = true
|
||||||
|
self.pos = self.data.length()
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
let at = self.pos
|
||||||
|
self.pos = self.pos + n
|
||||||
|
at
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Reader::u8(self : Reader) -> Int {
|
||||||
|
let at = self.bytes(1)
|
||||||
|
if at < 0 { 0 } else { self.data[at].to_int() }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Reader::uint(self : Reader, size : Int) -> UInt64 {
|
||||||
|
self.align(size)
|
||||||
|
let at = self.bytes(size)
|
||||||
|
if at < 0 {
|
||||||
|
return 0UL
|
||||||
|
}
|
||||||
|
let mut v = 0UL
|
||||||
|
for k = 0; k < size; k = k + 1 {
|
||||||
|
let b = self.data[if self.le { at + k } else { at + size - 1 - k }].to_uint64()
|
||||||
|
v = v | (b << (8 * k))
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Reader::u32(self : Reader) -> Int {
|
||||||
|
self.uint(4).to_int()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn Reader::text(self : Reader, n : Int) -> String {
|
||||||
|
let at = self.bytes(n)
|
||||||
|
if at < 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
let b = Array::makei(n, i => self.data[at + i])
|
||||||
|
ignore(self.bytes(1)) // the NUL
|
||||||
|
@utf8.decode_lossy(Bytes::from_array(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The end of the single complete type starting at `i` in `sig` (exclusive), or -1.
|
||||||
|
fn type_end(sig : Array[Char], i : Int) -> Int {
|
||||||
|
if i >= sig.length() {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
match sig[i] {
|
||||||
|
'a' => type_end(sig, i + 1)
|
||||||
|
'(' | '{' => {
|
||||||
|
let close = if sig[i] == '(' { ')' } else { '}' }
|
||||||
|
let mut j = i + 1
|
||||||
|
while j < sig.length() && sig[j] != close {
|
||||||
|
j = type_end(sig, j)
|
||||||
|
if j < 0 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if j < sig.length() { j + 1 } else { -1 }
|
||||||
|
}
|
||||||
|
_ => i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn chars(s : String) -> Array[Char] {
|
||||||
|
let a : Array[Char] = []
|
||||||
|
for c in s {
|
||||||
|
a.push(c)
|
||||||
|
}
|
||||||
|
a
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn sub(sig : Array[Char], from : Int, to : Int) -> String {
|
||||||
|
String::from_array(sig[from:to].to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Read the values of signature `sig` (a sequence of complete types).
|
||||||
|
fn Reader::values(self : Reader, sig : Array[Char], from : Int, to : Int) -> Array[DValue] {
|
||||||
|
let out : Array[DValue] = []
|
||||||
|
let mut i = from
|
||||||
|
while i < to && !self.bad {
|
||||||
|
let e = type_end(sig, i)
|
||||||
|
if e < 0 || e > to {
|
||||||
|
self.bad = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
out.push(self.value(sig, i))
|
||||||
|
i = e
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Read one value of the complete type at `sig[i]`.
|
||||||
|
fn Reader::value(self : Reader, sig : Array[Char], i : Int) -> DValue {
|
||||||
|
if self.bad {
|
||||||
|
return Byte(0)
|
||||||
|
}
|
||||||
|
match sig[i] {
|
||||||
|
'y' => Byte(self.u8())
|
||||||
|
'b' => Bool(self.u32() != 0)
|
||||||
|
'n' => {
|
||||||
|
let v = self.uint(2).to_int()
|
||||||
|
I32(if v >= 0x8000 { v - 0x10000 } else { v })
|
||||||
|
}
|
||||||
|
'q' => U32(self.uint(2).to_uint())
|
||||||
|
'i' => I32(self.u32())
|
||||||
|
'u' => U32(self.uint(4).to_uint())
|
||||||
|
'h' => Fd(self.u32())
|
||||||
|
'x' => I64(self.uint(8).reinterpret_as_int64())
|
||||||
|
't' => U64(self.uint(8))
|
||||||
|
'd' => F64(self.uint(8).reinterpret_as_double())
|
||||||
|
's' => Str(self.text(self.u32()))
|
||||||
|
'o' => Path(self.text(self.u32()))
|
||||||
|
'g' => Sig(self.text(self.u8()))
|
||||||
|
'v' => {
|
||||||
|
let s = chars(self.text(self.u8()))
|
||||||
|
if s.length() == 0 || type_end(s, 0) != s.length() {
|
||||||
|
self.bad = true
|
||||||
|
return Byte(0)
|
||||||
|
}
|
||||||
|
Variant(self.value(s, 0))
|
||||||
|
}
|
||||||
|
'a' => {
|
||||||
|
let n = self.u32()
|
||||||
|
let e = type_end(sig, i + 1)
|
||||||
|
if e < 0 {
|
||||||
|
self.bad = true
|
||||||
|
return Byte(0)
|
||||||
|
}
|
||||||
|
self.align(align_of(sig[i + 1]))
|
||||||
|
let end = self.pos + n
|
||||||
|
if n < 0 || end > self.data.length() {
|
||||||
|
self.bad = true
|
||||||
|
return Byte(0)
|
||||||
|
}
|
||||||
|
let items : Array[DValue] = []
|
||||||
|
while self.pos < end && !self.bad {
|
||||||
|
items.push(self.value(sig, i + 1))
|
||||||
|
}
|
||||||
|
Arr(sub(sig, i + 1, e), items)
|
||||||
|
}
|
||||||
|
'(' => {
|
||||||
|
self.align(8)
|
||||||
|
let e = type_end(sig, i)
|
||||||
|
if e < 0 {
|
||||||
|
self.bad = true
|
||||||
|
return Byte(0)
|
||||||
|
}
|
||||||
|
Struct(self.values(sig, i + 1, e - 1))
|
||||||
|
}
|
||||||
|
'{' => {
|
||||||
|
self.align(8)
|
||||||
|
let ke = type_end(sig, i + 1)
|
||||||
|
if ke < 0 || type_end(sig, ke) < 0 {
|
||||||
|
self.bad = true
|
||||||
|
return Byte(0)
|
||||||
|
}
|
||||||
|
let k = self.value(sig, i + 1)
|
||||||
|
let v = self.value(sig, ke)
|
||||||
|
Entry(k, v)
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
self.bad = true
|
||||||
|
Byte(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Total length of the message at the start of `buf`, or -1 when its fixed header isn't in yet.
|
||||||
|
pub fn message_length(buf : Array[Byte]) -> Int {
|
||||||
|
if buf.length() < 16 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
let le = buf[0] == b'l'
|
||||||
|
let rd = fn(at : Int) {
|
||||||
|
let mut v = 0
|
||||||
|
for k = 0; k < 4; k = k + 1 {
|
||||||
|
let b = buf[if le { at + k } else { at + 3 - k }].to_int()
|
||||||
|
v = v | (b << (8 * k))
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
let body = rd(4)
|
||||||
|
let fields = rd(12)
|
||||||
|
let hdr = (16 + fields + 7) / 8 * 8
|
||||||
|
hdr + body
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Parse one whole message; None when it is malformed.
|
||||||
|
pub fn decode(data : Array[Byte]) -> DMessage? {
|
||||||
|
if data.length() < 16 {
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let r = { data, pos: 12, le: data[0] == b'l', bad: false }
|
||||||
|
let mtype = data[1].to_int()
|
||||||
|
let serial = {
|
||||||
|
r.pos = 8
|
||||||
|
let s = r.u32()
|
||||||
|
r.pos = 12
|
||||||
|
s
|
||||||
|
}
|
||||||
|
let fields = r.value(chars("a(yv)"), 0)
|
||||||
|
r.align(8)
|
||||||
|
if r.bad {
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let mut path = ""
|
||||||
|
let mut iface = ""
|
||||||
|
let mut meth = ""
|
||||||
|
let mut error_name = ""
|
||||||
|
let mut reply_serial = 0
|
||||||
|
let mut dest = ""
|
||||||
|
let mut sig = ""
|
||||||
|
if fields is Arr(_, items) {
|
||||||
|
for f in items {
|
||||||
|
match f {
|
||||||
|
Struct([Byte(code), Variant(v)]) =>
|
||||||
|
match (code, v) {
|
||||||
|
(1, Path(s)) => path = s
|
||||||
|
(2, Str(s)) => iface = s
|
||||||
|
(3, Str(s)) => meth = s
|
||||||
|
(4, Str(s)) => error_name = s
|
||||||
|
(5, U32(n)) => reply_serial = n.reinterpret_as_int()
|
||||||
|
(6, Str(s)) => dest = s
|
||||||
|
(8, Sig(s)) => sig = s
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let sc = chars(sig)
|
||||||
|
let body = r.values(sc, 0, sc.length())
|
||||||
|
if r.bad {
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
Some({ mtype, serial, reply_serial, path, iface, meth, error_name, dest, sig, body })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the connection ----
|
||||||
|
|
||||||
|
///| A connection to a message bus.
|
||||||
|
pub struct DBus {
|
||||||
|
fd : Int
|
||||||
|
inbuf : Array[Byte]
|
||||||
|
mut serial : Int
|
||||||
|
pending : Map[Int, (DMessage) -> Unit]
|
||||||
|
mut alive : Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The system bus socket: $DBUS_SYSTEM_BUS_ADDRESS when it is a unix:path= address, else the
|
||||||
|
/// standard path.
|
||||||
|
pub fn system_bus_path() -> String {
|
||||||
|
let addr = @sys.getenv("DBUS_SYSTEM_BUS_ADDRESS")
|
||||||
|
let pre = "unix:path="
|
||||||
|
if addr.has_prefix(pre) {
|
||||||
|
let rest = addr[pre.length():].to_string()
|
||||||
|
match rest.find(",") {
|
||||||
|
Some(i) => rest[:i].to_string()
|
||||||
|
None => rest
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
"/run/dbus/system_bus_socket"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Our uid, from /proc/self/status, as the decimal string EXTERNAL authentication sends ("" if
|
||||||
|
/// unknown).
|
||||||
|
fn own_uid() -> String {
|
||||||
|
let st = @utf8.decode_lossy(@sys.read_proc_bytes("/proc/self/status"))
|
||||||
|
for line in st.split("\n") {
|
||||||
|
if line.has_prefix("Uid:") {
|
||||||
|
for f in line[4:].split("\t") {
|
||||||
|
let t = f.trim(chars=" ").to_string()
|
||||||
|
if t != "" {
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Hex of `s`'s ASCII bytes (how SASL EXTERNAL sends the uid).
|
||||||
|
fn hex_ascii(s : String) -> String {
|
||||||
|
let digits = "0123456789abcdef"
|
||||||
|
let sb = StringBuilder::new()
|
||||||
|
for c in s {
|
||||||
|
let v = c.to_int()
|
||||||
|
sb.write_char(digits.get_char(v >> 4).unwrap_or('0'))
|
||||||
|
sb.write_char(digits.get_char(v & 15).unwrap_or('0'))
|
||||||
|
}
|
||||||
|
sb.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn send_text(fd : Int, s : String) -> Bool {
|
||||||
|
let b = utf8_bytes(s)
|
||||||
|
@sys.sendmsg_fd(fd, b, -1) == b.length()
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Read into `into` until it holds a "\r\n"-terminated line; the line (without it), with the
|
||||||
|
/// bytes after it left in `into`. None on timeout or a closed socket.
|
||||||
|
fn read_line(fd : Int, into : Array[Byte], timeout_ms : Int) -> String? {
|
||||||
|
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
|
||||||
|
let deadline = @sys.monotonic_ms() + timeout_ms.to_uint64()
|
||||||
|
while true {
|
||||||
|
for i = 0; i + 1 < into.length(); i = i + 1 {
|
||||||
|
if into[i] == b'\r' && into[i + 1] == b'\n' {
|
||||||
|
let line = @utf8.decode_lossy(Bytes::from_array(into[:i].to_array()))
|
||||||
|
let rest = into[i + 2:].to_array()
|
||||||
|
into.clear()
|
||||||
|
into.append(rest)
|
||||||
|
return Some(line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let now = @sys.monotonic_ms()
|
||||||
|
if now >= deadline || @sys.poll_read(fd, (deadline - now).to_int()) <= 0 {
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let (n, extra) = @sys.recvmsg_fd(fd, buf, buf.length())
|
||||||
|
if extra >= 0 {
|
||||||
|
@sys.close_fd(extra)
|
||||||
|
}
|
||||||
|
if n <= 0 {
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
for i = 0; i < n; i = i + 1 {
|
||||||
|
into.push(buf[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Connect to the bus at `path`, authenticate (EXTERNAL) and say Hello. None when there is no
|
||||||
|
/// bus or it refuses us. Blocks for at most about a second.
|
||||||
|
pub fn DBus::open(path : String) -> DBus? {
|
||||||
|
let fd = @sys.unix_connect(path)
|
||||||
|
if fd < 0 {
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let fail = fn() {
|
||||||
|
@sys.close_fd(fd)
|
||||||
|
None
|
||||||
|
}
|
||||||
|
let inbuf : Array[Byte] = []
|
||||||
|
let uid = own_uid()
|
||||||
|
// The leading NUL is the credentials byte every client sends first.
|
||||||
|
let auth = if uid == "" {
|
||||||
|
"\u{0}AUTH EXTERNAL\r\n"
|
||||||
|
} else {
|
||||||
|
"\u{0}AUTH EXTERNAL " + hex_ascii(uid) + "\r\n"
|
||||||
|
}
|
||||||
|
if !send_text(fd, auth) {
|
||||||
|
return fail()
|
||||||
|
}
|
||||||
|
let mut ok = false
|
||||||
|
for _round = 0; _round < 3 && !ok; _round = _round + 1 {
|
||||||
|
match read_line(fd, inbuf, 1000) {
|
||||||
|
Some(l) if l.has_prefix("OK") => ok = true
|
||||||
|
Some(l) if l.has_prefix("DATA") => if !send_text(fd, "DATA\r\n") { return fail() }
|
||||||
|
_ => return fail()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !ok || !send_text(fd, "BEGIN\r\n") {
|
||||||
|
return fail()
|
||||||
|
}
|
||||||
|
let bus = { fd, inbuf, serial: 0, pending: {}, alive: true }
|
||||||
|
let hello = bus.call_sync(
|
||||||
|
DMessage::call(
|
||||||
|
"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Hello", [],
|
||||||
|
),
|
||||||
|
1000,
|
||||||
|
)
|
||||||
|
match hello {
|
||||||
|
Some(m) if m.mtype == method_return => Some(bus)
|
||||||
|
_ => {
|
||||||
|
bus.close()
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn DBus::close(self : DBus) -> Unit {
|
||||||
|
if self.alive {
|
||||||
|
self.alive = false
|
||||||
|
@sys.close_fd(self.fd)
|
||||||
|
}
|
||||||
|
self.pending.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Send `m`; `on_reply` runs from a later `pump` with its reply (or error). The serial.
|
||||||
|
pub fn DBus::call(self : DBus, m : DMessage, on_reply? : (DMessage) -> Unit) -> Int {
|
||||||
|
if !self.alive {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
self.serial = self.serial + 1
|
||||||
|
let s = self.serial
|
||||||
|
let b = m.encode(s)
|
||||||
|
if @sys.sendmsg_fd(self.fd, b, -1) != b.length() {
|
||||||
|
self.close()
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
match on_reply {
|
||||||
|
Some(f) => self.pending.set(s, f)
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Read whatever has arrived (waiting up to `timeout_ms`) and run reply handlers. Signals and
|
||||||
|
/// calls to us are dropped.
|
||||||
|
pub fn DBus::pump(self : DBus, timeout_ms? : Int = 0) -> Unit {
|
||||||
|
if !self.alive {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let buf : FixedArray[Byte] = FixedArray::make(65536, b'\x00')
|
||||||
|
let mut wait = timeout_ms
|
||||||
|
while self.alive && @sys.poll_read(self.fd, wait) > 0 {
|
||||||
|
wait = 0
|
||||||
|
let (n, extra) = @sys.recvmsg_fd(self.fd, buf, buf.length())
|
||||||
|
if extra >= 0 {
|
||||||
|
@sys.close_fd(extra)
|
||||||
|
}
|
||||||
|
if n == -1 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if n <= 0 {
|
||||||
|
self.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for i = 0; i < n; i = i + 1 {
|
||||||
|
self.inbuf.push(buf[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.dispatch()
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Run the handlers of the whole messages in the buffer.
|
||||||
|
fn DBus::dispatch(self : DBus) -> Unit {
|
||||||
|
while true {
|
||||||
|
let len = message_length(self.inbuf)
|
||||||
|
if len < 0 || len > self.inbuf.length() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
let msg = self.inbuf[:len].to_array()
|
||||||
|
let rest = self.inbuf[len:].to_array()
|
||||||
|
self.inbuf.clear()
|
||||||
|
self.inbuf.append(rest)
|
||||||
|
match decode(msg) {
|
||||||
|
Some(m) if m.mtype == method_return || m.mtype == error_reply =>
|
||||||
|
match self.pending.get(m.reply_serial) {
|
||||||
|
Some(f) => {
|
||||||
|
self.pending.remove(m.reply_serial)
|
||||||
|
f(m)
|
||||||
|
}
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Send `m` and wait up to `timeout_ms` for its reply.
|
||||||
|
pub fn DBus::call_sync(self : DBus, m : DMessage, timeout_ms : Int) -> DMessage? {
|
||||||
|
let got : Ref[DMessage?] = { val: None }
|
||||||
|
let s = self.call(m, on_reply=r => got.val = Some(r))
|
||||||
|
if s == 0 {
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let deadline = @sys.monotonic_ms() + timeout_ms.to_uint64()
|
||||||
|
while got.val is None && self.alive {
|
||||||
|
let now = @sys.monotonic_ms()
|
||||||
|
if now >= deadline {
|
||||||
|
self.pending.remove(s)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
self.pump(timeout_ms=(deadline - now).to_int())
|
||||||
|
}
|
||||||
|
got.val
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The first string in an error reply's body (its message), else the error name.
|
||||||
|
pub fn DMessage::error_text(self : DMessage) -> String {
|
||||||
|
match self.body {
|
||||||
|
[Str(s), ..] => s
|
||||||
|
_ => self.error_name
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
///| A backend for tests: it serves whatever status and network list it is given and records the
|
||||||
|
/// actions it receives (switching Wi-Fi off empties the list, as NetworkManager's would).
|
||||||
|
pub(all) struct FakeNet {
|
||||||
|
mut status : NetStatus
|
||||||
|
mut networks : Array[WifiNetwork]
|
||||||
|
actions : Array[NetAction]
|
||||||
|
mut ticks : Int
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn FakeNet::new(status : NetStatus, networks : Array[WifiNetwork]) -> FakeNet {
|
||||||
|
{ status, networks, actions: [], ticks: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for FakeNet with tick(self, _now) {
|
||||||
|
self.ticks = self.ticks + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for FakeNet with status(self) {
|
||||||
|
self.status
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for FakeNet with networks(self) {
|
||||||
|
if self.status.wifi_enabled {
|
||||||
|
self.networks
|
||||||
|
} else {
|
||||||
|
[]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for FakeNet with act(self, a) {
|
||||||
|
self.actions.push(a)
|
||||||
|
match a {
|
||||||
|
SetWifi(on) => self.status = { ..self.status, wifi_enabled: on }
|
||||||
|
SetAirplane(on) => self.status = { ..self.status, airplane: on, wifi_enabled: !on }
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for FakeNet with alive(_self) {
|
||||||
|
true
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
///| Network status and control for the `network` capability (the network panel module). The shell
|
||||||
|
/// owns a `NetService`; it picks a backend: NetworkManager over D-Bus (nm.mbt) when it answers,
|
||||||
|
/// else read-only status from /sys/class/net and /proc/net (sysfs.mbt), trying NetworkManager
|
||||||
|
/// again now and then. Tests plug in their own backend.
|
||||||
|
|
||||||
|
///| How the machine is connected now.
|
||||||
|
pub(all) enum NetState {
|
||||||
|
Offline
|
||||||
|
Wired
|
||||||
|
Wifi
|
||||||
|
Connecting
|
||||||
|
} derive(Eq, Debug)
|
||||||
|
|
||||||
|
///| The number the capability uses: 0 offline, 1 wired, 2 Wi-Fi, 3 connecting.
|
||||||
|
pub fn NetState::code(self : NetState) -> Int {
|
||||||
|
match self {
|
||||||
|
Offline => 0
|
||||||
|
Wired => 1
|
||||||
|
Wifi => 2
|
||||||
|
Connecting => 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| What the panel shows.
|
||||||
|
pub(all) struct NetStatus {
|
||||||
|
state : NetState
|
||||||
|
/// The Wi-Fi network's name, else the connection's (e.g. "Wired connection 1"); "" offline.
|
||||||
|
name : String
|
||||||
|
/// Signal of the Wi-Fi network in use, 0..100 (0 when not on Wi-Fi).
|
||||||
|
signal : Int
|
||||||
|
/// Something to tell the user: an action's outcome or why it failed ("" for nothing).
|
||||||
|
message : String
|
||||||
|
wifi_enabled : Bool
|
||||||
|
airplane : Bool
|
||||||
|
/// The network can be changed from here (NetworkManager answers); false: status only.
|
||||||
|
managed : Bool
|
||||||
|
/// There is a Wi-Fi device.
|
||||||
|
has_wifi : Bool
|
||||||
|
} derive(Eq, Debug)
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn NetStatus::offline() -> NetStatus {
|
||||||
|
{
|
||||||
|
state: Offline,
|
||||||
|
name: "",
|
||||||
|
signal: 0,
|
||||||
|
message: "",
|
||||||
|
wifi_enabled: false,
|
||||||
|
airplane: false,
|
||||||
|
managed: false,
|
||||||
|
has_wifi: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| A Wi-Fi network in range.
|
||||||
|
pub(all) struct WifiNetwork {
|
||||||
|
ssid : String
|
||||||
|
signal : Int
|
||||||
|
secured : Bool
|
||||||
|
/// The one in use.
|
||||||
|
active : Bool
|
||||||
|
/// There is a saved connection for it (no password needed).
|
||||||
|
saved : Bool
|
||||||
|
} derive(Eq, Debug)
|
||||||
|
|
||||||
|
///| What the module can ask for.
|
||||||
|
pub(all) enum NetAction {
|
||||||
|
Scan
|
||||||
|
Disconnect
|
||||||
|
SetWifi(Bool)
|
||||||
|
SetAirplane(Bool)
|
||||||
|
/// Connect to the network named `ssid`: a saved one as saved, a new one with `password`
|
||||||
|
/// ("" for an open network).
|
||||||
|
Connect(String, String)
|
||||||
|
/// Delete the saved connections for a network.
|
||||||
|
Forget(String)
|
||||||
|
} derive(Eq, Debug)
|
||||||
|
|
||||||
|
///| The capability's action codes (wit/host/plasmoids.wit `network-request`): 0 scan,
|
||||||
|
/// 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode off/on, 6 connect, 7 forget.
|
||||||
|
pub fn NetAction::from_code(code : Int, ssid : String, password : String) -> NetAction? {
|
||||||
|
match code {
|
||||||
|
0 => Some(Scan)
|
||||||
|
1 => Some(Disconnect)
|
||||||
|
2 => Some(SetWifi(false))
|
||||||
|
3 => Some(SetWifi(true))
|
||||||
|
4 => Some(SetAirplane(false))
|
||||||
|
5 => Some(SetAirplane(true))
|
||||||
|
6 => if ssid == "" { None } else { Some(Connect(ssid, password)) }
|
||||||
|
7 => if ssid == "" { None } else { Some(Forget(ssid)) }
|
||||||
|
_ => None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Where status comes from and where actions go.
|
||||||
|
pub(open) trait NetBackend {
|
||||||
|
/// Called every frame with monotonic ms: read replies, refresh when due.
|
||||||
|
tick(Self, UInt64) -> Unit
|
||||||
|
status(Self) -> NetStatus
|
||||||
|
networks(Self) -> Array[WifiNetwork]
|
||||||
|
act(Self, NetAction) -> Unit
|
||||||
|
/// False once the backend stopped working (NetworkManager went away).
|
||||||
|
alive(Self) -> Bool
|
||||||
|
/// Let go of what it holds (a bus connection).
|
||||||
|
close(Self) -> Unit = _
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
impl NetBackend with close(_self) {
|
||||||
|
()
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The network service the shell holds.
|
||||||
|
pub struct NetService {
|
||||||
|
mut backend : &NetBackend
|
||||||
|
mut on_nm : Bool
|
||||||
|
mut retry_at : UInt64
|
||||||
|
/// Look for NetworkManager (false with a test backend).
|
||||||
|
probe : Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
///| How often to look for NetworkManager again while it isn't there.
|
||||||
|
let nm_retry_ms : UInt64 = 30000UL
|
||||||
|
|
||||||
|
///| NetworkManager if it answers, else /sys status.
|
||||||
|
pub fn NetService::new() -> NetService {
|
||||||
|
match NmBackend::connect() {
|
||||||
|
Some(nm) => { backend: nm as &NetBackend, on_nm: true, retry_at: 0UL, probe: true }
|
||||||
|
None => {
|
||||||
|
backend: SysfsBackend::new() as &NetBackend,
|
||||||
|
on_nm: false,
|
||||||
|
retry_at: @sys.monotonic_ms() + nm_retry_ms,
|
||||||
|
probe: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| A service over `b` (tests).
|
||||||
|
pub fn NetService::with_backend(b : &NetBackend) -> NetService {
|
||||||
|
{ backend: b, on_nm: false, retry_at: 0UL, probe: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn NetService::tick(self : NetService, now : UInt64) -> Unit {
|
||||||
|
self.backend.tick(now)
|
||||||
|
if self.on_nm && !self.backend.alive() {
|
||||||
|
self.backend.close()
|
||||||
|
self.backend = SysfsBackend::new() as &NetBackend
|
||||||
|
self.on_nm = false
|
||||||
|
self.retry_at = now + nm_retry_ms
|
||||||
|
self.backend.tick(now)
|
||||||
|
} else if !self.on_nm && self.probe && now >= self.retry_at {
|
||||||
|
self.retry_at = now + nm_retry_ms
|
||||||
|
match NmBackend::connect() {
|
||||||
|
Some(nm) => {
|
||||||
|
self.backend = nm as &NetBackend
|
||||||
|
self.on_nm = true
|
||||||
|
self.backend.tick(now)
|
||||||
|
}
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Whether this service looks for NetworkManager (false with a test backend).
|
||||||
|
pub fn NetService::probe(self : NetService) -> Bool {
|
||||||
|
self.probe
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Let go of the bus connection.
|
||||||
|
pub fn NetService::close(self : NetService) -> Unit {
|
||||||
|
self.backend.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn NetService::status(self : NetService) -> NetStatus {
|
||||||
|
self.backend.status()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn NetService::networks(self : NetService) -> Array[WifiNetwork] {
|
||||||
|
self.backend.networks()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn NetService::act(self : NetService, a : NetAction) -> Unit {
|
||||||
|
self.backend.act(a)
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import {
|
||||||
|
"moonbitlang/core/builtin",
|
||||||
|
"moonbitlang/core/encoding/utf8" @utf8,
|
||||||
|
"chandra/desktop/compositor/sys" @sys,
|
||||||
|
}
|
||||||
|
|
||||||
|
supported_targets = "+native+wasm"
|
||||||
|
|
||||||
|
warnings = "-44"
|
||||||
@@ -0,0 +1,388 @@
|
|||||||
|
///|
|
||||||
|
fn hello() -> DMessage {
|
||||||
|
DMessage::call(
|
||||||
|
"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Hello", [],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "a Hello call has the well-known wire bytes" {
|
||||||
|
let b = hello().encode(1)
|
||||||
|
// l, method call, no flags, version 1; empty body; serial 1; 109 bytes of header fields.
|
||||||
|
let head = [
|
||||||
|
b'l', b'\x01', b'\x00', b'\x01', b'\x00', b'\x00', b'\x00', b'\x00', b'\x01', b'\x00', b'\x00',
|
||||||
|
b'\x00', b'\x6d', b'\x00', b'\x00', b'\x00',
|
||||||
|
]
|
||||||
|
for i = 0; i < head.length(); i = i + 1 {
|
||||||
|
assert_eq(b[i], head[i])
|
||||||
|
}
|
||||||
|
assert_eq(b.length(), 128)
|
||||||
|
assert_eq(message_length(b.to_array()), 128)
|
||||||
|
assert_eq(message_length(b.to_array()[:15].to_array()), -1)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "calls round-trip through the wire format" {
|
||||||
|
let args = [
|
||||||
|
dict("a{sv}", [
|
||||||
|
("802-11-wireless", dict("v", [("ssid", Variant(byte_array("Café")))])),
|
||||||
|
(
|
||||||
|
"802-11-wireless-security",
|
||||||
|
dict("v", [("key-mgmt", Variant(Str("wpa-psk"))), ("psk", Variant(Str("hunter22")))]),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
Path("/org/freedesktop/NetworkManager/Devices/3"),
|
||||||
|
Path("/"),
|
||||||
|
Struct([U32(100U), U32(7U)]),
|
||||||
|
I64(-5L),
|
||||||
|
Bool(true),
|
||||||
|
Arr("s", []),
|
||||||
|
]
|
||||||
|
let m = DMessage::call(
|
||||||
|
"org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.NetworkManager",
|
||||||
|
"AddAndActivateConnection", args,
|
||||||
|
)
|
||||||
|
assert_eq(m.sig, "a{sa{sv}}oo(uu)xbas")
|
||||||
|
let back = decode(m.encode(42).to_array()).unwrap()
|
||||||
|
assert_eq(back.serial, 42)
|
||||||
|
assert_eq(back.meth, "AddAndActivateConnection")
|
||||||
|
assert_eq(back.dest, "org.freedesktop.NetworkManager")
|
||||||
|
assert_eq(back.sig, m.sig)
|
||||||
|
assert_eq(back.body, args)
|
||||||
|
let groups = dict_map(back.body[0])
|
||||||
|
assert_eq(dict_map(groups.get("802-11-wireless").unwrap()).get("ssid").unwrap().bytes_text(), "Café")
|
||||||
|
assert_eq(settings_ssid(back.body[0]), "Café")
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "malformed messages are refused" {
|
||||||
|
let b = hello().encode(1).to_array()
|
||||||
|
b[12] = b'\xff' // a header field array longer than the message
|
||||||
|
assert_eq(decode(b) is None, true)
|
||||||
|
assert_eq(decode([b'l', b'\x01']) is None, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
///| A NetworkManager as GetManagedObjects / GetAll would describe it: Wi-Fi connected to "Home",
|
||||||
|
/// two more networks in range (one twice), an Ethernet device unplugged, one saved connection.
|
||||||
|
fn sample_objects() -> (Map[String, DValue], Map[String, Map[String, Map[String, DValue]]]) {
|
||||||
|
let nm = "/org/freedesktop/NetworkManager"
|
||||||
|
let obj = fn(ifaces : Array[(String, Array[(String, DValue)])]) {
|
||||||
|
Arr("{sa{sv}}", ifaces.map(i => Entry(Str(i.0), dict("v", i.1.map(p => (p.0, Variant(p.1)))))))
|
||||||
|
}
|
||||||
|
let ap = fn(ssid : String, strength : Int, flags : Int, wpa : Int, rsn : Int) {
|
||||||
|
obj([
|
||||||
|
(
|
||||||
|
ap_iface,
|
||||||
|
[
|
||||||
|
("Ssid", byte_array(ssid)),
|
||||||
|
("Strength", Byte(strength)),
|
||||||
|
("Flags", U32(flags.reinterpret_as_uint())),
|
||||||
|
("WpaFlags", U32(wpa.reinterpret_as_uint())),
|
||||||
|
("RsnFlags", U32(rsn.reinterpret_as_uint())),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
let objects = Arr("{oa{sa{sv}}}", [
|
||||||
|
Entry(
|
||||||
|
Path(nm + "/Devices/1"),
|
||||||
|
obj([
|
||||||
|
(
|
||||||
|
dev_iface,
|
||||||
|
[
|
||||||
|
("DeviceType", U32(1U)),
|
||||||
|
("State", U32(20U)),
|
||||||
|
("Interface", Str("enp3s0")),
|
||||||
|
("ActiveConnection", Path("/")),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
Entry(
|
||||||
|
Path(nm + "/Devices/2"),
|
||||||
|
obj([
|
||||||
|
(
|
||||||
|
dev_iface,
|
||||||
|
[
|
||||||
|
("DeviceType", U32(2U)),
|
||||||
|
("State", U32(100U)),
|
||||||
|
("StateReason", Struct([U32(100U), U32(0U)])),
|
||||||
|
("Interface", Str("wlan0")),
|
||||||
|
("ActiveConnection", Path(nm + "/ActiveConnection/5")),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
wifi_iface,
|
||||||
|
[
|
||||||
|
("ActiveAccessPoint", Path(nm + "/AccessPoint/10")),
|
||||||
|
(
|
||||||
|
"AccessPoints",
|
||||||
|
Arr("o", [
|
||||||
|
Path(nm + "/AccessPoint/10"),
|
||||||
|
Path(nm + "/AccessPoint/11"),
|
||||||
|
Path(nm + "/AccessPoint/12"),
|
||||||
|
Path(nm + "/AccessPoint/13"),
|
||||||
|
Path(nm + "/AccessPoint/14"),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
Entry(Path(nm + "/AccessPoint/10"), ap("Home", 72, 1, 0, 0x188)),
|
||||||
|
Entry(Path(nm + "/AccessPoint/11"), ap("Cafe", 40, 0, 0, 0)),
|
||||||
|
Entry(Path(nm + "/AccessPoint/12"), ap("Office", 30, 1, 0, 0x188)),
|
||||||
|
Entry(Path(nm + "/AccessPoint/13"), ap("Office", 55, 1, 0, 0x188)),
|
||||||
|
Entry(Path(nm + "/AccessPoint/14"), ap("", 90, 1, 0, 0x188)),
|
||||||
|
Entry(
|
||||||
|
Path(nm + "/ActiveConnection/5"),
|
||||||
|
obj([
|
||||||
|
(
|
||||||
|
active_iface,
|
||||||
|
[
|
||||||
|
("Id", Str("Home")),
|
||||||
|
("Type", Str("802-11-wireless")),
|
||||||
|
("Devices", Arr("o", [Path(nm + "/Devices/2")])),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
Entry(Path(nm + "/Settings/1"), obj([(setting_iface, [("Unsaved", Bool(false))])])),
|
||||||
|
])
|
||||||
|
let root = dict("v", [
|
||||||
|
("State", Variant(U32(70U))),
|
||||||
|
("PrimaryConnection", Variant(Path(nm + "/ActiveConnection/5"))),
|
||||||
|
("ActivatingConnection", Variant(Path("/"))),
|
||||||
|
("WirelessEnabled", Variant(Bool(true))),
|
||||||
|
("WwanEnabled", Variant(Bool(true))),
|
||||||
|
("NetworkingEnabled", Variant(Bool(true))),
|
||||||
|
])
|
||||||
|
// Through the wire and back, as a reply would arrive.
|
||||||
|
let reply = fn(v : DValue) {
|
||||||
|
let m = { ..DMessage::call("", "", "", "", [v]), mtype: method_return, reply_serial: 3 }
|
||||||
|
decode(m.encode(9).to_array()).unwrap().body[0]
|
||||||
|
}
|
||||||
|
(dict_map(reply(root)), objects_map(reply(objects)))
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "NetworkManager's objects become the panel's status and network list" {
|
||||||
|
let (root, objs) = sample_objects()
|
||||||
|
let saved = { "/org/freedesktop/NetworkManager/Settings/1": "Office" }
|
||||||
|
let v = nm_view(root, objs, saved)
|
||||||
|
assert_eq(v.status.state, Wifi)
|
||||||
|
assert_eq(v.status.name, "Home")
|
||||||
|
assert_eq(v.status.signal, 72)
|
||||||
|
assert_eq(v.status.wifi_enabled, true)
|
||||||
|
assert_eq(v.status.airplane, false)
|
||||||
|
assert_eq(v.status.has_wifi, true)
|
||||||
|
assert_eq(v.wifi_dev, "/org/freedesktop/NetworkManager/Devices/2")
|
||||||
|
assert_eq(v.wifi_state, 100)
|
||||||
|
// The one in use first, then by signal; the strongest "Office"; no hidden network.
|
||||||
|
assert_eq(v.networks.map(n => n.ssid), ["Home", "Office", "Cafe"])
|
||||||
|
assert_eq(v.networks[0].active, true)
|
||||||
|
assert_eq(v.networks[1], { ssid: "Office", signal: 55, secured: true, active: false, saved: true })
|
||||||
|
assert_eq(v.networks[2].secured, false)
|
||||||
|
assert_eq(v.aps.get("Office").unwrap().path, "/org/freedesktop/NetworkManager/AccessPoint/13")
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "wired, connecting, Wi-Fi off and airplane mode" {
|
||||||
|
let (root, objs) = sample_objects()
|
||||||
|
let nm = "/org/freedesktop/NetworkManager"
|
||||||
|
// Ethernet becomes the primary connection.
|
||||||
|
let conn : Map[String, Map[String, DValue]] = {}
|
||||||
|
conn.set(active_iface, {
|
||||||
|
"Id": Str("Wired connection 1"),
|
||||||
|
"Type": Str("802-3-ethernet"),
|
||||||
|
"Devices": Arr("o", [Path(nm + "/Devices/1")]),
|
||||||
|
})
|
||||||
|
objs.set(nm + "/ActiveConnection/6", conn)
|
||||||
|
root.set("PrimaryConnection", Path(nm + "/ActiveConnection/6"))
|
||||||
|
let v = nm_view(root, objs, {})
|
||||||
|
assert_eq(v.status.state, Wired)
|
||||||
|
assert_eq(v.status.name, "Wired connection 1")
|
||||||
|
assert_eq(v.status.signal, 0)
|
||||||
|
// Nothing up yet, a connection on its way.
|
||||||
|
root.set("PrimaryConnection", Path("/"))
|
||||||
|
root.set("State", U32(40U))
|
||||||
|
root.set("ActivatingConnection", Path(nm + "/ActiveConnection/6"))
|
||||||
|
let c = nm_view(root, objs, {}).status
|
||||||
|
assert_eq(c.state, Connecting)
|
||||||
|
assert_eq(c.name, "Wired connection 1")
|
||||||
|
// Wi-Fi off: no list; airplane mode is Wi-Fi and mobile broadband both off.
|
||||||
|
root.set("WirelessEnabled", Bool(false))
|
||||||
|
let off = nm_view(root, objs, {})
|
||||||
|
assert_eq(off.networks.length(), 0)
|
||||||
|
assert_eq(off.status.wifi_enabled, false)
|
||||||
|
assert_eq(off.status.airplane, false)
|
||||||
|
root.set("WwanEnabled", Bool(false))
|
||||||
|
assert_eq(nm_view(root, objs, {}).status.airplane, true)
|
||||||
|
// Networking off altogether.
|
||||||
|
root.set("NetworkingEnabled", Bool(false))
|
||||||
|
assert_eq(nm_view(root, objs, {}).status.state, Offline)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "security settings for new networks" {
|
||||||
|
let ap = fn(flags : Int, wpa : Int, rsn : Int) {
|
||||||
|
{ path: "/ap", ssid: "x", signal: 50, flags, wpa, rsn }
|
||||||
|
}
|
||||||
|
assert_eq(security_for(ap(0, 0, 0), ""), Ok(None))
|
||||||
|
assert_eq(security_for(ap(1, 0, 0), "k"), Err("WEP networks aren't supported"))
|
||||||
|
assert_eq(security_for(ap(1, 0, 0x200), "k"), Err("Enterprise (802.1X) networks aren't supported yet"))
|
||||||
|
assert_eq(security_for(ap(1, 0, 0x188), ""), Err("A password is needed"))
|
||||||
|
let psk = security_for(ap(1, 0, 0x188), "secret").unwrap().unwrap()
|
||||||
|
assert_eq(dict_map(psk).get("key-mgmt"), Some(Str("wpa-psk")))
|
||||||
|
assert_eq(dict_map(psk).get("psk"), Some(Str("secret")))
|
||||||
|
let sae = security_for(ap(1, 0, 0x400), "secret").unwrap().unwrap()
|
||||||
|
assert_eq(dict_map(sae).get("key-mgmt"), Some(Str("sae")))
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "status from /proc/net and /sys/class/net" {
|
||||||
|
let dev = "Inter-| Receive | Transmit\n face |bytes packets errs\n lo: 100 1 0\n eth0: 5 1 0\nwlan0: 7 1 0\ndocker0: 1 1 0\n"
|
||||||
|
assert_eq(proc_net_dev_names(dev), ["lo", "eth0", "wlan0", "docker0"])
|
||||||
|
let wl = "Inter-| sta-| Quality | Discarded packets\n face | tus | link level noise | nwid crypt\nwlan0: 0000 49. -61. -256 0 0\n"
|
||||||
|
assert_eq(proc_net_wireless(wl), { "wlan0": 70 })
|
||||||
|
let eth = { name: "eth0", wireless: false, physical: true, up: false, quality: -1 }
|
||||||
|
let wlan = { name: "wlan0", wireless: true, physical: true, up: true, quality: 70 }
|
||||||
|
let docker = { name: "docker0", wireless: false, physical: false, up: true, quality: -1 }
|
||||||
|
let s = sysfs_status([eth, wlan, docker])
|
||||||
|
assert_eq(s.state, Wifi)
|
||||||
|
assert_eq(s.name, "wlan0")
|
||||||
|
assert_eq(s.signal, 70)
|
||||||
|
assert_eq(s.managed, false)
|
||||||
|
assert_eq(s.has_wifi, true)
|
||||||
|
assert_eq(sysfs_status([{ ..eth, up: true }, wlan]).state, Wired)
|
||||||
|
assert_eq(sysfs_status([eth, docker]).state, Offline)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "action codes" {
|
||||||
|
assert_eq(NetAction::from_code(0, "", ""), Some(Scan))
|
||||||
|
assert_eq(NetAction::from_code(3, "", ""), Some(SetWifi(true)))
|
||||||
|
assert_eq(NetAction::from_code(5, "", ""), Some(SetAirplane(true)))
|
||||||
|
assert_eq(NetAction::from_code(6, "Home", "pw"), Some(Connect("Home", "pw")))
|
||||||
|
assert_eq(NetAction::from_code(6, "", "pw"), None)
|
||||||
|
assert_eq(NetAction::from_code(7, "Home", ""), Some(Forget("Home")))
|
||||||
|
assert_eq(NetAction::from_code(9, "", ""), None)
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Call a python-dbusmock method (scripts/test-network-dbus.sh runs the mock NetworkManager).
|
||||||
|
fn mock_call(bus : DBus, path : String, meth : String, args : Array[DValue]) -> DMessage {
|
||||||
|
let r = bus.call_sync(DMessage::call(nm_name, path, "org.freedesktop.DBus.Mock", meth, args), 2000).unwrap()
|
||||||
|
if r.mtype == error_reply {
|
||||||
|
abort(meth + ": " + r.error_text())
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Tick `nm` until `ok` holds (or 5 s pass).
|
||||||
|
fn settle(nm : NmBackend, ok : (NmBackend) -> Bool) -> Bool {
|
||||||
|
let until = @sys.monotonic_ms() + 5000UL
|
||||||
|
while @sys.monotonic_ms() < until {
|
||||||
|
NetBackend::tick(nm, @sys.monotonic_ms())
|
||||||
|
if nm.inflight <= 0 && ok(nm) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
@sys.sleep_ms(20)
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Against a real bus: auth, Hello, framing, and the NetworkManager calls, with python-dbusmock's
|
||||||
|
/// NetworkManager template standing in. Skipped unless CHANDRA_NM_E2E=1 (the script sets it).
|
||||||
|
test "NetworkManager over a real bus (python-dbusmock)" {
|
||||||
|
if @sys.getenv("CHANDRA_NM_E2E") != "1" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let bus = DBus::open(system_bus_path()).unwrap()
|
||||||
|
let mock = "/org/freedesktop"
|
||||||
|
let s = fn(m : DMessage) {
|
||||||
|
match m.body {
|
||||||
|
[Str(x), ..] => x
|
||||||
|
_ => abort("no path")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let dev = s(mock_call(bus, mock, "AddWiFiDevice", [Str("wifi0"), Str("wlan0"), I32(100)]))
|
||||||
|
let ap1 = s(
|
||||||
|
mock_call(bus, mock, "AddAccessPoint", [
|
||||||
|
Str(dev),
|
||||||
|
Str("ap1"),
|
||||||
|
Str("Home"),
|
||||||
|
Str("00:11:22:33:44:55"),
|
||||||
|
U32(2U),
|
||||||
|
U32(2437U),
|
||||||
|
U32(54000U),
|
||||||
|
Byte(72),
|
||||||
|
U32(0x100U),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
ignore(
|
||||||
|
mock_call(bus, mock, "AddAccessPoint", [
|
||||||
|
Str(dev),
|
||||||
|
Str("ap2"),
|
||||||
|
Str("Cafe"),
|
||||||
|
Str("00:11:22:33:44:66"),
|
||||||
|
U32(2U),
|
||||||
|
U32(2412U),
|
||||||
|
U32(54000U),
|
||||||
|
Byte(40),
|
||||||
|
U32(0U),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
let con = s(mock_call(bus, mock, "AddWiFiConnection", [Str(dev), Str("con1"), Str("Home"), Str("wpa-psk")]))
|
||||||
|
let act = s(
|
||||||
|
mock_call(bus, mock, "AddActiveConnection", [Arr("s", [Str(dev)]), Str(con), Str(ap1), Str("act1"), U32(2U)]),
|
||||||
|
)
|
||||||
|
ignore(mock_call(bus, nm_path, "AddProperty", [Str(nm_name), Str("PrimaryConnection"), Variant(Path(act))]))
|
||||||
|
ignore(mock_call(bus, dev, "AddProperty", [Str(wifi_iface), Str("ActiveAccessPoint"), Variant(Path(ap1))]))
|
||||||
|
ignore(mock_call(bus, mock, "SetProperty", [Str(nm_path), Str(nm_name), Str("WwanEnabled"), Variant(Bool(true))]))
|
||||||
|
let nm = NmBackend::connect().unwrap()
|
||||||
|
assert_eq(
|
||||||
|
settle(nm, n => NetBackend::status(n).state == Wifi && NetBackend::networks(n).length() == 2 && NetBackend::networks(n)[0].saved),
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
assert_eq(NetBackend::status(nm).name, "Home")
|
||||||
|
assert_eq(NetBackend::status(nm).signal, 72)
|
||||||
|
assert_eq(NetBackend::status(nm).managed, true)
|
||||||
|
assert_eq(
|
||||||
|
NetBackend::networks(nm),
|
||||||
|
[
|
||||||
|
{ ssid: "Home", signal: 72, secured: true, active: true, saved: true },
|
||||||
|
{ ssid: "Cafe", signal: 40, secured: false, active: false, saved: false },
|
||||||
|
],
|
||||||
|
)
|
||||||
|
// Wi-Fi off and on again; airplane mode.
|
||||||
|
NetBackend::act(nm, SetWifi(false))
|
||||||
|
assert_eq(settle(nm, n => !NetBackend::status(n).wifi_enabled && NetBackend::networks(n).length() == 0), true)
|
||||||
|
assert_eq(NetBackend::status(nm).airplane, false)
|
||||||
|
NetBackend::act(nm, SetAirplane(true))
|
||||||
|
assert_eq(settle(nm, n => NetBackend::status(n).airplane), true)
|
||||||
|
NetBackend::act(nm, SetAirplane(false))
|
||||||
|
assert_eq(settle(nm, n => NetBackend::status(n).wifi_enabled && !NetBackend::status(n).airplane), true)
|
||||||
|
// A new open network: AddAndActivateConnection makes a saved connection for it.
|
||||||
|
NetBackend::act(nm, Scan)
|
||||||
|
NetBackend::act(nm, Connect("Cafe", ""))
|
||||||
|
assert_eq(settle(nm, n => NetBackend::networks(n).iter().any(w => w.ssid == "Cafe" && w.saved)), true)
|
||||||
|
// A secured one with no password is refused here, before NetworkManager.
|
||||||
|
ignore(mock_call(bus, mock, "AddAccessPoint", [
|
||||||
|
Str(dev),
|
||||||
|
Str("ap3"),
|
||||||
|
Str("Office"),
|
||||||
|
Str("00:11:22:33:44:77"),
|
||||||
|
U32(2U),
|
||||||
|
U32(5180U),
|
||||||
|
U32(54000U),
|
||||||
|
Byte(30),
|
||||||
|
U32(0x100U),
|
||||||
|
]))
|
||||||
|
assert_eq(settle(nm, n => NetBackend::networks(n).length() == 3), true)
|
||||||
|
NetBackend::act(nm, Connect("Office", ""))
|
||||||
|
assert_eq(NetBackend::status(nm).message, "A password is needed")
|
||||||
|
// Forget deletes the saved connection.
|
||||||
|
NetBackend::act(nm, Forget("Cafe"))
|
||||||
|
assert_eq(settle(nm, n => NetBackend::networks(n).iter().any(w => w.ssid == "Cafe" && !w.saved)), true)
|
||||||
|
bus.close()
|
||||||
|
}
|
||||||
@@ -0,0 +1,639 @@
|
|||||||
|
///| NetworkManager over D-Bus (org.freedesktop.NetworkManager). Every couple of seconds one
|
||||||
|
/// ObjectManager.GetManagedObjects call fetches the devices, access points and active connections,
|
||||||
|
/// plus Properties.GetAll on the manager; saved connections' Wi-Fi names are read once each with
|
||||||
|
/// GetSettings. Actions are plain method calls: RequestScan, Device.Disconnect, setting
|
||||||
|
/// WirelessEnabled / WwanEnabled, ActivateConnection (a saved network), AddAndActivateConnection
|
||||||
|
/// (a new one, WPA/WPA3 personal with a password, or open) and Settings.Connection.Delete. All of
|
||||||
|
/// it is asynchronous: nothing waits for NetworkManager except the first connect.
|
||||||
|
|
||||||
|
///|
|
||||||
|
let nm_name : String = "org.freedesktop.NetworkManager"
|
||||||
|
|
||||||
|
///|
|
||||||
|
let nm_path : String = "/org/freedesktop/NetworkManager"
|
||||||
|
|
||||||
|
///|
|
||||||
|
let props_iface : String = "org.freedesktop.DBus.Properties"
|
||||||
|
|
||||||
|
///|
|
||||||
|
let dev_iface : String = "org.freedesktop.NetworkManager.Device"
|
||||||
|
|
||||||
|
///|
|
||||||
|
let wifi_iface : String = "org.freedesktop.NetworkManager.Device.Wireless"
|
||||||
|
|
||||||
|
///|
|
||||||
|
let ap_iface : String = "org.freedesktop.NetworkManager.AccessPoint"
|
||||||
|
|
||||||
|
///|
|
||||||
|
let active_iface : String = "org.freedesktop.NetworkManager.Connection.Active"
|
||||||
|
|
||||||
|
///|
|
||||||
|
let setting_iface : String = "org.freedesktop.NetworkManager.Settings.Connection"
|
||||||
|
|
||||||
|
///| NetworkManager device types and states we look at.
|
||||||
|
let dev_type_ethernet : Int = 1
|
||||||
|
|
||||||
|
///|
|
||||||
|
let dev_type_wifi : Int = 2
|
||||||
|
|
||||||
|
///| NM_DEVICE_STATE_*: 30 disconnected, 40-90 on the way (prepare ... secondaries), 100 activated,
|
||||||
|
/// 120 failed.
|
||||||
|
let dev_state_disconnected : Int = 30
|
||||||
|
|
||||||
|
///|
|
||||||
|
let dev_state_activated : Int = 100
|
||||||
|
|
||||||
|
///|
|
||||||
|
let dev_state_failed : Int = 120
|
||||||
|
|
||||||
|
///| NM_DEVICE_STATE_REASON_NO_SECRETS: the password was wrong or missing.
|
||||||
|
let reason_no_secrets : Int = 7
|
||||||
|
|
||||||
|
// ---- reading replies ----
|
||||||
|
|
||||||
|
///| Unwrap variants.
|
||||||
|
fn plain(v : DValue) -> DValue {
|
||||||
|
match v {
|
||||||
|
Variant(x) => plain(x)
|
||||||
|
_ => v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn as_str(v : DValue?) -> String {
|
||||||
|
match v.map(plain) {
|
||||||
|
Some(Str(s)) | Some(Path(s)) => s
|
||||||
|
_ => ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn as_int(v : DValue?) -> Int {
|
||||||
|
match v.map(plain) {
|
||||||
|
Some(U32(x)) => x.reinterpret_as_int()
|
||||||
|
Some(I32(x)) | Some(Byte(x)) => x
|
||||||
|
_ => 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn as_bool(v : DValue?) -> Bool {
|
||||||
|
match v.map(plain) {
|
||||||
|
Some(Bool(b)) => b
|
||||||
|
_ => false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn as_paths(v : DValue?) -> Array[String] {
|
||||||
|
match v.map(plain) {
|
||||||
|
Some(Arr(_, items)) =>
|
||||||
|
items.filter_map(it => match it {
|
||||||
|
Path(p) => Some(p)
|
||||||
|
_ => None
|
||||||
|
})
|
||||||
|
_ => []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| An a{s?} dict as a map (values with their variants unwrapped).
|
||||||
|
pub fn dict_map(v : DValue) -> Map[String, DValue] {
|
||||||
|
let m : Map[String, DValue] = {}
|
||||||
|
if plain(v) is Arr(_, items) {
|
||||||
|
for it in items {
|
||||||
|
if it is Entry(k, x) {
|
||||||
|
match k {
|
||||||
|
Str(s) | Path(s) => m.set(s, plain(x))
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
///| GetManagedObjects' a{oa{sa{sv}}}: path -> interface -> property -> value.
|
||||||
|
pub fn objects_map(v : DValue) -> Map[String, Map[String, Map[String, DValue]]] {
|
||||||
|
let out : Map[String, Map[String, Map[String, DValue]]] = {}
|
||||||
|
if v is Arr(_, objs) {
|
||||||
|
for o in objs {
|
||||||
|
if o is Entry(Path(p), ifaces) {
|
||||||
|
let im : Map[String, Map[String, DValue]] = {}
|
||||||
|
if ifaces is Arr(_, items) {
|
||||||
|
for it in items {
|
||||||
|
if it is Entry(Str(name), props) {
|
||||||
|
im.set(name, dict_map(props))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.set(p, im)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The Wi-Fi name in a saved connection's GetSettings reply (a{sa{sv}}), "" if it isn't Wi-Fi.
|
||||||
|
pub fn settings_ssid(v : DValue) -> String {
|
||||||
|
let groups = dict_map(v)
|
||||||
|
match groups.get("802-11-wireless") {
|
||||||
|
Some(w) => dict_map(w).get("ssid").map(x => x.bytes_text()).unwrap_or("")
|
||||||
|
None => ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- turning NetworkManager's objects into what the panel shows ----
|
||||||
|
|
||||||
|
///| An access point we could connect to.
|
||||||
|
pub(all) struct NmAp {
|
||||||
|
path : String
|
||||||
|
ssid : String
|
||||||
|
signal : Int
|
||||||
|
flags : Int
|
||||||
|
wpa : Int
|
||||||
|
rsn : Int
|
||||||
|
} derive(Eq, Debug)
|
||||||
|
|
||||||
|
///| What NetworkManager's state means for the panel.
|
||||||
|
pub(all) struct NmView {
|
||||||
|
status : NetStatus
|
||||||
|
networks : Array[WifiNetwork]
|
||||||
|
/// The Wi-Fi device ("" for none), its state and the reason for it.
|
||||||
|
wifi_dev : String
|
||||||
|
wifi_state : Int
|
||||||
|
wifi_reason : Int
|
||||||
|
/// The strongest access point for each network name.
|
||||||
|
aps : Map[String, NmAp]
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn prop(
|
||||||
|
objs : Map[String, Map[String, Map[String, DValue]]],
|
||||||
|
path : String,
|
||||||
|
iface : String,
|
||||||
|
name : String,
|
||||||
|
) -> DValue? {
|
||||||
|
objs.get(path).bind(o => o.get(iface)).bind(p => p.get(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Build the view from the manager's properties (`root`), the managed objects and the saved
|
||||||
|
/// connections' Wi-Fi names (settings path -> name).
|
||||||
|
pub fn nm_view(
|
||||||
|
root : Map[String, DValue],
|
||||||
|
objs : Map[String, Map[String, Map[String, DValue]]],
|
||||||
|
saved : Map[String, String],
|
||||||
|
) -> NmView {
|
||||||
|
let wifi_on = as_bool(root.get("WirelessEnabled"))
|
||||||
|
let wwan_on = as_bool(root.get("WwanEnabled"))
|
||||||
|
let networking = root.get("NetworkingEnabled").map(x => as_bool(Some(x))).unwrap_or(true)
|
||||||
|
let nm_state = as_int(root.get("State"))
|
||||||
|
// The Wi-Fi device: the first one, preferring one that is in use.
|
||||||
|
let mut wifi_dev = ""
|
||||||
|
for path, ifaces in objs {
|
||||||
|
if as_int(ifaces.get(dev_iface).bind(d => d.get("DeviceType"))) == dev_type_wifi {
|
||||||
|
let busy = as_str(prop(objs, path, dev_iface, "ActiveConnection")) != "/" &&
|
||||||
|
as_str(prop(objs, path, dev_iface, "ActiveConnection")) != ""
|
||||||
|
if wifi_dev == "" || busy {
|
||||||
|
wifi_dev = path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let ap_of = fn(path : String) -> NmAp {
|
||||||
|
{
|
||||||
|
path,
|
||||||
|
ssid: prop(objs, path, ap_iface, "Ssid").map(x => x.bytes_text()).unwrap_or(""),
|
||||||
|
signal: as_int(prop(objs, path, ap_iface, "Strength")),
|
||||||
|
flags: as_int(prop(objs, path, ap_iface, "Flags")),
|
||||||
|
wpa: as_int(prop(objs, path, ap_iface, "WpaFlags")),
|
||||||
|
rsn: as_int(prop(objs, path, ap_iface, "RsnFlags")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let active_ap = as_str(prop(objs, wifi_dev, wifi_iface, "ActiveAccessPoint"))
|
||||||
|
let active = if active_ap != "" && active_ap != "/" { Some(ap_of(active_ap)) } else { None }
|
||||||
|
// Networks in range: one entry per name, its strongest access point.
|
||||||
|
let aps : Map[String, NmAp] = {}
|
||||||
|
for p in as_paths(prop(objs, wifi_dev, wifi_iface, "AccessPoints")) {
|
||||||
|
let ap = ap_of(p)
|
||||||
|
if ap.ssid == "" {
|
||||||
|
continue // hidden networks
|
||||||
|
}
|
||||||
|
match aps.get(ap.ssid) {
|
||||||
|
Some(o) if o.signal >= ap.signal => ()
|
||||||
|
_ => aps.set(ap.ssid, ap)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let saved_names : Map[String, Bool] = {}
|
||||||
|
for _, n in saved {
|
||||||
|
if n != "" {
|
||||||
|
saved_names.set(n, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let active_ssid = match active {
|
||||||
|
Some(a) => a.ssid
|
||||||
|
None => ""
|
||||||
|
}
|
||||||
|
let networks : Array[WifiNetwork] = []
|
||||||
|
for name, ap in aps {
|
||||||
|
networks.push({
|
||||||
|
ssid: name,
|
||||||
|
signal: ap.signal,
|
||||||
|
secured: (ap.flags & 1) != 0 || ap.wpa != 0 || ap.rsn != 0,
|
||||||
|
active: name == active_ssid,
|
||||||
|
saved: saved_names.contains(name),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
networks.sort_by((a, b) => if a.active != b.active {
|
||||||
|
if a.active { -1 } else { 1 }
|
||||||
|
} else if a.signal != b.signal {
|
||||||
|
b.signal - a.signal
|
||||||
|
} else {
|
||||||
|
a.ssid.compare(b.ssid)
|
||||||
|
})
|
||||||
|
// The connection the default route goes through.
|
||||||
|
let primary = as_str(root.get("PrimaryConnection"))
|
||||||
|
let mut state = NetState::Offline
|
||||||
|
let mut name = ""
|
||||||
|
let mut signal = 0
|
||||||
|
if networking && primary != "" && primary != "/" {
|
||||||
|
let devs = as_paths(prop(objs, primary, active_iface, "Devices"))
|
||||||
|
let dtype = match devs {
|
||||||
|
[d, ..] => as_int(prop(objs, d, dev_iface, "DeviceType"))
|
||||||
|
[] => 0
|
||||||
|
}
|
||||||
|
let ctype = as_str(prop(objs, primary, active_iface, "Type"))
|
||||||
|
if dtype == dev_type_wifi || ctype == "802-11-wireless" {
|
||||||
|
state = Wifi
|
||||||
|
match active {
|
||||||
|
Some(a) => {
|
||||||
|
name = a.ssid
|
||||||
|
signal = a.signal
|
||||||
|
}
|
||||||
|
None => name = as_str(prop(objs, primary, active_iface, "Id"))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
state = Wired
|
||||||
|
name = as_str(prop(objs, primary, active_iface, "Id"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Activating (NM_STATE_CONNECTING, or a connection on its way) while nothing else is up.
|
||||||
|
if state == Offline && networking {
|
||||||
|
let activating = as_str(root.get("ActivatingConnection"))
|
||||||
|
if nm_state == 40 || (activating != "" && activating != "/") {
|
||||||
|
state = Connecting
|
||||||
|
name = as_str(prop(objs, activating, active_iface, "Id"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (wstate, wreason) = match prop(objs, wifi_dev, dev_iface, "StateReason") {
|
||||||
|
Some(Struct([U32(s), U32(r)])) => (s.reinterpret_as_int(), r.reinterpret_as_int())
|
||||||
|
_ => (as_int(prop(objs, wifi_dev, dev_iface, "State")), 0)
|
||||||
|
}
|
||||||
|
{
|
||||||
|
status: {
|
||||||
|
state,
|
||||||
|
name,
|
||||||
|
signal,
|
||||||
|
message: "",
|
||||||
|
wifi_enabled: wifi_on,
|
||||||
|
airplane: !wifi_on && !wwan_on,
|
||||||
|
managed: true,
|
||||||
|
has_wifi: wifi_dev != "",
|
||||||
|
},
|
||||||
|
networks: if wifi_on && wifi_dev != "" { networks } else { [] },
|
||||||
|
wifi_dev,
|
||||||
|
wifi_state: wstate,
|
||||||
|
wifi_reason: wreason,
|
||||||
|
aps,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The 802-11-wireless-security settings for a new connection to `ap`: Ok(None) for an open
|
||||||
|
/// network, Err(why) for one we can't set up here.
|
||||||
|
pub fn security_for(ap : NmAp, password : String) -> Result[DValue?, String] {
|
||||||
|
let ap_psk = 0x100
|
||||||
|
let ap_8021x = 0x200
|
||||||
|
let ap_sae = 0x400
|
||||||
|
let km = ap.wpa | ap.rsn
|
||||||
|
if km == 0 && (ap.flags & 1) == 0 {
|
||||||
|
return Ok(None)
|
||||||
|
}
|
||||||
|
if km == 0 {
|
||||||
|
return Err("WEP networks aren't supported")
|
||||||
|
}
|
||||||
|
if (km & (ap_psk | ap_sae)) == 0 && (km & ap_8021x) != 0 {
|
||||||
|
return Err("Enterprise (802.1X) networks aren't supported yet")
|
||||||
|
}
|
||||||
|
if password == "" {
|
||||||
|
return Err("A password is needed")
|
||||||
|
}
|
||||||
|
let key_mgmt = if (km & ap_psk) == 0 && (km & ap_sae) != 0 { "sae" } else { "wpa-psk" }
|
||||||
|
Ok(Some(dict("v", [("key-mgmt", Variant(Str(key_mgmt))), ("psk", Variant(Str(password)))])))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the backend ----
|
||||||
|
|
||||||
|
///| Talks to NetworkManager.
|
||||||
|
pub struct NmBackend {
|
||||||
|
bus : DBus
|
||||||
|
mut root : Map[String, DValue]
|
||||||
|
mut objs : Map[String, Map[String, Map[String, DValue]]]
|
||||||
|
/// Saved connection path -> its Wi-Fi name ("" for other kinds, or while it is being read).
|
||||||
|
saved : Map[String, String]
|
||||||
|
mut view : NmView
|
||||||
|
mut next_refresh : UInt64
|
||||||
|
mut inflight : Int
|
||||||
|
mut message : String
|
||||||
|
mut message_until : UInt64
|
||||||
|
/// A connection being made: the network, until when we watch it, and whether the device got
|
||||||
|
/// on its way (so a later disconnected state means it failed).
|
||||||
|
mut pending : String
|
||||||
|
mut pending_until : UInt64
|
||||||
|
mut pending_seen : Bool
|
||||||
|
mut now : UInt64
|
||||||
|
mut gone : Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
///| How often to re-read NetworkManager.
|
||||||
|
let refresh_ms : UInt64 = 2000UL
|
||||||
|
|
||||||
|
///| Connect to NetworkManager on the system bus; None when it isn't running.
|
||||||
|
pub fn NmBackend::connect() -> NmBackend? {
|
||||||
|
let bus = match DBus::open(system_bus_path()) {
|
||||||
|
Some(b) => b
|
||||||
|
None => return None
|
||||||
|
}
|
||||||
|
// Is NetworkManager there at all? (A bus without it would only give errors.)
|
||||||
|
let has = bus.call_sync(
|
||||||
|
DMessage::call(
|
||||||
|
"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner", [
|
||||||
|
Str(nm_name),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
1000,
|
||||||
|
)
|
||||||
|
match has.map(m => m.body) {
|
||||||
|
Some([Bool(true), ..]) => ()
|
||||||
|
_ => {
|
||||||
|
bus.close()
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some({
|
||||||
|
bus,
|
||||||
|
root: {},
|
||||||
|
objs: {},
|
||||||
|
saved: {},
|
||||||
|
view: nm_view({}, {}, {}),
|
||||||
|
next_refresh: 0UL,
|
||||||
|
inflight: 0,
|
||||||
|
message: "",
|
||||||
|
message_until: 0UL,
|
||||||
|
pending: "",
|
||||||
|
pending_until: 0UL,
|
||||||
|
pending_seen: false,
|
||||||
|
now: 0UL,
|
||||||
|
gone: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn NmBackend::say(self : NmBackend, s : String) -> Unit {
|
||||||
|
self.message = s
|
||||||
|
self.message_until = self.now + 8000UL
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Turn an error reply into something to show.
|
||||||
|
fn nm_error(m : DMessage) -> String {
|
||||||
|
let n = m.error_name
|
||||||
|
if n.has_suffix("PermissionDenied") || n.has_suffix("AccessDenied") {
|
||||||
|
"Not allowed: " + m.error_text()
|
||||||
|
} else {
|
||||||
|
m.error_text()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn NmBackend::nm_call(
|
||||||
|
self : NmBackend,
|
||||||
|
path : String,
|
||||||
|
iface : String,
|
||||||
|
meth : String,
|
||||||
|
args : Array[DValue],
|
||||||
|
on_ok? : (DMessage) -> Unit = _ => (),
|
||||||
|
) -> Unit {
|
||||||
|
ignore(
|
||||||
|
self.bus.call(DMessage::call(nm_name, path, iface, meth, args), on_reply=m => if m.mtype ==
|
||||||
|
error_reply {
|
||||||
|
if m.error_name == "org.freedesktop.DBus.Error.ServiceUnknown" ||
|
||||||
|
m.error_name == "org.freedesktop.DBus.Error.NameHasNoOwner" {
|
||||||
|
self.gone = true
|
||||||
|
} else {
|
||||||
|
self.say(nm_error(m))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
on_ok(m)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Ask for fresh state.
|
||||||
|
fn NmBackend::refresh(self : NmBackend) -> Unit {
|
||||||
|
self.inflight = 2
|
||||||
|
let done = fn() {
|
||||||
|
self.inflight = self.inflight - 1
|
||||||
|
if self.inflight <= 0 {
|
||||||
|
self.recompute()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ignore(
|
||||||
|
self.bus.call(
|
||||||
|
DMessage::call(nm_name, nm_path, props_iface, "GetAll", [Str(nm_name)]),
|
||||||
|
on_reply=m => {
|
||||||
|
match (m.mtype, m.body) {
|
||||||
|
(2, [d, ..]) => self.root = dict_map(d)
|
||||||
|
_ =>
|
||||||
|
if m.error_name.has_prefix("org.freedesktop.DBus.Error.ServiceUnknown") ||
|
||||||
|
m.error_name.has_prefix("org.freedesktop.DBus.Error.NameHasNoOwner") {
|
||||||
|
self.gone = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
done()
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
ignore(
|
||||||
|
self.bus.call(
|
||||||
|
DMessage::call(
|
||||||
|
nm_name, "/org/freedesktop", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", [],
|
||||||
|
),
|
||||||
|
on_reply=m => {
|
||||||
|
match (m.mtype, m.body) {
|
||||||
|
(2, [o, ..]) => self.objs = objects_map(o)
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
|
done()
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Recompute the view, read the names of newly seen saved connections, and follow a connection
|
||||||
|
/// being made.
|
||||||
|
fn NmBackend::recompute(self : NmBackend) -> Unit {
|
||||||
|
// Saved connections: forget deleted ones, read new ones.
|
||||||
|
let present : Map[String, Bool] = {}
|
||||||
|
for path, ifaces in self.objs {
|
||||||
|
if ifaces.contains(setting_iface) {
|
||||||
|
present.set(path, true)
|
||||||
|
if !self.saved.contains(path) {
|
||||||
|
self.saved.set(path, "")
|
||||||
|
self.nm_call(path, setting_iface, "GetSettings", [], on_ok=m => match m.body {
|
||||||
|
[s, ..] => {
|
||||||
|
self.saved.set(path, settings_ssid(s))
|
||||||
|
self.view = nm_view(self.root, self.objs, self.saved)
|
||||||
|
}
|
||||||
|
_ => ()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let gone_paths = self.saved.keys().filter(p => !present.contains(p)).collect()
|
||||||
|
for p in gone_paths {
|
||||||
|
self.saved.remove(p)
|
||||||
|
}
|
||||||
|
self.view = nm_view(self.root, self.objs, self.saved)
|
||||||
|
if self.pending != "" {
|
||||||
|
let v = self.view
|
||||||
|
if v.status.state == Wifi && v.status.name == self.pending {
|
||||||
|
self.say("Connected to " + self.pending)
|
||||||
|
self.pending = ""
|
||||||
|
} else if v.wifi_state > dev_state_disconnected && v.wifi_state < dev_state_activated {
|
||||||
|
self.pending_seen = true
|
||||||
|
} else if self.pending_seen &&
|
||||||
|
(v.wifi_state == dev_state_failed || v.wifi_state <= dev_state_disconnected) {
|
||||||
|
self.say(
|
||||||
|
"Couldn't connect to " +
|
||||||
|
self.pending +
|
||||||
|
(if v.wifi_reason == reason_no_secrets { ": wrong password?" } else { "" }),
|
||||||
|
)
|
||||||
|
self.pending = ""
|
||||||
|
} else if self.now > self.pending_until {
|
||||||
|
self.say("Couldn't connect to " + self.pending)
|
||||||
|
self.pending = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for NmBackend with tick(self, now) {
|
||||||
|
self.now = now
|
||||||
|
self.bus.pump()
|
||||||
|
if !self.bus.alive {
|
||||||
|
self.gone = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if self.inflight <= 0 && now >= self.next_refresh {
|
||||||
|
self.next_refresh = now + (if self.pending != "" { 1000UL } else { refresh_ms })
|
||||||
|
self.refresh()
|
||||||
|
}
|
||||||
|
if self.message != "" && now > self.message_until && self.pending == "" {
|
||||||
|
self.message = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for NmBackend with status(self) {
|
||||||
|
let s = self.view.status
|
||||||
|
let msg = if self.pending != "" && self.message == "" {
|
||||||
|
"Connecting to " + self.pending + "..."
|
||||||
|
} else {
|
||||||
|
self.message
|
||||||
|
}
|
||||||
|
{ ..s, message: msg }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for NmBackend with networks(self) {
|
||||||
|
self.view.networks
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for NmBackend with close(self) {
|
||||||
|
self.bus.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for NmBackend with alive(self) {
|
||||||
|
!self.gone && self.bus.alive
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn NmBackend::set_prop(self : NmBackend, name : String, v : DValue) -> Unit {
|
||||||
|
self.nm_call(nm_path, props_iface, "Set", [Str(nm_name), Str(name), Variant(v)])
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for NmBackend with act(self, a) {
|
||||||
|
let dev = self.view.wifi_dev
|
||||||
|
self.next_refresh = self.now + 300UL // show the outcome soon
|
||||||
|
match a {
|
||||||
|
Scan =>
|
||||||
|
if dev != "" {
|
||||||
|
// Scanning too often is refused; that isn't worth a message.
|
||||||
|
ignore(self.bus.call(DMessage::call(nm_name, dev, wifi_iface, "RequestScan", [dict("v", [])])))
|
||||||
|
}
|
||||||
|
Disconnect =>
|
||||||
|
if dev != "" {
|
||||||
|
self.pending = ""
|
||||||
|
self.nm_call(dev, dev_iface, "Disconnect", [])
|
||||||
|
}
|
||||||
|
SetWifi(on) => self.set_prop("WirelessEnabled", Bool(on))
|
||||||
|
SetAirplane(on) => {
|
||||||
|
self.set_prop("WirelessEnabled", Bool(!on))
|
||||||
|
self.set_prop("WwanEnabled", Bool(!on))
|
||||||
|
}
|
||||||
|
Connect(ssid, password) => {
|
||||||
|
if dev == "" {
|
||||||
|
self.say("No Wi-Fi device")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let saved = self.saved.iter().filter(e => e.1 == ssid).map(e => e.0).collect()
|
||||||
|
let start = fn() {
|
||||||
|
self.pending = ssid
|
||||||
|
self.pending_seen = false
|
||||||
|
self.pending_until = self.now + 45000UL
|
||||||
|
self.message = ""
|
||||||
|
}
|
||||||
|
if saved.length() > 0 && password == "" {
|
||||||
|
start()
|
||||||
|
self.nm_call(nm_path, nm_name, "ActivateConnection", [Path(saved[0]), Path(dev), Path("/")])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
match self.view.aps.get(ssid) {
|
||||||
|
None => self.say(ssid + " is out of range")
|
||||||
|
Some(ap) =>
|
||||||
|
match security_for(ap, password) {
|
||||||
|
Err(why) => self.say(why)
|
||||||
|
Ok(sec) => {
|
||||||
|
let groups = [("802-11-wireless", dict("v", [("ssid", Variant(byte_array(ssid)))]))]
|
||||||
|
match sec {
|
||||||
|
Some(s) => groups.push(("802-11-wireless-security", s))
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
start()
|
||||||
|
self.nm_call(nm_path, nm_name, "AddAndActivateConnection", [
|
||||||
|
dict("a{sv}", groups),
|
||||||
|
Path(dev),
|
||||||
|
Path(ap.path),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Forget(ssid) =>
|
||||||
|
for path, name in self.saved {
|
||||||
|
if name == ssid {
|
||||||
|
self.nm_call(path, setting_iface, "Delete", [], on_ok=_ => self.say("Forgot " + ssid))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
///| Read-only status without NetworkManager: interfaces from /proc/net/dev, whether each is a
|
||||||
|
/// physical Ethernet or Wi-Fi device and up from /sys/class/net/<if>, and Wi-Fi link quality from
|
||||||
|
/// /proc/net/wireless. The network's name isn't there (that needs nl80211), so the interface's
|
||||||
|
/// name stands in. Nothing can be changed.
|
||||||
|
|
||||||
|
///| One interface's state, as read.
|
||||||
|
pub(all) struct IfState {
|
||||||
|
name : String
|
||||||
|
wireless : Bool
|
||||||
|
physical : Bool
|
||||||
|
up : Bool
|
||||||
|
/// Link quality 0..100 (Wi-Fi), -1 unknown.
|
||||||
|
quality : Int
|
||||||
|
} derive(Eq, Debug)
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn read_text(path : String) -> String {
|
||||||
|
@utf8.decode_lossy(@sys.read_proc_bytes(path)).trim(chars=" \n\t").to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Interface names in /proc/net/dev.
|
||||||
|
pub fn proc_net_dev_names(text : String) -> Array[String] {
|
||||||
|
let out : Array[String] = []
|
||||||
|
for line in text.split("\n") {
|
||||||
|
match line.find(":") {
|
||||||
|
Some(i) => {
|
||||||
|
let name = line[:i].trim(chars=" ").to_string()
|
||||||
|
if name != "" && !name.contains("|") {
|
||||||
|
out.push(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Link quality per interface from /proc/net/wireless ("wlan0: 0000 54. -56. -256 ..."),
|
||||||
|
/// scaled from the usual 0..70 to 0..100.
|
||||||
|
pub fn proc_net_wireless(text : String) -> Map[String, Int] {
|
||||||
|
let out : Map[String, Int] = {}
|
||||||
|
for line in text.split("\n") {
|
||||||
|
match line.find(":") {
|
||||||
|
Some(i) => {
|
||||||
|
let name = line[:i].trim(chars=" ").to_string()
|
||||||
|
let rest = line[i + 1:].to_string()
|
||||||
|
let fs = rest.split(" ").filter(f => f != "").map(f => f.to_string()).collect()
|
||||||
|
if name != "" && fs.length() >= 2 && !name.contains("|") {
|
||||||
|
let mut q = 0
|
||||||
|
for c in fs[1] {
|
||||||
|
if c >= '0' && c <= '9' {
|
||||||
|
q = q * 10 + (c.to_int() - 48)
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.set(name, if q >= 70 { 100 } else { q * 100 / 70 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
///| What the interfaces say about the connection: Ethernet up wins, then Wi-Fi up.
|
||||||
|
pub fn sysfs_status(ifs : Array[IfState]) -> NetStatus {
|
||||||
|
let has_wifi = ifs.iter().any(i => i.wireless)
|
||||||
|
let base = { ..NetStatus::offline(), has_wifi, wifi_enabled: has_wifi }
|
||||||
|
for i in ifs {
|
||||||
|
if i.up && i.physical && !i.wireless {
|
||||||
|
return { ..base, state: Wired, name: i.name }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i in ifs {
|
||||||
|
if i.up && i.wireless {
|
||||||
|
return { ..base, state: Wifi, name: i.name, signal: if i.quality < 0 { 0 } else { i.quality } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
base
|
||||||
|
}
|
||||||
|
|
||||||
|
///| The read-only backend.
|
||||||
|
pub struct SysfsBackend {
|
||||||
|
mut status : NetStatus
|
||||||
|
mut next : UInt64
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn SysfsBackend::new() -> SysfsBackend {
|
||||||
|
{ status: NetStatus::offline(), next: 0UL }
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Read the interfaces now.
|
||||||
|
pub fn read_interfaces() -> Array[IfState] {
|
||||||
|
let quality = proc_net_wireless(read_text("/proc/net/wireless"))
|
||||||
|
let out : Array[IfState] = []
|
||||||
|
for name in proc_net_dev_names(read_text("/proc/net/dev")) {
|
||||||
|
if name == "lo" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let base = "/sys/class/net/" + name
|
||||||
|
let wireless = quality.contains(name) || read_text(base + "/phy80211/name") != ""
|
||||||
|
// Physical devices have a device link (veth, bridges, docker0, tun don't).
|
||||||
|
let physical = read_text(base + "/device/uevent") != ""
|
||||||
|
let oper = read_text(base + "/operstate")
|
||||||
|
let carrier = read_text(base + "/carrier")
|
||||||
|
out.push({
|
||||||
|
name,
|
||||||
|
wireless,
|
||||||
|
physical,
|
||||||
|
up: oper == "up" || (oper == "unknown" && carrier == "1"),
|
||||||
|
quality: quality.get(name).unwrap_or(-1),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for SysfsBackend with tick(self, now) {
|
||||||
|
if now >= self.next {
|
||||||
|
self.next = now + 3000UL
|
||||||
|
let s = sysfs_status(read_interfaces())
|
||||||
|
self.status = { ..s, message: "NetworkManager isn't running: status only" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for SysfsBackend with status(self) {
|
||||||
|
self.status
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for SysfsBackend with networks(_self) {
|
||||||
|
[]
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for SysfsBackend with act(_self, _a) {
|
||||||
|
()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub impl NetBackend for SysfsBackend with alive(_self) {
|
||||||
|
true
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
"chandra/desktop/compositor/renderer" @renderer,
|
"chandra/desktop/compositor/renderer" @renderer,
|
||||||
"chandra/desktop/compositor/raster" @raster,
|
"chandra/desktop/compositor/raster" @raster,
|
||||||
"chandra/desktop/compositor/wasm" @wasm,
|
"chandra/desktop/compositor/wasm" @wasm,
|
||||||
|
"chandra/desktop/compositor/network" @network,
|
||||||
}
|
}
|
||||||
|
|
||||||
supported_targets = "+native+wasm"
|
supported_targets = "+native+wasm"
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
///| The `network` capability: the shell keeps a network service (compositor/network: NetworkManager
|
||||||
|
/// over D-Bus, else read-only /sys status) while a module imports it, publishes its status and the
|
||||||
|
/// Wi-Fi networks in range as host tables every frame, and hands the module's actions to it.
|
||||||
|
|
||||||
|
///| Start the network service if a module needs it (tests can set their own first).
|
||||||
|
fn DesktopShell::network(self : DesktopShell) -> @network.NetService {
|
||||||
|
match self.net {
|
||||||
|
Some(n) => n
|
||||||
|
None => {
|
||||||
|
let n = @network.NetService::new()
|
||||||
|
self.net = Some(n)
|
||||||
|
n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Use `b` for network status and actions (tests: a fake backend).
|
||||||
|
pub fn DesktopShell::set_network_backend(self : DesktopShell, b : &@network.NetBackend) -> Unit {
|
||||||
|
match self.net {
|
||||||
|
Some(n) => n.close()
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
self.net = Some(@network.NetService::with_backend(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
///| Refresh and publish network state while a module imports `network`; drop the service (and
|
||||||
|
/// its bus connection) when none does any more.
|
||||||
|
fn DesktopShell::publish_network(self : DesktopShell) -> Unit {
|
||||||
|
if !self.widgets.iter().any(w => w.has_cap("network")) {
|
||||||
|
match self.net {
|
||||||
|
Some(n) if n.probe() => {
|
||||||
|
n.close()
|
||||||
|
self.net = None
|
||||||
|
}
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let net = self.network()
|
||||||
|
net.tick(@sys.monotonic_ms())
|
||||||
|
let s = net.status()
|
||||||
|
let st = @wasm.Table::new()
|
||||||
|
st.int(s.state.code())
|
||||||
|
st.int(s.signal)
|
||||||
|
st.str(s.name)
|
||||||
|
st.str(s.message)
|
||||||
|
st.int(if s.wifi_enabled { 1 } else { 0 })
|
||||||
|
st.int(if s.airplane { 1 } else { 0 })
|
||||||
|
st.int(if s.managed { 1 } else { 0 })
|
||||||
|
st.int(if s.has_wifi { 1 } else { 0 })
|
||||||
|
st.end_row()
|
||||||
|
@wasm.publish(NetStatus, st)
|
||||||
|
let nt = @wasm.Table::new()
|
||||||
|
for w in net.networks() {
|
||||||
|
nt.str(w.ssid)
|
||||||
|
nt.int(w.signal)
|
||||||
|
nt.int(if w.secured { 1 } else { 0 })
|
||||||
|
nt.int(if w.active { 1 } else { 0 })
|
||||||
|
nt.int(if w.saved { 1 } else { 0 })
|
||||||
|
nt.end_row()
|
||||||
|
}
|
||||||
|
@wasm.publish(NetNetworks, nt)
|
||||||
|
}
|
||||||
|
|
||||||
|
///| A network module's request.
|
||||||
|
fn DesktopShell::network_request(self : DesktopShell, code : Int, ssid : String, password : String) -> Unit {
|
||||||
|
match @network.NetAction::from_code(code, ssid, password) {
|
||||||
|
Some(a) => self.network().act(a)
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -235,6 +235,8 @@ pub(all) struct DesktopShell {
|
|||||||
/// What the screenshot module is told (the compositor sets it every frame): bit 0 a
|
/// What the screenshot module is told (the compositor sets it every frame): bit 0 a
|
||||||
/// recording is running, bit 1 recordings show the pointer.
|
/// recording is running, bit 1 recordings show the pointer.
|
||||||
mut screenshot_state : Int
|
mut screenshot_state : Int
|
||||||
|
/// The network service (network.mbt), while a module imports `network`.
|
||||||
|
mut net : @network.NetService?
|
||||||
mut remember_windows : Bool
|
mut remember_windows : Bool
|
||||||
/// Dark mode (the configured theme) or light (Moon Day); saved as `:theme :light` when off.
|
/// Dark mode (the configured theme) or light (Moon Day); saved as `:theme :light` when off.
|
||||||
mut dark_mode : Bool
|
mut dark_mode : Bool
|
||||||
@@ -342,6 +344,7 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
|
|||||||
bg_key: None,
|
bg_key: None,
|
||||||
restore_session: true,
|
restore_session: true,
|
||||||
screenshot_state: 2,
|
screenshot_state: 2,
|
||||||
|
net: None,
|
||||||
remember_windows: true,
|
remember_windows: true,
|
||||||
dark_mode: true,
|
dark_mode: true,
|
||||||
screen_off_min: default_screen_off_min,
|
screen_off_min: default_screen_off_min,
|
||||||
|
|||||||
@@ -13,8 +13,8 @@
|
|||||||
|
|
||||||
///| Modules loaded into a fresh panel, in order. `tasks` stretches, so what follows it packs right.
|
///| Modules loaded into a fresh panel, in order. `tasks` stretches, so what follows it packs right.
|
||||||
let default_panel : Array[String] = [
|
let default_panel : Array[String] = [
|
||||||
"launcher", "inspector", "layout", "tasks", "moon-disc", "clock-digital12", "screenshot", "session-settings",
|
"launcher", "inspector", "layout", "tasks", "moon-disc", "network", "clock-digital12", "screenshot",
|
||||||
"logout",
|
"session-settings", "logout",
|
||||||
]
|
]
|
||||||
|
|
||||||
///| A fresh panel's modules: the defaults, plus the battery before the clock on a machine that
|
///| A fresh panel's modules: the defaults, plus the battery before the clock on a machine that
|
||||||
@@ -463,6 +463,7 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
|
|||||||
let b = self.battery.refresh()
|
let b = self.battery.refresh()
|
||||||
@wasm.publish_battery(b.percent, b.state, b.secs_left)
|
@wasm.publish_battery(b.percent, b.state, b.secs_left)
|
||||||
}
|
}
|
||||||
|
self.publish_network()
|
||||||
let it = @wasm.Table::new()
|
let it = @wasm.Table::new()
|
||||||
for w in self.widgets {
|
for w in self.widgets {
|
||||||
it.str(w.slot)
|
it.str(w.slot)
|
||||||
@@ -577,6 +578,7 @@ fn DesktopShell::process_requests(self : DesktopShell) -> Unit {
|
|||||||
Some(SetScreenOff(m)) => self.set_power_timeouts(m, self.suspend_min)
|
Some(SetScreenOff(m)) => self.set_power_timeouts(m, self.suspend_min)
|
||||||
Some(SetSuspendAfter(m)) => self.set_power_timeouts(self.screen_off_min, m)
|
Some(SetSuspendAfter(m)) => self.set_power_timeouts(self.screen_off_min, m)
|
||||||
Some(PowerAction(a)) => if a >= 0 && a <= 2 { self.actions.push(SystemPower(a)) }
|
Some(PowerAction(a)) => if a >= 0 && a <= 2 { self.actions.push(SystemPower(a)) }
|
||||||
|
Some(Network(code, ssid, password)) => self.network_request(code, ssid, password)
|
||||||
Some(SetInspector(on)) => self.set_inspecting(on)
|
Some(SetInspector(on)) => self.set_inspecting(on)
|
||||||
Some(LoadModule(path)) => {
|
Some(LoadModule(path)) => {
|
||||||
match self.load_path(path) {
|
match self.load_path(path) {
|
||||||
|
|||||||
@@ -259,6 +259,10 @@ pub(all) enum HostTable {
|
|||||||
SessionSettings
|
SessionSettings
|
||||||
/// App id -> image handle (`raster.load-image`), served by `icons.app-icon`.
|
/// App id -> image handle (`raster.load-image`), served by `icons.app-icon`.
|
||||||
Icons
|
Icons
|
||||||
|
/// One row (iissiiii): the network status `network.status` returns.
|
||||||
|
NetStatus
|
||||||
|
/// Wi-Fi networks in range (siiii: ssid signal secured active saved).
|
||||||
|
NetNetworks
|
||||||
}
|
}
|
||||||
|
|
||||||
///|
|
///|
|
||||||
@@ -281,6 +285,8 @@ pub fn publish(which : HostTable, t : Table) -> Unit {
|
|||||||
Wallpapers => 5U
|
Wallpapers => 5U
|
||||||
SessionSettings => 6U
|
SessionSettings => 6U
|
||||||
Icons => 7U
|
Icons => 7U
|
||||||
|
NetStatus => 8U
|
||||||
|
NetNetworks => 9U
|
||||||
}
|
}
|
||||||
// Most tables are republished every frame unchanged: skip the copy into the host then.
|
// Most tables are republished every frame unchanged: skip the copy into the host then.
|
||||||
let slot = id.reinterpret_as_int()
|
let slot = id.reinterpret_as_int()
|
||||||
@@ -348,6 +354,9 @@ pub(all) enum HostRequest {
|
|||||||
SetScreenOff(Int)
|
SetScreenOff(Int)
|
||||||
SetSuspendAfter(Int)
|
SetSuspendAfter(Int)
|
||||||
PowerAction(Int)
|
PowerAction(Int)
|
||||||
|
/// A network module's action (0 scan, 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode
|
||||||
|
/// off/on, 6 connect, 7 forget), with the network name and password where it needs them.
|
||||||
|
Network(Int, String, String)
|
||||||
} derive(Eq, Debug)
|
} derive(Eq, Debug)
|
||||||
|
|
||||||
///|
|
///|
|
||||||
@@ -368,6 +377,7 @@ pub fn next_request() -> HostRequest? {
|
|||||||
Some(SetScreenOff(m)) => Some(SetScreenOff(m))
|
Some(SetScreenOff(m)) => Some(SetScreenOff(m))
|
||||||
Some(SetSuspendAfter(m)) => Some(SetSuspendAfter(m))
|
Some(SetSuspendAfter(m)) => Some(SetSuspendAfter(m))
|
||||||
Some(PowerAction(a)) => Some(PowerAction(a))
|
Some(PowerAction(a)) => Some(PowerAction(a))
|
||||||
|
Some(Network(r)) => Some(Network(r.action, r.ssid, r.password))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -243,6 +243,7 @@ pub fn load(path : String, tokens : @theme.Tokens) -> Result[Plasmoid, String] {
|
|||||||
-1 => "not a wasm file"
|
-1 => "not a wasm file"
|
||||||
-2 => "cannot read file"
|
-2 => "cannot read file"
|
||||||
-3 | -4 => "no plasmoid (chandra:desktop/plasmoid) in this module"
|
-3 | -4 => "no plasmoid (chandra:desktop/plasmoid) in this module"
|
||||||
|
-11 => "too many modules loaded"
|
||||||
_ => "wasm runtime error"
|
_ => "wasm runtime error"
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -690,6 +691,10 @@ pub(all) enum HostTable {
|
|||||||
SessionSettings
|
SessionSettings
|
||||||
/// App id -> image handle (`raster.load-image`), served by `icons.app-icon`.
|
/// App id -> image handle (`raster.load-image`), served by `icons.app-icon`.
|
||||||
Icons
|
Icons
|
||||||
|
/// One row (iissiiii): the network status `network.status` returns.
|
||||||
|
NetStatus
|
||||||
|
/// Wi-Fi networks in range (siiii: ssid signal secured active saved).
|
||||||
|
NetNetworks
|
||||||
}
|
}
|
||||||
|
|
||||||
///| Publish `t` as the data behind `which` for every module's next call.
|
///| Publish `t` as the data behind `which` for every module's next call.
|
||||||
@@ -703,6 +708,8 @@ pub fn publish(which : HostTable, t : Table) -> Unit {
|
|||||||
Wallpapers => 5
|
Wallpapers => 5
|
||||||
SessionSettings => 6
|
SessionSettings => 6
|
||||||
Icons => 7
|
Icons => 7
|
||||||
|
NetStatus => 8
|
||||||
|
NetNetworks => 9
|
||||||
}
|
}
|
||||||
let out : Array[Byte] = []
|
let out : Array[Byte] = []
|
||||||
for k = 0; k < 4; k = k + 1 {
|
for k = 0; k < 4; k = k + 1 {
|
||||||
@@ -769,6 +776,9 @@ pub(all) enum HostRequest {
|
|||||||
SetScreenOff(Int)
|
SetScreenOff(Int)
|
||||||
SetSuspendAfter(Int)
|
SetSuspendAfter(Int)
|
||||||
PowerAction(Int)
|
PowerAction(Int)
|
||||||
|
/// A network module's action (0 scan, 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode
|
||||||
|
/// off/on, 6 connect, 7 forget), with the network name and password where it needs them.
|
||||||
|
Network(Int, String, String)
|
||||||
} derive(Eq, Debug)
|
} derive(Eq, Debug)
|
||||||
|
|
||||||
///|
|
///|
|
||||||
@@ -796,6 +806,14 @@ pub fn next_request() -> HostRequest? {
|
|||||||
13 => Some(SetScreenOff(c_host_req_int()))
|
13 => Some(SetScreenOff(c_host_req_int()))
|
||||||
14 => Some(SetSuspendAfter(c_host_req_int()))
|
14 => Some(SetSuspendAfter(c_host_req_int()))
|
||||||
15 => Some(PowerAction(c_host_req_int()))
|
15 => Some(PowerAction(c_host_req_int()))
|
||||||
|
16 => {
|
||||||
|
let code = c_host_req_int()
|
||||||
|
let s = req_str()
|
||||||
|
match s.find("\u{1f}") {
|
||||||
|
Some(i) => Some(Network(code, s[:i].to_string(), s[i + 1:].to_string()))
|
||||||
|
None => Some(Network(code, s, ""))
|
||||||
|
}
|
||||||
|
}
|
||||||
_ => None
|
_ => None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,13 +57,16 @@ enum {
|
|||||||
K_APP_ICON,
|
K_APP_ICON,
|
||||||
K_SHOT_TAKE, K_SHOT_RECORD, K_SHOT_STOP, K_SHOT_IS_REC, K_SHOT_PTR, K_SHOT_SET_PTR,
|
K_SHOT_TAKE, K_SHOT_RECORD, K_SHOT_STOP, K_SHOT_IS_REC, K_SHOT_PTR, K_SHOT_SET_PTR,
|
||||||
K_PW_SCREEN, K_PW_SET_SCREEN, K_PW_SUSP, K_PW_SET_SUSP, K_PW_SUSPEND, K_PW_OFF, K_PW_REBOOT,
|
K_PW_SCREEN, K_PW_SET_SCREEN, K_PW_SUSP, K_PW_SET_SUSP, K_PW_SUSPEND, K_PW_OFF, K_PW_REBOOT,
|
||||||
K_BAT_READ
|
K_BAT_READ,
|
||||||
|
K_NET_STATUS, K_NET_LIST, K_NET_SCAN, K_NET_CONNECT, K_NET_DISCONNECT, K_NET_FORGET, K_NET_SET_WIFI,
|
||||||
|
K_NET_SET_AIRPLANE
|
||||||
};
|
};
|
||||||
typedef struct Env { Inst *inst; int kind; } Env;
|
typedef struct Env { Inst *inst; int kind; } Env;
|
||||||
|
|
||||||
/* ---- host data the shell publishes before calling a guest ----
|
/* ---- host data the shell publishes before calling a guest ----
|
||||||
* A table is [u32 rows] then rows of fields, each field a LE i32 ('i') or a u32 byte length + UTF-8 ('s'). */
|
* A table is [u32 rows] then rows of fields, each field a LE i32 ('i') or a u32 byte length + UTF-8 ('s'). */
|
||||||
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS, T_N };
|
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS,
|
||||||
|
T_NET_STATUS, T_NET_NETWORKS, T_N };
|
||||||
typedef struct { uint8_t *data; size_t len; } Blob;
|
typedef struct { uint8_t *data; size_t len; } Blob;
|
||||||
static Blob tables[T_N];
|
static Blob tables[T_N];
|
||||||
static int32_t host_ints[12] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
|
static int32_t host_ints[12] = {[7] = -1}; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i),
|
||||||
@@ -186,12 +189,64 @@ static char *guest_str(Inst *in, int32_t ptr, int32_t units) {
|
|||||||
|
|
||||||
static uint32_t rd_u32(const uint8_t *p) { uint32_t v; memcpy(&v, p, 4); return v; }
|
static uint32_t rd_u32(const uint8_t *p) { uint32_t v; memcpy(&v, p, 4); return v; }
|
||||||
|
|
||||||
/* Lower table `t` (row layout `spec`: 'i' or 's' per field) as a list<record> and write (ptr,len) at `retptr`. */
|
/* Lower one row of table `t` (from byte `*pos`) as a record at guest address `off`: 'i' an i32,
|
||||||
|
* 's' a string, 'b' a bool (an i32 in the table, one byte in the record; bools go last). 0 when
|
||||||
|
* the table ends early. */
|
||||||
|
static int lower_row(Inst *in, Blob *b, size_t *pos, const char *spec, int32_t off) {
|
||||||
|
for (const char *c = spec; *c; c++) {
|
||||||
|
if (*pos + 4 > b->len) return 0;
|
||||||
|
uint32_t v = rd_u32(b->data + *pos);
|
||||||
|
*pos += 4;
|
||||||
|
if (*c == 'i') { w32(in, off, (int32_t)v); off += 4; }
|
||||||
|
else if (*c == 'b') { uint8_t one = v ? 1 : 0; mem_write(in, off, &one, 1); off += 1; }
|
||||||
|
else {
|
||||||
|
if (*pos + v > b->len) return 0;
|
||||||
|
put_str(in, off, b->data + *pos, v);
|
||||||
|
*pos += v;
|
||||||
|
off += 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A record's size for `spec` ('s' 8, 'i' 4, 'b' 1), rounded up to its 4-byte alignment. */
|
||||||
|
static size_t record_size(const char *spec) {
|
||||||
|
size_t esz = 0;
|
||||||
|
for (const char *c = spec; *c; c++) esz += *c == 's' ? 8 : *c == 'b' ? 1 : 4;
|
||||||
|
return (esz + 3) & ~(size_t)3;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Lower row 0 of table `t` as a record at `retptr` (zeros when the table is empty). */
|
||||||
|
static void build_record(Inst *in, int t, const char *spec, int32_t retptr) {
|
||||||
|
Blob *b = &tables[t];
|
||||||
|
size_t pos = 4;
|
||||||
|
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
|
||||||
|
if (n == 0 || !lower_row(in, b, &pos, spec, retptr)) {
|
||||||
|
/* strings still need real (empty) allocations: the guest frees what it lifts */
|
||||||
|
int32_t off = retptr;
|
||||||
|
for (const char *c = spec; *c; c++) {
|
||||||
|
if (*c == 's') { put_str(in, off, (const uint8_t *)"", 0); off += 8; }
|
||||||
|
else if (*c == 'b') { uint8_t z = 0; mem_write(in, off, &z, 1); off += 1; }
|
||||||
|
else { w32(in, off, 0); off += 4; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Lower table `t` (row layout `spec`, see lower_row) as a list<record> and write (ptr,len) at `retptr`. */
|
||||||
static void build_list(Inst *in, int t, const char *spec, int32_t retptr) {
|
static void build_list(Inst *in, int t, const char *spec, int32_t retptr) {
|
||||||
Blob *b = &tables[t];
|
Blob *b = &tables[t];
|
||||||
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
|
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
|
||||||
size_t esz = 0;
|
size_t esz = record_size(spec);
|
||||||
for (const char *c = spec; *c; c++) esz += *c == 's' ? 8 : 4;
|
if (strchr(spec, 'b')) {
|
||||||
|
int32_t base = guest_alloc(in, (int32_t)(esz * (n ? n : 1)), 4);
|
||||||
|
if (base < 0) { w32(in, retptr, 0); w32(in, retptr + 4, 0); return; }
|
||||||
|
size_t pos = 4;
|
||||||
|
uint32_t r = 0;
|
||||||
|
while (r < n && lower_row(in, b, &pos, spec, base + (int32_t)(r * esz))) r++;
|
||||||
|
w32(in, retptr, base);
|
||||||
|
w32(in, retptr + 4, (int32_t)r);
|
||||||
|
return;
|
||||||
|
}
|
||||||
int32_t base = guest_alloc(in, (int32_t)(esz * (n ? n : 1)), 4);
|
int32_t base = guest_alloc(in, (int32_t)(esz * (n ? n : 1)), 4);
|
||||||
if (base < 0) { w32(in, retptr, 0); w32(in, retptr + 4, 0); return; }
|
if (base < 0) { w32(in, retptr, 0); w32(in, retptr + 4, 0); return; }
|
||||||
size_t pos = 4;
|
size_t pos = 4;
|
||||||
@@ -334,6 +389,30 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_
|
|||||||
case K_PW_SUSPEND: push_req(15, 0, NULL); break; /* 15: power action n (0 suspend, 1 off, 2 restart) */
|
case K_PW_SUSPEND: push_req(15, 0, NULL); break; /* 15: power action n (0 suspend, 1 off, 2 restart) */
|
||||||
case K_PW_OFF: push_req(15, 1, NULL); break;
|
case K_PW_OFF: push_req(15, 1, NULL); break;
|
||||||
case K_PW_REBOOT: push_req(15, 2, NULL); break;
|
case K_PW_REBOOT: push_req(15, 2, NULL); break;
|
||||||
|
/* Network: status and the Wi-Fi list from tables 8/9; request 16 carries the action (n) and
|
||||||
|
* "ssid\x1fpassword" (see wit/host/plasmoids.wit network-request). */
|
||||||
|
case K_NET_STATUS: build_record(in, T_NET_STATUS, "iissbbbb", a0); break;
|
||||||
|
case K_NET_LIST: build_list(in, T_NET_NETWORKS, "sibbb", a0); break;
|
||||||
|
case K_NET_SCAN: push_req(16, 0, NULL); break;
|
||||||
|
case K_NET_DISCONNECT: push_req(16, 1, NULL); break;
|
||||||
|
case K_NET_SET_WIFI: push_req(16, a0 ? 3 : 2, NULL); break;
|
||||||
|
case K_NET_SET_AIRPLANE: push_req(16, a0 ? 5 : 4, NULL); break;
|
||||||
|
case K_NET_CONNECT:
|
||||||
|
case K_NET_FORGET: {
|
||||||
|
int32_t a3 = args->size >= 4 ? args->data[3].of.i32 : 0;
|
||||||
|
char *ssid = guest_str(in, a0, a1);
|
||||||
|
char *pw = e->kind == K_NET_CONNECT ? guest_str(in, a2, a3) : strdup("");
|
||||||
|
size_t ls = strlen(ssid), lp = strlen(pw);
|
||||||
|
char *both = (char *)malloc(ls + lp + 2);
|
||||||
|
memcpy(both, ssid, ls);
|
||||||
|
both[ls] = 0x1f;
|
||||||
|
memcpy(both + ls + 1, pw, lp + 1);
|
||||||
|
push_req(16, e->kind == K_NET_CONNECT ? 6 : 7, both);
|
||||||
|
memset(pw, 0, lp); /* don't leave the password lying around in freed memory */
|
||||||
|
memset(both, 0, ls + lp + 1);
|
||||||
|
free(ssid); free(pw); free(both);
|
||||||
|
break;
|
||||||
|
}
|
||||||
case K_SHOT_IS_REC:
|
case K_SHOT_IS_REC:
|
||||||
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[4] & 1);
|
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[4] & 1);
|
||||||
break;
|
break;
|
||||||
@@ -507,6 +586,14 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
|
|||||||
if (!strcmp(iface, "power") && !strcmp(fn, "suspend")) return K_PW_SUSPEND;
|
if (!strcmp(iface, "power") && !strcmp(fn, "suspend")) return K_PW_SUSPEND;
|
||||||
if (!strcmp(iface, "power") && !strcmp(fn, "power-off")) return K_PW_OFF;
|
if (!strcmp(iface, "power") && !strcmp(fn, "power-off")) return K_PW_OFF;
|
||||||
if (!strcmp(iface, "power") && !strcmp(fn, "reboot")) return K_PW_REBOOT;
|
if (!strcmp(iface, "power") && !strcmp(fn, "reboot")) return K_PW_REBOOT;
|
||||||
|
if (!strcmp(iface, "network") && !strcmp(fn, "status")) return K_NET_STATUS;
|
||||||
|
if (!strcmp(iface, "network") && !strcmp(fn, "wifi-networks")) return K_NET_LIST;
|
||||||
|
if (!strcmp(iface, "network") && !strcmp(fn, "scan")) return K_NET_SCAN;
|
||||||
|
if (!strcmp(iface, "network") && !strcmp(fn, "connect")) return K_NET_CONNECT;
|
||||||
|
if (!strcmp(iface, "network") && !strcmp(fn, "disconnect")) return K_NET_DISCONNECT;
|
||||||
|
if (!strcmp(iface, "network") && !strcmp(fn, "forget")) return K_NET_FORGET;
|
||||||
|
if (!strcmp(iface, "network") && !strcmp(fn, "set-wifi-enabled")) return K_NET_SET_WIFI;
|
||||||
|
if (!strcmp(iface, "network") && !strcmp(fn, "set-airplane-mode")) return K_NET_SET_AIRPLANE;
|
||||||
if (!strcmp(iface, "layout-control") && !strcmp(fn, "layout-modes")) return K_LAYOUTS;
|
if (!strcmp(iface, "layout-control") && !strcmp(fn, "layout-modes")) return K_LAYOUTS;
|
||||||
if (!strcmp(iface, "layout-control") && !strcmp(fn, "current-layout")) return K_LAYOUT_CUR;
|
if (!strcmp(iface, "layout-control") && !strcmp(fn, "current-layout")) return K_LAYOUT_CUR;
|
||||||
if (!strcmp(iface, "layout-control") && !strcmp(fn, "set-layout")) return K_SET_LAYOUT;
|
if (!strcmp(iface, "layout-control") && !strcmp(fn, "set-layout")) return K_SET_LAYOUT;
|
||||||
@@ -772,6 +859,7 @@ void mp_host_set_int(int32_t which, int32_t v) {
|
|||||||
/* Pop the next guest request: returns its kind (0 = none). Fetch its arguments with req_int / req_str. */
|
/* Pop the next guest request: returns its kind (0 = none). Fetch its arguments with req_int / req_str. */
|
||||||
MOONBIT_FFI_EXPORT
|
MOONBIT_FFI_EXPORT
|
||||||
int32_t mp_host_req_pop(void) {
|
int32_t mp_host_req_pop(void) {
|
||||||
|
if (cur_req.s) memset(cur_req.s, 0, strlen(cur_req.s)); /* may hold a Wi-Fi password */
|
||||||
free(cur_req.s);
|
free(cur_req.s);
|
||||||
memset(&cur_req, 0, sizeof(cur_req));
|
memset(&cur_req, 0, sizeof(cur_req));
|
||||||
if (req_head >= req_tail) return 0;
|
if (req_head >= req_tail) return 0;
|
||||||
|
|||||||
@@ -256,6 +256,9 @@ impl chandra::host::plasmoids::Host for State {
|
|||||||
Req::SetScreenOff(m) => R::SetScreenOff(m),
|
Req::SetScreenOff(m) => R::SetScreenOff(m),
|
||||||
Req::SetSuspendAfter(m) => R::SetSuspendAfter(m),
|
Req::SetSuspendAfter(m) => R::SetSuspendAfter(m),
|
||||||
Req::PowerAction(a) => R::PowerAction(a),
|
Req::PowerAction(a) => R::PowerAction(a),
|
||||||
|
Req::Network(action, ssid, password) => {
|
||||||
|
R::Network(chandra::host::plasmoids::NetworkRequest { action, ssid, password })
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+142
-1
@@ -52,6 +52,9 @@ pub enum Req {
|
|||||||
SetSuspendAfter(i32),
|
SetSuspendAfter(i32),
|
||||||
/// 0 suspend, 1 power off, 2 restart.
|
/// 0 suspend, 1 power off, 2 restart.
|
||||||
PowerAction(i32),
|
PowerAction(i32),
|
||||||
|
/// A network action (0 scan, 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode off/on,
|
||||||
|
/// 6 connect, 7 forget), the network's name and the password.
|
||||||
|
Network(i32, String, String),
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const T_APPS: usize = 0;
|
pub const T_APPS: usize = 0;
|
||||||
@@ -63,11 +66,15 @@ pub const T_WALLPAPERS: usize = 5;
|
|||||||
pub const T_SESSION_SETTINGS: usize = 6;
|
pub const T_SESSION_SETTINGS: usize = 6;
|
||||||
/// App id -> raster image handle (`raster.load-image`), behind `icons.app-icon`.
|
/// App id -> raster image handle (`raster.load-image`), behind `icons.app-icon`.
|
||||||
pub const T_ICONS: usize = 7;
|
pub const T_ICONS: usize = 7;
|
||||||
|
/// One row (iissiiii): state signal name message wifi-enabled airplane can-manage has-wifi.
|
||||||
|
pub const T_NET_STATUS: usize = 8;
|
||||||
|
/// Wi-Fi networks in range (siiii): ssid signal secured active saved.
|
||||||
|
pub const T_NET_NETWORKS: usize = 9;
|
||||||
|
|
||||||
/// Host data every module reads from, shared by all loaded modules.
|
/// Host data every module reads from, shared by all loaded modules.
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct Shared {
|
pub struct Shared {
|
||||||
pub tables: [Vec<u8>; 8],
|
pub tables: [Vec<u8>; 10],
|
||||||
pub layout_mode: i32,
|
pub layout_mode: i32,
|
||||||
pub wallpaper: i32,
|
pub wallpaper: i32,
|
||||||
/// Which session settings are on: bit i for row i of the session settings table.
|
/// Which session settings are on: bit i for row i of the session settings table.
|
||||||
@@ -365,6 +372,71 @@ impl d::screenshot::Host for PState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl d::network::Host for PState {
|
||||||
|
fn status(&mut self) -> d::network::NetStatus {
|
||||||
|
let rows = self.rows(T_NET_STATUS, "iissiiii");
|
||||||
|
match rows.first() {
|
||||||
|
Some(r) if r.len() == 8 => d::network::NetStatus {
|
||||||
|
state: i(&r[0]) as u32,
|
||||||
|
signal: i(&r[1]) as u32,
|
||||||
|
name: s(&r[2]),
|
||||||
|
message: s(&r[3]),
|
||||||
|
wifi_enabled: i(&r[4]) != 0,
|
||||||
|
airplane: i(&r[5]) != 0,
|
||||||
|
can_manage: i(&r[6]) != 0,
|
||||||
|
has_wifi: i(&r[7]) != 0,
|
||||||
|
},
|
||||||
|
_ => d::network::NetStatus {
|
||||||
|
state: 0,
|
||||||
|
signal: 0,
|
||||||
|
name: String::new(),
|
||||||
|
message: String::new(),
|
||||||
|
wifi_enabled: false,
|
||||||
|
airplane: false,
|
||||||
|
can_manage: false,
|
||||||
|
has_wifi: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn wifi_networks(&mut self) -> Vec<d::network::WifiNetwork> {
|
||||||
|
self.rows(T_NET_NETWORKS, "siiii")
|
||||||
|
.iter()
|
||||||
|
.filter(|r| r.len() == 5)
|
||||||
|
.map(|r| d::network::WifiNetwork {
|
||||||
|
ssid: s(&r[0]),
|
||||||
|
signal: i(&r[1]) as u32,
|
||||||
|
secured: i(&r[2]) != 0,
|
||||||
|
active: i(&r[3]) != 0,
|
||||||
|
saved: i(&r[4]) != 0,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
fn scan(&mut self) {
|
||||||
|
self.net(0, String::new(), String::new());
|
||||||
|
}
|
||||||
|
fn connect(&mut self, ssid: String, password: String) {
|
||||||
|
self.net(6, ssid, password);
|
||||||
|
}
|
||||||
|
fn disconnect(&mut self) {
|
||||||
|
self.net(1, String::new(), String::new());
|
||||||
|
}
|
||||||
|
fn forget(&mut self, ssid: String) {
|
||||||
|
self.net(7, ssid, String::new());
|
||||||
|
}
|
||||||
|
fn set_wifi_enabled(&mut self, on: bool) {
|
||||||
|
self.net(if on { 3 } else { 2 }, String::new(), String::new());
|
||||||
|
}
|
||||||
|
fn set_airplane_mode(&mut self, on: bool) {
|
||||||
|
self.net(if on { 5 } else { 4 }, String::new(), String::new());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PState {
|
||||||
|
fn net(&mut self, action: i32, ssid: String, password: String) {
|
||||||
|
self.shared.borrow_mut().requests.push_back(Req::Network(action, ssid, password));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl d::session_settings::Host for PState {
|
impl d::session_settings::Host for PState {
|
||||||
fn settings(&mut self) -> Vec<String> {
|
fn settings(&mut self) -> Vec<String> {
|
||||||
self.rows(T_SESSION_SETTINGS, "s").iter().map(|r| s(&r[0])).collect()
|
self.rows(T_SESSION_SETTINGS, "s").iter().map(|r| s(&r[0])).collect()
|
||||||
@@ -901,4 +973,73 @@ mod tests {
|
|||||||
assert!(rt.popup(h).is_none());
|
assert!(rt.popup(h).is_none());
|
||||||
rt.unload(h);
|
rt.unload(h);
|
||||||
}
|
}
|
||||||
|
/// Table bytes from rows of fields ('i' a number, 's' a string).
|
||||||
|
enum F<'a> {
|
||||||
|
I(i32),
|
||||||
|
S(&'a str),
|
||||||
|
}
|
||||||
|
fn rows_table(rows: &[Vec<F>]) -> Vec<u8> {
|
||||||
|
let mut t = (rows.len() as u32).to_le_bytes().to_vec();
|
||||||
|
for r in rows {
|
||||||
|
for f in r {
|
||||||
|
match f {
|
||||||
|
F::I(v) => t.extend(v.to_le_bytes()),
|
||||||
|
F::S(s) => {
|
||||||
|
t.extend((s.len() as u32).to_le_bytes());
|
||||||
|
t.extend(s.as_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn network_module_shows_the_connection_and_connects_with_a_password() {
|
||||||
|
let mut rt = runtime();
|
||||||
|
let l = rt.load(&module("network")).expect("network loads");
|
||||||
|
assert!(l.imports.contains(&"network".to_string()));
|
||||||
|
let h = l.handle;
|
||||||
|
{
|
||||||
|
let mut sh = rt.shared.borrow_mut();
|
||||||
|
// Wi-Fi "Home" at 72%, NetworkManager there, Wi-Fi on.
|
||||||
|
sh.tables[T_NET_STATUS] = rows_table(&[vec![
|
||||||
|
F::I(2),
|
||||||
|
F::I(72),
|
||||||
|
F::S("Home"),
|
||||||
|
F::S(""),
|
||||||
|
F::I(1),
|
||||||
|
F::I(0),
|
||||||
|
F::I(1),
|
||||||
|
F::I(1),
|
||||||
|
]]);
|
||||||
|
sh.tables[T_NET_NETWORKS] = rows_table(&[
|
||||||
|
vec![F::S("Home"), F::I(72), F::I(1), F::I(1), F::I(1)],
|
||||||
|
vec![F::S("Office"), F::I(55), F::I(1), F::I(0), F::I(0)],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
assert!(texts(&rt.render(h, Size { w: 130, h: 34 })).contains(&"Home".to_string()));
|
||||||
|
// Opening the popup asks for a scan.
|
||||||
|
assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 })));
|
||||||
|
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Network(0, _, _))));
|
||||||
|
let p = rt.popup(h).expect("popup open");
|
||||||
|
for n in ["Connected to Home (72%)", "Wi-Fi", "Airplane mode", "Office", "Secured"] {
|
||||||
|
assert!(texts(&p.ops).contains(&n.to_string()), "{n} listed");
|
||||||
|
}
|
||||||
|
// Row 5 (Office) opens the password field; typing and Enter connects.
|
||||||
|
let row = |i: i32| Point { x: 60, y: 6 + i * 30 + 14 };
|
||||||
|
assert!(rt.on_event(h, true, InputEvent::PointerDown(row(5))));
|
||||||
|
assert!(texts(&rt.popup(h).unwrap().ops).contains(&"Password|".to_string()));
|
||||||
|
for k in ["p", "w", "Enter"] {
|
||||||
|
rt.on_event(h, true, InputEvent::KeyDown(k.to_string()));
|
||||||
|
}
|
||||||
|
match rt.shared.borrow_mut().requests.pop_front() {
|
||||||
|
Some(Req::Network(6, ssid, pw)) => assert_eq!((ssid.as_str(), pw.as_str()), ("Office", "pw")),
|
||||||
|
_ => panic!("connect asked for"),
|
||||||
|
}
|
||||||
|
// The Wi-Fi switch (row 1).
|
||||||
|
assert!(rt.on_event(h, true, InputEvent::PointerDown(row(1))));
|
||||||
|
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Network(2, _, _))));
|
||||||
|
rt.unload(h);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
Network status and control (NetworkManager), for the network panel module. The shell talks to
|
||||||
|
NetworkManager over D-Bus; without it, status comes read-only from /sys/class/net and
|
||||||
|
/proc/net, `can-manage` is false and the actions do nothing.
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn wasmImportStatus(p0 : Int) = "chandra:desktop/network@0.1.0" "status"
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn wasmImportWifiNetworks(p0 : Int) = "chandra:desktop/network@0.1.0" "wifi-networks"
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn wasmImportScan() = "chandra:desktop/network@0.1.0" "scan"
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn wasmImportConnect(p0 : Int, p1 : Int, p2 : Int, p3 : Int) = "chandra:desktop/network@0.1.0" "connect"
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn wasmImportDisconnect() = "chandra:desktop/network@0.1.0" "disconnect"
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn wasmImportForget(p0 : Int, p1 : Int) = "chandra:desktop/network@0.1.0" "forget"
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn wasmImportSetWifiEnabled(p0 : Int) = "chandra:desktop/network@0.1.0" "set-wifi-enabled"
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn wasmImportSetAirplaneMode(p0 : Int) = "chandra:desktop/network@0.1.0" "set-airplane-mode"
|
||||||
|
|
||||||
|
///|
|
||||||
|
#owned(str)
|
||||||
|
extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
|
||||||
|
#|(func (param i32) (result i32) local.get 0)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_free(position : Int) =
|
||||||
|
#|(func (param i32) local.get 0 call $moonbit.decref)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
||||||
|
#|(func (param i32) (result i32) (local i32)
|
||||||
|
#| local.get 0 i32.const 4 i32.add call $moonbit.gc.malloc
|
||||||
|
#| local.tee 1 i32.const 0 call $moonbit.init_array8
|
||||||
|
#| local.get 1)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
|
||||||
|
#|(func (param i32) (result i32) local.get 0 i32.load)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
|
||||||
|
#|(func (param i32) (param i32) (result i32)
|
||||||
|
#| local.get 0
|
||||||
|
#| local.get 1 call $moonbit.init_array16
|
||||||
|
#| local.get 0)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
|
||||||
|
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
|
||||||
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
warnings = "-44"
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||||
|
///|
|
||||||
|
pub(all) struct NetStatus {
|
||||||
|
state : UInt; signal : UInt; name : String; message : String; wifi_enabled : Bool; airplane : Bool; can_manage : Bool; has_wifi : Bool
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
pub(all) struct WifiNetwork {
|
||||||
|
ssid : String; signal : UInt; secured : Bool; active : Bool; saved : Bool
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
pub fn status() -> NetStatus {
|
||||||
|
|
||||||
|
let return_area = mbt_ffi_malloc(28)
|
||||||
|
wasmImportStatus(return_area);
|
||||||
|
|
||||||
|
let result = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 8), mbt_ffi_load32((return_area) + 12))
|
||||||
|
|
||||||
|
let result0 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 16), mbt_ffi_load32((return_area) + 20))
|
||||||
|
let ret = NetStatus::{state : (mbt_ffi_load32((return_area) + 0)).reinterpret_as_uint(), signal : (mbt_ffi_load32((return_area) + 4)).reinterpret_as_uint(), name : result, message : result0, wifi_enabled : (mbt_ffi_load8_u((return_area) + 24) != 0), airplane : (mbt_ffi_load8_u((return_area) + 25) != 0), can_manage : (mbt_ffi_load8_u((return_area) + 26) != 0), has_wifi : (mbt_ffi_load8_u((return_area) + 27) != 0)}
|
||||||
|
mbt_ffi_free(return_area)
|
||||||
|
return ret
|
||||||
|
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
/// Wi-Fi networks in range, the one in use first, then by signal (empty with Wi-Fi off).
|
||||||
|
pub fn wifi_networks() -> Array[WifiNetwork] {
|
||||||
|
|
||||||
|
let return_area = mbt_ffi_malloc(8)
|
||||||
|
wasmImportWifiNetworks(return_area);
|
||||||
|
|
||||||
|
let array : Array[WifiNetwork] = [];
|
||||||
|
for index = 0; index < (mbt_ffi_load32((return_area) + 4)); index = index + 1 {
|
||||||
|
let iter_base = (mbt_ffi_load32((return_area) + 0)) + (index * 16)
|
||||||
|
|
||||||
|
let result = mbt_ffi_ptr2str(mbt_ffi_load32((iter_base) + 0), mbt_ffi_load32((iter_base) + 4))
|
||||||
|
|
||||||
|
array.push(WifiNetwork::{ssid : result, signal : (mbt_ffi_load32((iter_base) + 8)).reinterpret_as_uint(), secured : (mbt_ffi_load8_u((iter_base) + 12) != 0), active : (mbt_ffi_load8_u((iter_base) + 13) != 0), saved : (mbt_ffi_load8_u((iter_base) + 14) != 0)})
|
||||||
|
}
|
||||||
|
mbt_ffi_free(mbt_ffi_load32((return_area) + 0))
|
||||||
|
let ret = array
|
||||||
|
mbt_ffi_free(return_area)
|
||||||
|
return ret
|
||||||
|
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
/// Ask the Wi-Fi device to look for networks (the list fills in over a few seconds).
|
||||||
|
pub fn scan() -> Unit {
|
||||||
|
|
||||||
|
wasmImportScan();
|
||||||
|
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
/// Connect to `ssid`: a saved network as saved, a new one with `password` ("" when open).
|
||||||
|
/// WPA/WPA2/WPA3 personal and open networks; the outcome shows in `status.message`.
|
||||||
|
pub fn connect(ssid : String, password : String) -> Unit {
|
||||||
|
|
||||||
|
let ptr = mbt_ffi_str2ptr(ssid)
|
||||||
|
|
||||||
|
let ptr0 = mbt_ffi_str2ptr(password)
|
||||||
|
wasmImportConnect(ptr, ssid.length(), ptr0, password.length());
|
||||||
|
mbt_ffi_free(ptr)
|
||||||
|
mbt_ffi_free(ptr0)
|
||||||
|
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
/// Disconnect the Wi-Fi device.
|
||||||
|
pub fn disconnect() -> Unit {
|
||||||
|
|
||||||
|
wasmImportDisconnect();
|
||||||
|
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
/// Delete the saved connection(s) for `ssid`.
|
||||||
|
pub fn forget(ssid : String) -> Unit {
|
||||||
|
|
||||||
|
let ptr = mbt_ffi_str2ptr(ssid)
|
||||||
|
wasmImportForget(ptr, ssid.length());
|
||||||
|
mbt_ffi_free(ptr)
|
||||||
|
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
pub fn set_wifi_enabled(on : Bool) -> Unit {
|
||||||
|
|
||||||
|
wasmImportSetWifiEnabled((if on { 1 } else { 0 }));
|
||||||
|
|
||||||
|
}
|
||||||
|
///|
|
||||||
|
pub fn set_airplane_mode(on : Bool) -> Unit {
|
||||||
|
|
||||||
|
wasmImportSetAirplaneMode((if on { 1 } else { 0 }));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@@ -67,8 +67,12 @@ fn wasmImportPickerStart() -> Int = "chandra:host/plasmoids@0.1.0" "picker-start
|
|||||||
fn wasmImportPickerPoll(p0 : Int) = "chandra:host/plasmoids@0.1.0" "picker-poll"
|
fn wasmImportPickerPoll(p0 : Int) = "chandra:host/plasmoids@0.1.0" "picker-poll"
|
||||||
|
|
||||||
///|
|
///|
|
||||||
extern "wasm" fn mbt_ffi_store64(offset : Int, value : Int64) =
|
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
|
||||||
#|(func (param i32) (param i64) local.get 0 local.get 1 i64.store)
|
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
|
||||||
|
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
|
||||||
|
|
||||||
///|
|
///|
|
||||||
#owned(str)
|
#owned(str)
|
||||||
@@ -76,12 +80,8 @@ extern "wasm" fn mbt_ffi_str2ptr(str : String) -> Int =
|
|||||||
#|(func (param i32) (result i32) local.get 0)
|
#|(func (param i32) (result i32) local.get 0)
|
||||||
|
|
||||||
///|
|
///|
|
||||||
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
|
extern "wasm" fn mbt_ffi_store64(offset : Int, value : Int64) =
|
||||||
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
|
#|(func (param i32) (param i64) local.get 0 local.get 1 i64.store)
|
||||||
|
|
||||||
///|
|
|
||||||
extern "wasm" fn mbt_ffi_store32(offset : Int, value : Int) =
|
|
||||||
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store)
|
|
||||||
|
|
||||||
///|
|
///|
|
||||||
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
|
extern "wasm" fn mbt_ffi_ptr2str(ptr : Int, len : Int) -> String =
|
||||||
@@ -96,12 +96,8 @@ extern "wasm" fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int =
|
|||||||
#|(func (param i32) (result i32) local.get 0)
|
#|(func (param i32) (result i32) local.get 0)
|
||||||
|
|
||||||
///|
|
///|
|
||||||
extern "wasm" fn mbt_ffi_load8_u(offset : Int) -> Int =
|
extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 =
|
||||||
#|(func (param i32) (result i32) local.get 0 i32.load8_u)
|
#|(func (param i32) (result i64) local.get 0 i64.load)
|
||||||
|
|
||||||
///|
|
|
||||||
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
|
|
||||||
#|(func (param i32) (result i32) local.get 0 i32.load)
|
|
||||||
|
|
||||||
///|
|
///|
|
||||||
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
||||||
@@ -110,11 +106,15 @@ extern "wasm" fn mbt_ffi_malloc(size : Int) -> Int =
|
|||||||
#| local.tee 1 i32.const 0 call $moonbit.init_array8
|
#| local.tee 1 i32.const 0 call $moonbit.init_array8
|
||||||
#| local.get 1)
|
#| local.get 1)
|
||||||
|
|
||||||
///|
|
|
||||||
extern "wasm" fn mbt_ffi_load64(offset : Int) -> Int64 =
|
|
||||||
#|(func (param i32) (result i64) local.get 0 i64.load)
|
|
||||||
|
|
||||||
///|
|
///|
|
||||||
extern "wasm" fn mbt_ffi_free(position : Int) =
|
extern "wasm" fn mbt_ffi_free(position : Int) =
|
||||||
#|(func (param i32) local.get 0 call $moonbit.decref)
|
#|(func (param i32) local.get 0 call $moonbit.decref)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_store8(offset : Int, value : Int) =
|
||||||
|
#|(func (param i32) (param i32) local.get 0 local.get 1 i32.store8)
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "wasm" fn mbt_ffi_load32(offset : Int) -> Int =
|
||||||
|
#|(func (param i32) (result i32) local.get 0 i32.load)
|
||||||
|
|
||||||
@@ -71,6 +71,12 @@ pub(all) struct Loaded {
|
|||||||
imports : Array[String]
|
imports : Array[String]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(all) struct NetworkRequest {
|
||||||
|
action : Int32
|
||||||
|
ssid : String
|
||||||
|
password : String
|
||||||
|
}
|
||||||
|
|
||||||
pub(all) enum PickerState {
|
pub(all) enum PickerState {
|
||||||
Open
|
Open
|
||||||
Cancelled
|
Cancelled
|
||||||
@@ -97,6 +103,7 @@ pub(all) enum Request {
|
|||||||
SetScreenOff(Int32)
|
SetScreenOff(Int32)
|
||||||
SetSuspendAfter(Int32)
|
SetSuspendAfter(Int32)
|
||||||
PowerAction(Int32)
|
PowerAction(Int32)
|
||||||
|
Network(NetworkRequest)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(all) struct SettingChange {
|
pub(all) struct SettingChange {
|
||||||
|
|||||||
@@ -24,6 +24,12 @@ pub(all) struct WindowEntry {
|
|||||||
id : UInt64; title : String; app_id : String; focused : Bool
|
id : UInt64; title : String; app_id : String; focused : Bool
|
||||||
}
|
}
|
||||||
///|
|
///|
|
||||||
|
/// A network module's action: 0 scan, 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode
|
||||||
|
/// off/on, 6 connect (ssid, password), 7 forget (ssid).
|
||||||
|
pub(all) struct NetworkRequest {
|
||||||
|
action : Int; ssid : String; password : String
|
||||||
|
}
|
||||||
|
///|
|
||||||
/// A module turning a session setting on or off.
|
/// A module turning a session setting on or off.
|
||||||
pub(all) struct SettingChange {
|
pub(all) struct SettingChange {
|
||||||
index : Int; on : Bool
|
index : Int; on : Bool
|
||||||
@@ -45,6 +51,7 @@ pub(all) enum Request {
|
|||||||
SetScreenOff(Int)
|
SetScreenOff(Int)
|
||||||
SetSuspendAfter(Int)
|
SetSuspendAfter(Int)
|
||||||
PowerAction(Int)
|
PowerAction(Int)
|
||||||
|
Network(NetworkRequest)
|
||||||
}
|
}
|
||||||
///|
|
///|
|
||||||
/// A native file-chooser dialog (zenity on the host session) for "Add widget".
|
/// A native file-chooser dialog (zenity on the host session) for "Add widget".
|
||||||
@@ -375,7 +382,9 @@ pub fn set_config(handle : UInt, key : String, value : String) -> Bool {
|
|||||||
/// i32 ('i') or a LE u32 byte length + UTF-8 ('s'). `which`: 0 apps (sssss: id name comment
|
/// i32 ('i') or a LE u32 byte length + UTF-8 ('s'). `which`: 0 apps (sssss: id name comment
|
||||||
/// category glyph), 1 windows (isii: id title focused minimized), 2 layouts (s), 3 modules
|
/// category glyph), 1 windows (isii: id title focused minimized), 2 layouts (s), 3 modules
|
||||||
/// (sssi: id name path loaded), 4 instances (sss: slot module name), 5 wallpapers (s), 6 session
|
/// (sssi: id name path loaded), 4 instances (sss: slot module name), 5 wallpapers (s), 6 session
|
||||||
/// settings (s), 7 icons (si: app id, raster image handle from `raster.load-image`) served by `icons.app-icon`.
|
/// settings (s), 7 icons (si: app id, raster image handle from `raster.load-image`) served by `icons.app-icon`,
|
||||||
|
/// 8 network status (one row, iissiiii: state signal name message wifi-enabled airplane
|
||||||
|
/// can-manage has-wifi), 9 Wi-Fi networks (siiii: ssid signal secured active saved).
|
||||||
pub fn publish_table(which : UInt, rows : FixedArray[Byte]) -> Unit {
|
pub fn publish_table(which : UInt, rows : FixedArray[Byte]) -> Unit {
|
||||||
|
|
||||||
let ptr = mbt_ffi_bytes2ptr(rows)
|
let ptr = mbt_ffi_bytes2ptr(rows)
|
||||||
@@ -465,10 +474,10 @@ pub fn publish_windows(wins : Array[WindowEntry]) -> Unit {
|
|||||||
/// The next pending request, oldest first.
|
/// The next pending request, oldest first.
|
||||||
pub fn next_request() -> Request? {
|
pub fn next_request() -> Request? {
|
||||||
|
|
||||||
let return_area = mbt_ffi_malloc(16)
|
let return_area = mbt_ffi_malloc(28)
|
||||||
wasmImportNextRequest(return_area);
|
wasmImportNextRequest(return_area);
|
||||||
|
|
||||||
let lifted2 : Request? = match mbt_ffi_load8_u((return_area) + 0) {
|
let lifted4 : Request? = match mbt_ffi_load8_u((return_area) + 0) {
|
||||||
0 => Option::None
|
0 => Option::None
|
||||||
1 => {
|
1 => {
|
||||||
|
|
||||||
@@ -535,6 +544,14 @@ pub fn next_request() -> Request? {
|
|||||||
|
|
||||||
Request::PowerAction(mbt_ffi_load32((return_area) + 8))
|
Request::PowerAction(mbt_ffi_load32((return_area) + 8))
|
||||||
}
|
}
|
||||||
|
14 => {
|
||||||
|
|
||||||
|
let result2 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 12), mbt_ffi_load32((return_area) + 16))
|
||||||
|
|
||||||
|
let result3 = mbt_ffi_ptr2str(mbt_ffi_load32((return_area) + 20), mbt_ffi_load32((return_area) + 24))
|
||||||
|
|
||||||
|
Request::Network(NetworkRequest::{action : mbt_ffi_load32((return_area) + 8), ssid : result2, password : result3})
|
||||||
|
}
|
||||||
_ => panic()
|
_ => panic()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -542,7 +559,7 @@ pub fn next_request() -> Request? {
|
|||||||
}
|
}
|
||||||
_ => panic()
|
_ => panic()
|
||||||
}
|
}
|
||||||
let ret = lifted2
|
let ret = lifted4
|
||||||
mbt_ffi_free(return_area)
|
mbt_ffi_free(return_area)
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
|
|||||||
@@ -12,3 +12,4 @@ logout logout-widget
|
|||||||
session-settings session-settings-widget
|
session-settings session-settings-widget
|
||||||
screenshot screenshot-widget
|
screenshot screenshot-widget
|
||||||
battery battery-widget
|
battery battery-widget
|
||||||
|
network network-widget
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Run the network package's D-Bus test against a private bus with python-dbusmock's NetworkManager
|
||||||
|
# template (apt: dbus python3-dbusmock). It checks the client's auth, framing and every
|
||||||
|
# NetworkManager call the network module makes, without a real NetworkManager.
|
||||||
|
set -euo pipefail
|
||||||
|
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT"
|
||||||
|
PY="${PYTHON:-}"
|
||||||
|
if [ -z "$PY" ]; then
|
||||||
|
for p in python3 /usr/bin/python3 /usr/bin/python3.12; do
|
||||||
|
if "$p" -c 'import dbusmock' 2>/dev/null; then PY="$p"; break; fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
[ -n "$PY" ] || { echo "python3 with dbusmock not found (apt install python3-dbusmock)" >&2; exit 1; }
|
||||||
|
eval "$(dbus-launch --sh-syntax)"
|
||||||
|
trap 'kill "$DBUS_SESSION_BUS_PID" ${MOCK_PID:-} 2>/dev/null || true' EXIT
|
||||||
|
export DBUS_SYSTEM_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS"
|
||||||
|
"$PY" -m dbusmock --system --template networkmanager >/dev/null 2>&1 &
|
||||||
|
MOCK_PID=$!
|
||||||
|
for _ in $(seq 50); do
|
||||||
|
dbus-send --system --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.NameHasOwner \
|
||||||
|
string:org.freedesktop.NetworkManager 2>/dev/null | grep -q 'boolean true' && break
|
||||||
|
sleep 0.1
|
||||||
|
done
|
||||||
|
CHANDRA_NM_E2E=1 moon test --target native --warn-list -a -p compositor/network "$@"
|
||||||
@@ -252,6 +252,11 @@ fn request_val(r : @wasm.HostRequest) -> @wt.Val {
|
|||||||
SetScreenOff(n) => Variant("set-screen-off", Some(S32(n)))
|
SetScreenOff(n) => Variant("set-screen-off", Some(S32(n)))
|
||||||
SetSuspendAfter(n) => Variant("set-suspend-after", Some(S32(n)))
|
SetSuspendAfter(n) => Variant("set-suspend-after", Some(S32(n)))
|
||||||
PowerAction(n) => Variant("power-action", Some(S32(n)))
|
PowerAction(n) => Variant("power-action", Some(S32(n)))
|
||||||
|
Network(action, ssid, password) =>
|
||||||
|
Variant(
|
||||||
|
"network",
|
||||||
|
Some(Record([("action", S32(action)), ("ssid", Str(ssid)), ("password", Str(password))])),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -206,3 +206,50 @@ interface battery {
|
|||||||
}
|
}
|
||||||
read: func() -> status;
|
read: func() -> status;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Network status and control (NetworkManager), for the network panel module. The shell talks to
|
||||||
|
/// NetworkManager over D-Bus; without it, status comes read-only from /sys/class/net and
|
||||||
|
/// /proc/net, `can-manage` is false and the actions do nothing.
|
||||||
|
interface network {
|
||||||
|
record net-status {
|
||||||
|
/// 0 offline, 1 wired, 2 Wi-Fi, 3 connecting.
|
||||||
|
state: u32,
|
||||||
|
/// Signal of the Wi-Fi network in use, 0..100 (0 when not on Wi-Fi).
|
||||||
|
signal: u32,
|
||||||
|
/// The Wi-Fi network's name, else the connection's (e.g. "Wired connection 1"); "" offline.
|
||||||
|
name: string,
|
||||||
|
/// An action's outcome or why it failed, to show ("" for nothing).
|
||||||
|
message: string,
|
||||||
|
wifi-enabled: bool,
|
||||||
|
/// Wi-Fi and mobile broadband both off.
|
||||||
|
airplane: bool,
|
||||||
|
/// The network can be changed from here (NetworkManager answers).
|
||||||
|
can-manage: bool,
|
||||||
|
/// There is a Wi-Fi device.
|
||||||
|
has-wifi: bool,
|
||||||
|
}
|
||||||
|
record wifi-network {
|
||||||
|
ssid: string,
|
||||||
|
/// 0..100.
|
||||||
|
signal: u32,
|
||||||
|
secured: bool,
|
||||||
|
/// The one in use.
|
||||||
|
active: bool,
|
||||||
|
/// There is a saved connection for it: connecting needs no password.
|
||||||
|
saved: bool,
|
||||||
|
}
|
||||||
|
status: func() -> net-status;
|
||||||
|
/// Wi-Fi networks in range, the one in use first, then by signal (empty with Wi-Fi off).
|
||||||
|
wifi-networks: func() -> list<wifi-network>;
|
||||||
|
/// Ask the Wi-Fi device to look for networks (the list fills in over a few seconds).
|
||||||
|
scan: func();
|
||||||
|
/// Connect to `ssid`: a saved network as saved, a new one with `password` ("" when open).
|
||||||
|
/// WPA/WPA2/WPA3 personal and open networks; the outcome shows in `status.message`.
|
||||||
|
connect: func(ssid: string, password: string);
|
||||||
|
/// Disconnect the Wi-Fi device.
|
||||||
|
disconnect: func();
|
||||||
|
/// Delete the saved connection(s) for `ssid`.
|
||||||
|
forget: func(ssid: string);
|
||||||
|
set-wifi-enabled: func(on: bool);
|
||||||
|
set-airplane-mode: func(on: bool);
|
||||||
|
}
|
||||||
+12
-1
@@ -54,7 +54,9 @@ interface plasmoids {
|
|||||||
/// i32 ('i') or a LE u32 byte length + UTF-8 ('s'). `which`: 0 apps (sssss: id name comment
|
/// i32 ('i') or a LE u32 byte length + UTF-8 ('s'). `which`: 0 apps (sssss: id name comment
|
||||||
/// category glyph), 1 windows (isii: id title focused minimized), 2 layouts (s), 3 modules
|
/// category glyph), 1 windows (isii: id title focused minimized), 2 layouts (s), 3 modules
|
||||||
/// (sssi: id name path loaded), 4 instances (sss: slot module name), 5 wallpapers (s), 6 session
|
/// (sssi: id name path loaded), 4 instances (sss: slot module name), 5 wallpapers (s), 6 session
|
||||||
/// settings (s), 7 icons (si: app id, raster image handle from `raster.load-image`) served by `icons.app-icon`.
|
/// settings (s), 7 icons (si: app id, raster image handle from `raster.load-image`) served by `icons.app-icon`,
|
||||||
|
/// 8 network status (one row, iissiiii: state signal name message wifi-enabled airplane
|
||||||
|
/// can-manage has-wifi), 9 Wi-Fi networks (siiii: ssid signal secured active saved).
|
||||||
publish-table: func(which: u32, rows: list<u8>);
|
publish-table: func(which: u32, rows: list<u8>);
|
||||||
/// Layout mode (0 tiling, 1 monocle, 2 floating) and whether the Interface Explorer is on.
|
/// Layout mode (0 tiling, 1 monocle, 2 floating) and whether the Interface Explorer is on.
|
||||||
publish-state: func(layout-mode: s32, inspector-on: bool);
|
publish-state: func(layout-mode: s32, inspector-on: bool);
|
||||||
@@ -91,6 +93,14 @@ interface plasmoids {
|
|||||||
}
|
}
|
||||||
publish-windows: func(wins: list<window-entry>);
|
publish-windows: func(wins: list<window-entry>);
|
||||||
|
|
||||||
|
/// A network module's action: 0 scan, 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode
|
||||||
|
/// off/on, 6 connect (ssid, password), 7 forget (ssid).
|
||||||
|
record network-request {
|
||||||
|
action: s32,
|
||||||
|
ssid: string,
|
||||||
|
password: string,
|
||||||
|
}
|
||||||
|
|
||||||
/// A module turning a session setting on or off.
|
/// A module turning a session setting on or off.
|
||||||
record setting-change {
|
record setting-change {
|
||||||
index: s32,
|
index: s32,
|
||||||
@@ -118,6 +128,7 @@ interface plasmoids {
|
|||||||
set-screen-off(s32),
|
set-screen-off(s32),
|
||||||
set-suspend-after(s32),
|
set-suspend-after(s32),
|
||||||
power-action(s32),
|
power-action(s32),
|
||||||
|
network(network-request),
|
||||||
}
|
}
|
||||||
/// The next pending request, oldest first.
|
/// The next pending request, oldest first.
|
||||||
next-request: func() -> option<request>;
|
next-request: func() -> option<request>;
|
||||||
|
|||||||
@@ -82,6 +82,7 @@ world plasmoid-host {
|
|||||||
import screenshot;
|
import screenshot;
|
||||||
import power;
|
import power;
|
||||||
import battery;
|
import battery;
|
||||||
|
import network;
|
||||||
export plasmoid;
|
export plasmoid;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,3 +117,10 @@ world battery-widget {
|
|||||||
import battery;
|
import battery;
|
||||||
export module-config;
|
export module-config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Network status (Ethernet, Wi-Fi name and signal, offline) and a popup to pick a Wi-Fi network,
|
||||||
|
/// connect, disconnect, and switch Wi-Fi or airplane mode.
|
||||||
|
world network-widget {
|
||||||
|
include widget;
|
||||||
|
import network;
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
Network status (Ethernet, Wi-Fi name and signal, offline) and a popup to pick a Wi-Fi network,
|
||||||
|
connect, disconnect, and switch Wi-Fi or airplane mode.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||||
|
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!
|
||||||
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
warnings = "-44"
|
||||||
Reference in new issue
Block a user