Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Add nectarlink-ffi: UniFFI bindings for the Android app

Bee63e9adb712a3
diff --git a/Cargo.lock b/Cargo.lock
index d9cf27e..cb1b701 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -141,6 +141,59 @@ version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
+[[package]]
+name = "askama"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6024d73179f43f15ccd2b881bfea6fee7f3a46ec53f33b52210dea749ebebaa4"
+dependencies = [
+ "askama_macros",
+ "itoa",
+ "percent-encoding",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "askama_derive"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071ee5ebf2138e3ad180e0aacf6940c2cab5e6d8333741d9925c7bee2b153f39"
+dependencies = [
+ "askama_parser",
+ "basic-toml",
+ "glob",
+ "memchr",
+ "proc-macro2",
+ "quote",
+ "rustc-hash",
+ "serde",
+ "serde_derive",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "askama_macros"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "643e1c7cbb6aec1d920332fe51a7c0d8219e273dcb8602db03f5263e4d16487b"
+dependencies = [
+ "askama_derive",
+]
+
+[[package]]
+name = "askama_parser"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c5ae75772275d268b03ab8bdccdd12117b6169ee23256942b34e46c9f476583"
+dependencies = [
+ "rustc-hash",
+ "serde",
+ "serde_derive",
+ "unicode-ident",
+ "winnow",
+]
+
[[package]]
name = "async_io_stream"
version = "0.3.3"
@@ -211,6 +264,15 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+[[package]]
+name = "basic-toml"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -260,6 +322,39 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+[[package]]
+name = "camino"
+version = "1.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "cargo-platform"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd0061da739915fae12ea00e16397555ed4371a6bb285431aab930f61b0aa4ba"
+dependencies = [
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "cargo_metadata"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9"
+dependencies = [
+ "camino",
+ "cargo-platform",
+ "semver",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "cc"
version = "1.6.0"
@@ -1005,6 +1100,15 @@ dependencies = [
"percent-encoding",
]
+[[package]]
+name = "fs-err"
+version = "3.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5c95b673b8f6f7235229ae11c5642d81b04c2e64c1e2fb417bc0cf73ca45f29"
+dependencies = [
+ "autocfg",
+]
+
[[package]]
name = "futures"
version = "0.3.34"
@@ -1181,6 +1285,12 @@ dependencies = [
"polyval",
]
+[[package]]
+name = "glob"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
+
[[package]]
name = "gloo-timers"
version = "0.3.0"
@@ -1193,6 +1303,17 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "goblin"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47"
+dependencies = [
+ "log",
+ "plain",
+ "scroll",
+]
+
[[package]]
name = "h2"
version = "0.4.19"
@@ -1571,6 +1692,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown 0.17.1",
+ "serde",
+ "serde_core",
]
[[package]]
@@ -2017,6 +2140,12 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
[[package]]
name = "mio"
version = "1.2.4"
@@ -2112,6 +2241,15 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
+[[package]]
+name = "ndk-sys"
+version = "0.5.0+25.2.9519653"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691"
+dependencies = [
+ "jni-sys 0.3.1",
+]
+
[[package]]
name = "nectarlink-cli"
version = "0.0.1"
@@ -2169,6 +2307,19 @@ dependencies = [
"windows",
]
+[[package]]
+name = "nectarlink-ffi"
+version = "0.0.1"
+dependencies = [
+ "nectarlink-core",
+ "paranoid-android",
+ "thiserror 2.0.21",
+ "tokio",
+ "tracing",
+ "tracing-subscriber",
+ "uniffi",
+]
+
[[package]]
name = "nectarlink-protocol"
version = "0.0.1"
@@ -2352,6 +2503,16 @@ dependencies = [
"wmi",
]
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
[[package]]
name = "noq"
version = "1.3.0"
@@ -2594,6 +2755,20 @@ dependencies = [
"seize",
]
+[[package]]
+name = "paranoid-android"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "101795d63d371b43e38d6e7254677657be82f17022f7f7893c268f33ac0caadc"
+dependencies = [
+ "lazy_static",
+ "ndk-sys",
+ "sharded-slab",
+ "smallvec",
+ "tracing-core",
+ "tracing-subscriber",
+]
+
[[package]]
name = "parking"
version = "2.2.1"
@@ -2696,6 +2871,12 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+[[package]]
+name = "plain"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
+
[[package]]
name = "plist"
version = "1.10.1"
@@ -3160,6 +3341,26 @@ version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2"
+[[package]]
+name = "scroll"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6"
+dependencies = [
+ "scroll_derive",
+]
+
+[[package]]
+name = "scroll_derive"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -3194,6 +3395,10 @@ name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+dependencies = [
+ "serde",
+ "serde_core",
+]
[[package]]
name = "send_wrapper"
@@ -3254,6 +3459,15 @@ dependencies = [
"zmij",
]
+[[package]]
+name = "serde_spanned"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
+dependencies = [
+ "serde_core",
+]
+
[[package]]
name = "serdect"
version = "0.4.3"
@@ -3340,6 +3554,12 @@ dependencies = [
"bitflags",
]
+[[package]]
+name = "siphasher"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
+
[[package]]
name = "slab"
version = "0.4.12"
@@ -3352,6 +3572,12 @@ version = "1.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
+[[package]]
+name = "smawk"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100"
+
[[package]]
name = "smol_str"
version = "0.1.24"
@@ -3558,6 +3784,16 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "textwrap"
+version = "0.16.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ecfad6c3abc80a577f2b91c1e412ee57e7a060d430b553c1b0c940974ebcd49"
+dependencies = [
+ "smawk",
+ "unicode-width 0.2.2",
+]
+
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -3741,6 +3977,21 @@ dependencies = [
"tokio-util",
]
+[[package]]
+name = "toml"
+version = "1.1.6+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
+dependencies = [
+ "indexmap",
+ "serde_core",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_parser",
+ "toml_writer",
+ "winnow",
+]
+
[[package]]
name = "toml_datetime"
version = "1.1.1+spec-1.1.0"
@@ -3771,6 +4022,12 @@ dependencies = [
"winnow",
]
+[[package]]
+name = "toml_writer"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
+
[[package]]
name = "tower"
version = "0.5.3"
@@ -3920,6 +4177,127 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+[[package]]
+name = "uniffi"
+version = "0.32.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76407f5f396a2c949a069eff4a9fca9ce462410eb872bffef4c2b7b89804a77a"
+dependencies = [
+ "anyhow",
+ "camino",
+ "cargo_metadata",
+ "clap",
+ "uniffi_bindgen",
+ "uniffi_core",
+ "uniffi_macros",
+ "uniffi_pipeline",
+]
+
+[[package]]
+name = "uniffi_bindgen"
+version = "0.32.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3df3ced8f0eda3de99f6d50820e8628f443da8e4f447f477d1403ceba29dacbd"
+dependencies = [
+ "anyhow",
+ "askama",
+ "camino",
+ "cargo_metadata",
+ "fs-err",
+ "glob",
+ "goblin",
+ "heck",
+ "indexmap",
+ "once_cell",
+ "serde",
+ "tempfile",
+ "textwrap",
+ "toml",
+ "uniffi_internal_macros",
+ "uniffi_meta",
+ "uniffi_pipeline",
+ "uniffi_udl",
+]
+
+[[package]]
+name = "uniffi_core"
+version = "0.32.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7530ae8efeaaa488622865966763fe0294832779fff80508c36d69c6a874a6a"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "once_cell",
+ "static_assertions",
+]
+
+[[package]]
+name = "uniffi_internal_macros"
+version = "0.32.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f4bad017164375d99450d70495014810d15a84ba9da6ed14b9628b1424223ba"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "uniffi_macros"
+version = "0.32.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b855a58da153739ce6e863f6e296edc3716a093768c4d3d957f17f5e4317c60"
+dependencies = [
+ "camino",
+ "fs-err",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "serde",
+ "syn 2.0.119",
+ "toml",
+ "uniffi_meta",
+]
+
+[[package]]
+name = "uniffi_meta"
+version = "0.32.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af0c88664a9cb9559856f5a250283c9708923b303170e2e5c7db8f4ad65e9459"
+dependencies = [
+ "anyhow",
+ "siphasher",
+ "uniffi_internal_macros",
+ "uniffi_pipeline",
+]
+
+[[package]]
+name = "uniffi_pipeline"
+version = "0.32.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d00f5c044b4a3dca0b1226c92ddaeea626f337470e22180dd182160c87a06b0b"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "tempfile",
+ "uniffi_internal_macros",
+]
+
+[[package]]
+name = "uniffi_udl"
+version = "0.32.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55dfd9c778d6b39cb5acd541d9ff63431974035d2bad83c897b766a6ee3152ac"
+dependencies = [
+ "anyhow",
+ "textwrap",
+ "uniffi_meta",
+ "weedle2",
+]
+
[[package]]
name = "universal-hash"
version = "0.5.1"
@@ -4111,6 +4489,15 @@ dependencies = [
"rustls-pki-types",
]
+[[package]]
+name = "weedle2"
+version = "5.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e"
+dependencies = [
+ "nom",
+]
+
[[package]]
name = "which"
version = "8.0.6"
diff --git a/Cargo.toml b/Cargo.toml
index 55b2762..7a4bf3d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,6 +4,7 @@ members = [
"core/nectarlink-protocol",
"core/nectarlink-core",
"core/nectarlink-cli",
+ "core/nectarlink-ffi",
"desktop/app",
"tools/xtask",
"spikes/s1-qt-rust",
@@ -43,6 +44,7 @@ serde_bytes = "0.11"
sha2 = "0.11"
tempfile = "3"
thiserror = "2"
+uniffi = "0.32"
tokio-util = "0.7"
tokio = { version = "1.53", features = ["rt-multi-thread", "macros", "io-util", "sync", "time", "fs"] }
tracing = "0.1"
diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rs
index 39c5f70..aadb321 100644
--- a/core/nectarlink-core/src/features.rs
+++ b/core/nectarlink-core/src/features.rs
@@ -132,6 +132,31 @@ pub enum UpgradeAction {
UpdateApp(Role),
}
+impl UpgradeAction {
+ /// A stable `(action, target)` pair for UIs and bindings, e.g.
+ /// `("raisePower", "elevated")` or `("enableToggle", "clipboard")`.
+ pub fn describe(self) -> (&'static str, String) {
+ match self {
+ UpgradeAction::RaisePower(level) => (
+ "raisePower",
+ match level {
+ PowerLevel::Assist => "assist",
+ PowerLevel::Elevated => "elevated",
+ _ => "basic",
+ }
+ .into(),
+ ),
+ UpgradeAction::GrantPermission(p) => ("grantPermission", p.as_str().into()),
+ UpgradeAction::EnableAddon(addon) => ("enableAddon", addon.into()),
+ UpgradeAction::EnablePath(ConnectionPath::Relay) => ("enablePath", "relay".into()),
+ UpgradeAction::EnablePath(ConnectionPath::Lan) => ("enablePath", "lan".into()),
+ UpgradeAction::EnableDeviceToggle(toggle) => ("enableToggle", toggle.into()),
+ UpgradeAction::UpdateApp(Role::Phone) => ("updateApp", "phone".into()),
+ UpgradeAction::UpdateApp(Role::Desktop) => ("updateApp", "desktop".into()),
+ }
+ }
+}
+
/// Roughly how long an upgrade takes, so the UI can say "~2 min".
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Effort {
@@ -176,6 +201,29 @@ pub enum UnsupportedReason {
NotOnThisDevice,
}
+impl UnsupportedReason {
+ /// A stable key for UIs and bindings: `deviceKinds`, `android:<release>`,
+ /// `windows:<build>` or `notOnThisDevice`.
+ pub fn describe(self) -> String {
+ match self {
+ UnsupportedReason::DeviceKinds => "deviceKinds".into(),
+ UnsupportedReason::AndroidTooOld { needs } => format!("android:{needs}"),
+ UnsupportedReason::WindowsTooOld { needs_build } => format!("windows:{needs_build}"),
+ UnsupportedReason::NotOnThisDevice => "notOnThisDevice".into(),
+ }
+ }
+}
+
+impl Effort {
+ /// Whole minutes (0 for instant).
+ pub fn minutes(self) -> u8 {
+ match self {
+ Effort::Instant => 0,
+ Effort::Minutes(m) => m,
+ }
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FeatureState {
Available,
diff --git a/core/nectarlink-ffi/Cargo.toml b/core/nectarlink-ffi/Cargo.toml
new file mode 100644
index 0000000..801bc3f
--- /dev/null
+++ b/core/nectarlink-ffi/Cargo.toml
@@ -0,0 +1,36 @@
+[package]
+name = "nectarlink-ffi"
+description = "UniFFI bindings for nectarlink-core (used by the Android app)"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+authors.workspace = true
+repository.workspace = true
+license = "MPL-2.0"
+publish = false
+
+[lib]
+crate-type = ["cdylib", "lib"]
+
+[[bin]]
+# Generates the Kotlin bindings: see android/README.md.
+name = "uniffi-bindgen"
+path = "src/bin/uniffi-bindgen.rs"
+required-features = ["bindgen"]
+
+[features]
+bindgen = ["uniffi/cli"]
+
+[dependencies]
+nectarlink-core.workspace = true
+thiserror.workspace = true
+tokio.workspace = true
+tracing.workspace = true
+tracing-subscriber.workspace = true
+uniffi.workspace = true
+
+[target.'cfg(target_os = "android")'.dependencies]
+paranoid-android = "0.2"
+
+[lints]
+workspace = true
diff --git a/core/nectarlink-ffi/src/bin/uniffi-bindgen.rs b/core/nectarlink-ffi/src/bin/uniffi-bindgen.rs
new file mode 100644
index 0000000..dc4410f
--- /dev/null
+++ b/core/nectarlink-ffi/src/bin/uniffi-bindgen.rs
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Generates foreign-language bindings for this crate (library mode).
+
+fn main() {
+ uniffi::uniffi_bindgen_main()
+}
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
new file mode 100644
index 0000000..9860bf4
--- /dev/null
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -0,0 +1,733 @@
+// SPDX-License-Identifier: MPL-2.0
+//! UniFFI bindings for `nectarlink-core`, used by the Android app.
+//!
+//! The boundary uses plain records and enums (see
+//! docs/architecture/core-api.md). The node runs on its own Tokio runtime;
+//! every async method executes there, so the foreign side can await it from
+//! any executor (Kotlin coroutines). Events are delivered to a foreign
+//! listener on a core thread; the listener should hand them off quickly.
+
+use std::{path::PathBuf, sync::Arc, time::Duration};
+
+use nectarlink_core as core;
+use nectarlink_core::{
+ ConnectionPath, DeviceId, LinkState, Node, NodeConfig, NodeEvent, PairingEvent,
+ features::{CapabilityMatrix, FeatureState},
+};
+use tokio::{runtime::Runtime, sync::broadcast::error::RecvError};
+
+uniffi::setup_scaffolding!();
+
+const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3);
+
+// ---- Records and enums ----
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum DeviceKind {
+ Phone,
+ Tablet,
+ Desktop,
+ Laptop,
+ Unknown,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct DeviceInfo {
+ pub name: String,
+ pub kind: DeviceKind,
+ /// "android", "windows" or "macos".
+ pub os: String,
+ pub os_version: String,
+ pub model: Option<String>,
+ /// ARGB seed color for Material You sync.
+ pub accent: Option<u32>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum PowerLevel {
+ Basic,
+ Assist,
+ Elevated,
+ /// Desktops.
+ NotApplicable,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct Battery {
+ /// 0–100.
+ pub level: u8,
+ pub charging: bool,
+ /// "ac", "usb" or "wireless".
+ pub plugged: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
+pub enum Link {
+ /// `last_seen` is in Unix seconds.
+ Offline {
+ last_seen: Option<i64>,
+ },
+ Connecting,
+ Online {
+ relayed: bool,
+ rtt_ms: u32,
+ },
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct PairedDevice {
+ /// The device ID (z-base-32).
+ pub id: String,
+ pub info: DeviceInfo,
+ /// Unix seconds.
+ pub paired_at: i64,
+ pub link: Link,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct DiscoveredDevice {
+ pub id: String,
+ pub name: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
+pub enum PairingFailure {
+ Rejected,
+ Declined,
+ Expired,
+ Unreachable,
+ Other { message: String },
+}
+
+/// What unlocks a feature (see docs/architecture/capabilities.md).
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct Upgrade {
+ /// "raisePower", "grantPermission", "enableAddon", "enablePath",
+ /// "enableToggle" or "updateApp".
+ pub action: String,
+ /// E.g. "elevated", "notification_access", "clipboard", "phone".
+ pub target: String,
+ /// Roughly how long it takes; 0 for instant.
+ pub minutes: u8,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
+pub enum FeatureStatus {
+ Available,
+ Partial {
+ limit: String,
+ upgrade: Option<Upgrade>,
+ },
+ Locked {
+ upgrade: Upgrade,
+ },
+ /// `reason`: "deviceKinds", "android:<release>", "windows:<build>" or
+ /// "notOnThisDevice".
+ Unsupported {
+ reason: String,
+ },
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct Feature {
+ pub id: String,
+ pub status: FeatureStatus,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct DeviceToggle {
+ pub name: String,
+ pub enabled: bool,
+}
+
+/// Everything the UI needs to know about, as it happens.
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
+pub enum Event {
+ DeviceAdded {
+ device: PairedDevice,
+ },
+ DeviceRemoved {
+ id: String,
+ },
+ LinkChanged {
+ id: String,
+ link: Link,
+ },
+ PeerInfoChanged {
+ id: String,
+ info: DeviceInfo,
+ },
+ PeerPowerChanged {
+ id: String,
+ power: PowerLevel,
+ },
+ Battery {
+ id: String,
+ battery: Battery,
+ },
+ /// A device asked this one to start (or stop) ringing.
+ Ring {
+ id: String,
+ on: bool,
+ },
+ Discovered {
+ device: DiscoveredDevice,
+ },
+ DiscoveryExpired {
+ id: String,
+ },
+ /// Show this 6-digit code and ask the user whether it matches.
+ PairingCode {
+ peer: String,
+ code: String,
+ },
+ Paired {
+ device: PairedDevice,
+ },
+ PairingFailed {
+ failure: PairingFailure,
+ },
+ Capabilities {
+ id: String,
+ features: Vec<Feature>,
+ },
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]
+pub enum NectarlinkError {
+ #[error("device is not paired")]
+ NotPaired,
+ #[error("device is offline")]
+ Offline,
+ #[error("the operation was denied")]
+ Denied,
+ #[error("declined")]
+ Declined,
+ #[error("timed out")]
+ Timeout,
+ /// `this_device`: whether this app (true) or the other device's app
+ /// (false) needs an update.
+ #[error("an app is too old for this connection")]
+ VersionTooOld { this_device: bool },
+ #[error("not supported by the other device")]
+ Unsupported,
+ #[error("no pairing in progress")]
+ NotPairing,
+ #[error("invalid pairing link")]
+ InvalidPairingLink,
+ #[error("invalid device ID")]
+ InvalidDeviceId,
+ #[error("network error: {message}")]
+ Network { message: String },
+ #[error("storage error: {message}")]
+ Storage { message: String },
+ #[error("internal error: {message}")]
+ Internal { message: String },
+}
+
+impl From<core::Error> for NectarlinkError {
+ fn from(e: core::Error) -> Self {
+ match e {
+ core::Error::NotPaired => NectarlinkError::NotPaired,
+ core::Error::Offline => NectarlinkError::Offline,
+ core::Error::Denied => NectarlinkError::Denied,
+ core::Error::Declined => NectarlinkError::Declined,
+ core::Error::Timeout => NectarlinkError::Timeout,
+ core::Error::VersionTooOld { side } => {
+ NectarlinkError::VersionTooOld { this_device: side == core::Side::Local }
+ }
+ core::Error::Unsupported => NectarlinkError::Unsupported,
+ core::Error::NotPairing => NectarlinkError::NotPairing,
+ core::Error::InvalidPairingLink(_) => NectarlinkError::InvalidPairingLink,
+ core::Error::Network(message) => NectarlinkError::Network { message },
+ core::Error::Storage(message) => NectarlinkError::Storage { message },
+ core::Error::Io(e) => NectarlinkError::Storage { message: e.to_string() },
+ core::Error::Protocol(message) | core::Error::Internal(message) => {
+ NectarlinkError::Internal { message }
+ }
+ }
+ }
+}
+
+type Result<T, E = NectarlinkError> = std::result::Result<T, E>;
+
+// ---- Conversions ----
+
+impl From<core::DeviceKind> for DeviceKind {
+ fn from(kind: core::DeviceKind) -> Self {
+ match kind {
+ core::DeviceKind::Phone => DeviceKind::Phone,
+ core::DeviceKind::Tablet => DeviceKind::Tablet,
+ core::DeviceKind::Desktop => DeviceKind::Desktop,
+ core::DeviceKind::Laptop => DeviceKind::Laptop,
+ core::DeviceKind::Unknown => DeviceKind::Unknown,
+ }
+ }
+}
+
+impl From<DeviceKind> for core::DeviceKind {
+ fn from(kind: DeviceKind) -> Self {
+ match kind {
+ DeviceKind::Phone => core::DeviceKind::Phone,
+ DeviceKind::Tablet => core::DeviceKind::Tablet,
+ DeviceKind::Desktop => core::DeviceKind::Desktop,
+ DeviceKind::Laptop => core::DeviceKind::Laptop,
+ DeviceKind::Unknown => core::DeviceKind::Unknown,
+ }
+ }
+}
+
+impl From<core::DeviceInfo> for DeviceInfo {
+ fn from(i: core::DeviceInfo) -> Self {
+ DeviceInfo {
+ name: i.name,
+ kind: i.kind.into(),
+ os: i.os,
+ os_version: i.os_ver,
+ model: i.model,
+ accent: i.accent,
+ }
+ }
+}
+
+impl From<DeviceInfo> for core::DeviceInfo {
+ fn from(i: DeviceInfo) -> Self {
+ core::DeviceInfo {
+ name: i.name,
+ kind: i.kind.into(),
+ os: i.os,
+ os_ver: i.os_version,
+ model: i.model,
+ accent: i.accent,
+ }
+ }
+}
+
+impl From<core::PowerLevel> for PowerLevel {
+ fn from(p: core::PowerLevel) -> Self {
+ match p.effective() {
+ core::PowerLevel::Assist => PowerLevel::Assist,
+ core::PowerLevel::Elevated => PowerLevel::Elevated,
+ core::PowerLevel::NotApplicable => PowerLevel::NotApplicable,
+ core::PowerLevel::Basic | core::PowerLevel::Unknown => PowerLevel::Basic,
+ }
+ }
+}
+
+impl From<PowerLevel> for core::PowerLevel {
+ fn from(p: PowerLevel) -> Self {
+ match p {
+ PowerLevel::Basic => core::PowerLevel::Basic,
+ PowerLevel::Assist => core::PowerLevel::Assist,
+ PowerLevel::Elevated => core::PowerLevel::Elevated,
+ PowerLevel::NotApplicable => core::PowerLevel::NotApplicable,
+ }
+ }
+}
+
+impl From<core::Battery> for Battery {
+ fn from(b: core::Battery) -> Self {
+ Battery { level: b.level, charging: b.charging, plugged: b.plugged }
+ }
+}
+
+impl From<Battery> for core::Battery {
+ fn from(b: Battery) -> Self {
+ core::Battery { level: b.level.min(100), charging: b.charging, plugged: b.plugged }
+ }
+}
+
+impl From<LinkState> for Link {
+ fn from(l: LinkState) -> Self {
+ match l {
+ LinkState::Offline { last_seen } => Link::Offline { last_seen },
+ LinkState::Connecting => Link::Connecting,
+ LinkState::Online { path, rtt_ms } => {
+ Link::Online { relayed: path == ConnectionPath::Relay, rtt_ms }
+ }
+ }
+ }
+}
+
+impl From<core::PairedDevice> for PairedDevice {
+ fn from(d: core::PairedDevice) -> Self {
+ PairedDevice {
+ id: d.id.to_string(),
+ info: d.info.into(),
+ paired_at: d.paired_at,
+ link: d.link.into(),
+ }
+ }
+}
+
+impl From<core::DiscoveredDevice> for DiscoveredDevice {
+ fn from(d: core::DiscoveredDevice) -> Self {
+ DiscoveredDevice { id: d.id.to_string(), name: d.name }
+ }
+}
+
+impl From<core::PairingFailure> for PairingFailure {
+ fn from(f: core::PairingFailure) -> Self {
+ match f {
+ core::PairingFailure::Rejected => PairingFailure::Rejected,
+ core::PairingFailure::Declined => PairingFailure::Declined,
+ core::PairingFailure::Expired => PairingFailure::Expired,
+ core::PairingFailure::Unreachable => PairingFailure::Unreachable,
+ core::PairingFailure::Other(message) => PairingFailure::Other { message },
+ }
+ }
+}
+
+fn upgrade(u: core::features::Upgrade) -> Upgrade {
+ let (action, target) = u.action.describe();
+ Upgrade { action: action.into(), target, minutes: u.effort.minutes() }
+}
+
+impl From<FeatureState> for FeatureStatus {
+ fn from(state: FeatureState) -> Self {
+ match state {
+ FeatureState::Available => FeatureStatus::Available,
+ FeatureState::Partial { limit, upgrade: u } => {
+ FeatureStatus::Partial { limit: limit.into(), upgrade: u.map(upgrade) }
+ }
+ FeatureState::Locked { upgrade: u } => FeatureStatus::Locked { upgrade: upgrade(u) },
+ FeatureState::Unsupported { reason } => FeatureStatus::Unsupported { reason: reason.describe() },
+ }
+ }
+}
+
+fn features(matrix: &CapabilityMatrix) -> Vec<Feature> {
+ matrix.features.iter().map(|(id, state)| Feature { id: (*id).into(), status: (*state).into() }).collect()
+}
+
+impl From<NodeEvent> for Event {
+ fn from(event: NodeEvent) -> Self {
+ match event {
+ NodeEvent::DeviceAdded(device) => Event::DeviceAdded { device: device.into() },
+ NodeEvent::DeviceRemoved(id) => Event::DeviceRemoved { id: id.to_string() },
+ NodeEvent::LinkChanged { device, link } => {
+ Event::LinkChanged { id: device.to_string(), link: link.into() }
+ }
+ NodeEvent::PeerInfoChanged { device, info } => {
+ Event::PeerInfoChanged { id: device.to_string(), info: info.into() }
+ }
+ NodeEvent::PeerPowerChanged { device, power } => {
+ Event::PeerPowerChanged { id: device.to_string(), power: power.into() }
+ }
+ NodeEvent::Battery { device, battery } => {
+ Event::Battery { id: device.to_string(), battery: battery.into() }
+ }
+ NodeEvent::Ring { device, on } => Event::Ring { id: device.to_string(), on },
+ NodeEvent::Discovered(device) => Event::Discovered { device: device.into() },
+ NodeEvent::DiscoveryExpired(id) => Event::DiscoveryExpired { id: id.to_string() },
+ NodeEvent::Pairing(PairingEvent::SasCode { peer, code }) => {
+ Event::PairingCode { peer: peer.to_string(), code }
+ }
+ NodeEvent::Pairing(PairingEvent::Paired(device)) => Event::Paired { device: device.into() },
+ NodeEvent::Pairing(PairingEvent::Failed(failure)) => {
+ Event::PairingFailed { failure: failure.into() }
+ }
+ NodeEvent::Capabilities(matrix) => {
+ Event::Capabilities { id: matrix.device.to_string(), features: features(&matrix) }
+ }
+ }
+ }
+}
+
+fn parse_id(id: &str) -> Result<DeviceId> {
+ id.parse().map_err(|_| NectarlinkError::InvalidDeviceId)
+}
+
+// ---- Foreign interfaces (implemented in Kotlin) ----
+
+/// What the app does for the core: ring the phone.
+#[uniffi::export(with_foreign)]
+pub trait Platform: Send + Sync {
+ /// Ring loudly, even in silent mode, until `stop_ringing`.
+ fn start_ringing(&self);
+ fn stop_ringing(&self);
+}
+
+/// Encrypts the device key at rest (Android: a Keystore key).
+#[uniffi::export(with_foreign)]
+pub trait KeyProtector: Send + Sync {
+ fn protect(&self, plaintext: Vec<u8>) -> Result<Vec<u8>>;
+ fn unprotect(&self, ciphertext: Vec<u8>) -> Result<Vec<u8>>;
+}
+
+/// Receives core events on a core thread. Hand them off; don't block.
+#[uniffi::export(with_foreign)]
+pub trait EventListener: Send + Sync {
+ fn on_event(&self, event: Event);
+}
+
+struct PlatformAdapter(Arc<dyn Platform>);
+
+impl std::fmt::Debug for PlatformAdapter {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("PlatformAdapter")
+ }
+}
+
+impl core::Platform for PlatformAdapter {
+ fn start_ringing(&self) {
+ self.0.start_ringing();
+ }
+ fn stop_ringing(&self) {
+ self.0.stop_ringing();
+ }
+}
+
+struct KeyProtectorAdapter(Arc<dyn KeyProtector>);
+
+/// Key files written with the Android Keystore protector.
+const ANDROID_KEYSTORE_PROTECTOR: u8 = 2;
+
+impl core::KeyProtector for KeyProtectorAdapter {
+ fn id(&self) -> u8 {
+ ANDROID_KEYSTORE_PROTECTOR
+ }
+ fn protect(&self, plaintext: &[u8]) -> std::io::Result<Vec<u8>> {
+ self.0.protect(plaintext.to_vec()).map_err(std::io::Error::other)
+ }
+ fn unprotect(&self, ciphertext: &[u8]) -> std::io::Result<Vec<u8>> {
+ self.0.unprotect(ciphertext.to_vec()).map_err(std::io::Error::other)
+ }
+}
+
+// ---- The node ----
+
+#[derive(Debug, Clone, uniffi::Record)]
+pub struct NodeOptions {
+ /// App-private directory for the identity and database.
+ pub data_dir: String,
+ pub device: DeviceInfo,
+ pub app_version: String,
+ pub power: PowerLevel,
+ /// Allow connections through relays when away from home.
+ pub away_mode: bool,
+}
+
+/// The Nectarlink engine. One per app process.
+#[derive(uniffi::Object)]
+pub struct NectarlinkNode {
+ runtime: Runtime,
+ node: Node,
+}
+
+impl std::fmt::Debug for NectarlinkNode {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("NectarlinkNode").field("node", &self.node).finish_non_exhaustive()
+ }
+}
+
+impl NectarlinkNode {
+ /// Runs `fut` on the node's runtime and waits for it from the caller's
+ /// executor.
+ async fn run<T: Send + 'static>(&self, fut: impl Future<Output = T> + Send + 'static) -> T {
+ match self.runtime.spawn(fut).await {
+ Ok(value) => value,
+ Err(e) => std::panic::resume_unwind(e.into_panic()),
+ }
+ }
+}
+
+#[uniffi::export]
+impl NectarlinkNode {
+ /// Loads or creates this device's identity and trust store, starts
+ /// networking and starts delivering events to `listener`. Blocks for
+ /// the (short) startup; call it off the main thread.
+ #[uniffi::constructor]
+ pub fn start(
+ options: NodeOptions,
+ platform: Arc<dyn Platform>,
+ key_protector: Arc<dyn KeyProtector>,
+ listener: Arc<dyn EventListener>,
+ ) -> Result<Arc<Self>> {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .thread_name("nectarlink-core")
+ .enable_all()
+ .build()
+ .map_err(|e| NectarlinkError::Internal { message: e.to_string() })?;
+ let mut config =
+ NodeConfig::new(PathBuf::from(options.data_dir), options.device.into(), options.app_version);
+ config.power = options.power.into();
+ config.away_mode = options.away_mode;
+ config.key_protector = Some(Arc::new(KeyProtectorAdapter(key_protector)));
+ let node = runtime.block_on(Node::start(config, Arc::new(PlatformAdapter(platform))))?;
+
+ let mut events = node.events();
+ runtime.spawn(async move {
+ loop {
+ match events.recv().await {
+ Ok(event) => listener.on_event(event.into()),
+ Err(RecvError::Lagged(missed)) => tracing::warn!(missed, "event listener fell behind"),
+ Err(RecvError::Closed) => return,
+ }
+ }
+ });
+ Ok(Arc::new(NectarlinkNode { runtime, node }))
+ }
+
+ /// This device's ID (z-base-32).
+ pub fn device_id(&self) -> String {
+ self.node.device_id().to_string()
+ }
+
+ /// Stops networking and tells connected devices.
+ pub async fn shutdown(&self) {
+ let node = self.node.clone();
+ self.run(async move {
+ if tokio::time::timeout(SHUTDOWN_TIMEOUT, node.shutdown()).await.is_err() {
+ tracing::warn!("shutdown timed out");
+ }
+ })
+ .await;
+ }
+
+ // ---- Pairing ----
+
+ /// Enters pairing mode and returns the link to show as a QR code.
+ pub async fn pairing_start_qr(&self) -> Result<String> {
+ let node = self.node.clone();
+ self.run(async move { Ok(node.pairing_start_qr().await?.to_uri()) }).await
+ }
+
+ /// Pairs with the device whose pairing link was scanned.
+ pub async fn pairing_join(&self, link: String) -> Result<()> {
+ let node = self.node.clone();
+ self.run(async move { Ok(node.pairing_join(&link).await?) }).await
+ }
+
+ /// Starts nearby pairing with a discovered device in pairing mode; the
+ /// code to compare arrives as `Event::PairingCode`.
+ pub async fn pairing_start_nearby(&self, peer: String) -> Result<()> {
+ let peer = parse_id(&peer)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.pairing_start_nearby(peer).await?) }).await
+ }
+
+ /// Answers the code comparison.
+ pub fn pairing_confirm(&self, codes_match: bool) -> Result<()> {
+ Ok(self.node.pairing_confirm(codes_match)?)
+ }
+
+ pub fn pairing_cancel(&self) {
+ self.node.pairing_cancel();
+ }
+
+ pub fn discovered_devices(&self) -> Vec<DiscoveredDevice> {
+ self.node.discovered_devices().into_iter().map(Into::into).collect()
+ }
+
+ // ---- Paired devices ----
+
+ pub fn paired_devices(&self) -> Result<Vec<PairedDevice>> {
+ Ok(self.node.paired_devices()?.into_iter().map(Into::into).collect())
+ }
+
+ pub async fn unpair(&self, id: String) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.unpair(id).await?) }).await
+ }
+
+ pub async fn ring(&self, id: String, on: bool) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.ring(id, on).await?) }).await
+ }
+
+ pub fn capabilities(&self, id: String) -> Result<Vec<Feature>> {
+ Ok(features(&self.node.capabilities(parse_id(&id)?)?))
+ }
+
+ pub fn device_toggles(&self, id: String) -> Result<Vec<DeviceToggle>> {
+ Ok(self
+ .node
+ .device_toggles(parse_id(&id)?)?
+ .into_iter()
+ .map(|(name, enabled)| DeviceToggle { name: name.into(), enabled })
+ .collect())
+ }
+
+ pub fn set_device_toggle(&self, id: String, name: String, enabled: bool) -> Result<()> {
+ Ok(self.node.set_device_toggle(parse_id(&id)?, &name, enabled)?)
+ }
+
+ // ---- This device ----
+
+ pub async fn update_battery(&self, battery: Battery) {
+ let node = self.node.clone();
+ self.run(async move { node.update_battery(battery.into()).await }).await;
+ }
+
+ pub async fn update_device_info(&self, info: DeviceInfo) {
+ let node = self.node.clone();
+ self.run(async move { node.update_device_info(info.into()).await }).await;
+ }
+
+ /// Updates this phone's power level and the capabilities it offers on
+ /// top of the built-in ones (they depend on permissions and power).
+ pub async fn update_power(&self, power: PowerLevel, capabilities: Vec<String>) {
+ let node = self.node.clone();
+ self.run(async move { node.update_power(power.into(), capabilities).await }).await;
+ }
+
+ /// Call when connectivity changes (Android doesn't tell native code).
+ pub async fn network_changed(&self) {
+ let node = self.node.clone();
+ self.run(async move { node.network_changed().await }).await;
+ }
+}
+
+/// Sends core logs to the platform log (logcat on Android). Call once,
+/// before starting the node. `filter` uses tracing's syntax, e.g. "info".
+#[uniffi::export]
+pub fn init_logging(filter: String) {
+ use tracing_subscriber::{EnvFilter, prelude::*};
+ let filter = EnvFilter::try_new(&filter).unwrap_or_else(|_| EnvFilter::new("info"));
+ #[cfg(target_os = "android")]
+ let layer = paranoid_android::layer("Nectarlink");
+ #[cfg(not(target_os = "android"))]
+ let layer = tracing_subscriber::fmt::layer();
+ let _ = tracing_subscriber::registry().with(filter).with(layer).try_init();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn errors_map_to_actionable_variants() {
+ assert_eq!(NectarlinkError::from(core::Error::Offline), NectarlinkError::Offline);
+ assert_eq!(
+ NectarlinkError::from(core::Error::VersionTooOld { side: core::Side::Remote }),
+ NectarlinkError::VersionTooOld { this_device: false }
+ );
+ assert!(matches!(
+ NectarlinkError::from(core::Error::Internal("x".into())),
+ NectarlinkError::Internal { message } if message == "x"
+ ));
+ }
+
+ #[test]
+ fn device_info_round_trips() {
+ let info = DeviceInfo {
+ name: "Pixel".into(),
+ kind: DeviceKind::Phone,
+ os: "android".into(),
+ os_version: "16".into(),
+ model: Some("Google Pixel 9".into()),
+ accent: Some(0xFF8A5100),
+ };
+ assert_eq!(DeviceInfo::from(core::DeviceInfo::from(info.clone())), info);
+ }
+
+ #[test]
+ fn batteries_are_clamped() {
+ let b: core::Battery = Battery { level: 140, charging: true, plugged: None }.into();
+ assert_eq!(b.level, 100);
+ }
+}
diff --git a/core/nectarlink-ffi/uniffi.toml b/core/nectarlink-ffi/uniffi.toml
new file mode 100644
index 0000000..849feb8
--- /dev/null
+++ b/core/nectarlink-ffi/uniffi.toml
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: MPL-2.0
+[bindings.kotlin]
+package_name = "app.nectarlink.core"
+cdylib_name = "nectarlink_ffi"
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index ffffa10..0ffcc7d 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -11,10 +11,7 @@ use cxx_qt::{CxxQtThread, CxxQtType, Threading};
use cxx_qt_lib::{
QHash, QHashPair_QString_QVariant, QList, QMap, QMapPair_QString_QVariant, QString, QVariant,
};
-use nectarlink_core::{
- ConnectionPath, DeviceId, Error, FeatureState, LinkState, PowerLevel,
- features::{Effort, Role, UnsupportedReason, Upgrade, UpgradeAction},
-};
+use nectarlink_core::{DeviceId, Error, FeatureState, LinkState, features::Upgrade};
use crate::{
core_host,
@@ -322,16 +319,10 @@ fn feature_state_map(state: Option<FeatureState>) -> QMap<QMapPair_QString_QVari
let mut put = |key: &str, value: QVariant| map.insert(QString::from(key), value);
let text = |s: &str| QVariant::from(&QString::from(s));
let upgrade_fields = |put: &mut dyn FnMut(&str, QVariant), upgrade: &Upgrade| {
- let (action, target) = describe_upgrade(upgrade.action);
+ let (action, target) = upgrade.action.describe();
put("action", text(action));
put("target", text(&target));
- put(
- "minutes",
- QVariant::from(&match upgrade.effort {
- Effort::Instant => 0i32,
- Effort::Minutes(m) => i32::from(m),
- }),
- );
+ put("minutes", QVariant::from(&i32::from(upgrade.effort.minutes())));
};
match state {
None => put("state", text("unknown")),
@@ -349,36 +340,8 @@ fn feature_state_map(state: Option<FeatureState>) -> QMap<QMapPair_QString_QVari
}
Some(FeatureState::Unsupported { reason }) => {
put("state", text("unsupported"));
- let reason = match reason {
- UnsupportedReason::DeviceKinds => "deviceKinds".to_owned(),
- UnsupportedReason::AndroidTooOld { needs } => format!("android:{needs}"),
- UnsupportedReason::WindowsTooOld { needs_build } => format!("windows:{needs_build}"),
- UnsupportedReason::NotOnThisDevice => "notOnThisDevice".to_owned(),
- };
- put("reason", text(&reason));
+ put("reason", text(&reason.describe()));
}
}
map
}
-
-/// An upgrade as `(action, target)` strings for QML.
-fn describe_upgrade(action: UpgradeAction) -> (&'static str, String) {
- match action {
- UpgradeAction::RaisePower(level) => (
- "raisePower",
- match level {
- PowerLevel::Assist => "assist",
- PowerLevel::Elevated => "elevated",
- _ => "basic",
- }
- .into(),
- ),
- UpgradeAction::GrantPermission(p) => ("grantPermission", p.as_str().into()),
- UpgradeAction::EnableAddon(addon) => ("enableAddon", addon.into()),
- UpgradeAction::EnablePath(ConnectionPath::Relay) => ("enablePath", "relay".into()),
- UpgradeAction::EnablePath(ConnectionPath::Lan) => ("enablePath", "lan".into()),
- UpgradeAction::EnableDeviceToggle(toggle) => ("enableToggle", toggle.into()),
- UpgradeAction::UpdateApp(Role::Phone) => ("updateApp", "phone".into()),
- UpgradeAction::UpdateApp(Role::Desktop) => ("updateApp", "desktop".into()),
- }
-}