Skip to content

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

Add the desktop app: pairing, home, settings and tray

Beed16a1063ac17
diff --git a/Cargo.lock b/Cargo.lock
index a3f05c1..d9cf27e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2147,6 +2147,28 @@ dependencies = [
"windows",
]
+[[package]]
+name = "nectarlink-desktop"
+version = "0.0.1"
+dependencies = [
+ "anyhow",
+ "cxx",
+ "cxx-qt",
+ "cxx-qt-build",
+ "cxx-qt-lib",
+ "dirs",
+ "hostname",
+ "nectarlink-core",
+ "qrcode",
+ "serde",
+ "serde_json",
+ "tempfile",
+ "tokio",
+ "tracing",
+ "tracing-subscriber",
+ "windows",
+]
+
[[package]]
name = "nectarlink-protocol"
version = "0.0.1"
@@ -4468,6 +4490,14 @@ dependencies = [
"xml-rs",
]
+[[package]]
+name = "xtask"
+version = "0.0.1"
+dependencies = [
+ "anyhow",
+ "serde_json",
+]
+
[[package]]
name = "yoke"
version = "0.8.3"
diff --git a/Cargo.toml b/Cargo.toml
index 5a53816..55b2762 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,6 +4,8 @@ members = [
"core/nectarlink-protocol",
"core/nectarlink-core",
"core/nectarlink-cli",
+ "desktop/app",
+ "tools/xtask",
"spikes/s1-qt-rust",
]
@@ -21,6 +23,10 @@ nectarlink-core = { path = "core/nectarlink-core", version = "0.0.1" }
anyhow = "1"
ciborium = "0.2"
clap = { version = "4.6", features = ["derive"] }
+cxx = "1"
+cxx-qt = "0.10"
+cxx-qt-build = "0.10"
+cxx-qt-lib = { version = "0.10", features = ["qt_gui", "qt_qml"] }
data-encoding = "2.11"
dirs = "7"
hostname = "0.4"
@@ -32,6 +38,7 @@ qrcode = { version = "0.14", default-features = false }
rand = "0.10"
rusqlite = { version = "0.40", features = ["bundled"] }
serde = { version = "1", features = ["derive"] }
+serde_json = "1"
serde_bytes = "0.11"
sha2 = "0.11"
tempfile = "3"
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
new file mode 100644
index 0000000..c6bcba9
--- /dev/null
+++ b/desktop/app/Cargo.toml
@@ -0,0 +1,55 @@
+[package]
+name = "nectarlink-desktop"
+description = "Nectarlink for Windows: the desktop app"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+authors.workspace = true
+repository.workspace = true
+license = "GPL-3.0-or-later"
+publish = false
+
+[[bin]]
+name = "nectarlink-desktop"
+path = "src/main.rs"
+
+[dependencies]
+anyhow.workspace = true
+cxx.workspace = true
+cxx-qt.workspace = true
+cxx-qt-lib.workspace = true
+dirs.workspace = true
+hostname.workspace = true
+nectarlink-core.workspace = true
+qrcode.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+tokio.workspace = true
+tracing.workspace = true
+tracing-subscriber.workspace = true
+
+[target.'cfg(windows)'.dependencies]
+windows = { workspace = true, features = [
+ "Win32_Foundation",
+ "Win32_Graphics_Dwm",
+ "Win32_Graphics_Gdi",
+ "Win32_System_LibraryLoader",
+ "Win32_Security",
+ "Win32_System_Power",
+ "Win32_System_Registry",
+ "Win32_System_Threading",
+ "Win32_UI_Shell",
+ "Win32_UI_WindowsAndMessaging",
+ "Win32_NetworkManagement_IpHelper",
+ "Win32_Networking_WinSock",
+ "Win32_Media_Audio",
+] }
+
+[build-dependencies]
+cxx-qt-build = { workspace = true, features = ["link_qt_object_files"] }
+
+[dev-dependencies]
+tempfile.workspace = true
+
+[lints]
+workspace = true
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
new file mode 100644
index 0000000..fffddef
--- /dev/null
+++ b/desktop/app/build.rs
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Builds the QML module `app.nectarlink` (QML files compiled ahead of time,
+//! Rust QObjects, C++ helpers) and links the Windows libraries C++ uses.
+
+use cxx_qt_build::{CxxQtBuilder, QmlFile, QmlModule};
+
+const QML: &[&str] = &[
+ "qml/App.qml",
+ "qml/MainWindow.qml",
+ "qml/components/Avatar.qml",
+ "qml/components/Button.qml",
+ "qml/components/CaptionButtons.qml",
+ "qml/components/Card.qml",
+ "qml/components/Chip.qml",
+ "qml/components/CodeDigits.qml",
+ "qml/components/Divider.qml",
+ "qml/components/Icon.qml",
+ "qml/components/IconButton.qml",
+ "qml/components/ListRow.qml",
+ "qml/components/LockChip.qml",
+ "qml/components/NavItem.qml",
+ "qml/components/QrCode.qml",
+ "qml/components/Segmented.qml",
+ "qml/components/Sheet.qml",
+ "qml/components/Spinner.qml",
+ "qml/components/StatusDot.qml",
+ "qml/components/Toast.qml",
+ "qml/components/Toggle.qml",
+ "qml/components/Txt.qml",
+ "qml/pages/HomePage.qml",
+ "qml/pages/PairingPanel.qml",
+ "qml/pages/SettingsPage.qml",
+ "qml/pages/WelcomePage.qml",
+];
+
+/// QML singletons.
+const QML_SINGLETONS: &[&str] = &["qml/Tokens.qml", "qml/Theme.qml", "qml/Icons.qml"];
+
+fn main() {
+ let module = QmlModule::new("app.nectarlink")
+ .qml_files(QML.iter().map(|f| QmlFile::from(*f)))
+ .qml_files(QML_SINGLETONS.iter().map(|f| QmlFile::from(*f).singleton(true)));
+ CxxQtBuilder::new_qml_module(module)
+ .qt_module("Quick")
+ .include_dir("cpp")
+ .cpp_files(["cpp/app_helpers.cpp", "cpp/native_window.h", "cpp/native_window.cpp"])
+ .files([
+ "src/bridge/native.rs",
+ "src/bridge/app.rs",
+ "src/bridge/devices.rs",
+ "src/bridge/pairing.rs",
+ "src/bridge/prefs.rs",
+ ])
+ .build();
+
+ // The C++ window code calls DWM and user32 directly.
+ println!("cargo:rustc-link-lib=dwmapi");
+ println!("cargo:rustc-link-lib=user32");
+}
diff --git a/desktop/app/cpp/app_helpers.cpp b/desktop/app/cpp/app_helpers.cpp
new file mode 100644
index 0000000..cff5bc3
--- /dev/null
+++ b/desktop/app/cpp/app_helpers.cpp
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "app_helpers.h"
+
+#include <QtCore/QtEnvironmentVariables>
+#include <QtGui/QGuiApplication>
+#include <QtGui/QIcon>
+#include <QtGui/QImage>
+#include <QtGui/QPixmap>
+#include <QtQuick/QQuickWindow>
+
+namespace {
+QIcon &appIcon()
+{
+ static QIcon icon;
+ return icon;
+}
+} // namespace
+
+void prepare_qt()
+{
+ // Windows get an alpha channel so the Mica backdrop can show through, and
+ // D3D swap chains are presented with DirectComposition, without which
+ // transparent pixels render white (see spikes/s1-qt-rust, lesson 7).
+ QQuickWindow::setDefaultAlphaBuffer(true);
+ qputenv("QT_QPA_DISABLE_REDIRECTION_SURFACE", "1");
+}
+
+void add_app_icon_image(int32_t size, rust::Slice<const uint8_t> rgba)
+{
+ if (size <= 0 || rgba.size() != static_cast<size_t>(size) * size * 4)
+ return;
+ // Copy: the image must not reference Rust memory after this call.
+ const QImage image =
+ QImage(rgba.data(), size, size, size * 4, QImage::Format_RGBA8888).copy();
+ appIcon().addPixmap(QPixmap::fromImage(image));
+}
+
+void apply_app_icon()
+{
+ QGuiApplication::setWindowIcon(appIcon());
+}
+
+void keep_running_without_windows()
+{
+ QGuiApplication::setQuitOnLastWindowClosed(false);
+}
diff --git a/desktop/app/cpp/app_helpers.h b/desktop/app/cpp/app_helpers.h
new file mode 100644
index 0000000..afef0cd
--- /dev/null
+++ b/desktop/app/cpp/app_helpers.h
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include <rust/cxx.h>
+
+#include <cstdint>
+
+// Qt setup that must happen before QGuiApplication is created.
+void prepare_qt();
+
+// Adds one size of the app icon (straight-alpha RGBA, size x size).
+void add_app_icon_image(int32_t size, rust::Slice<const uint8_t> rgba);
+// Sets the icon built from the added images on all windows.
+void apply_app_icon();
+
+// Keeps the app running with no windows open (it lives in the tray).
+void keep_running_without_windows();
diff --git a/desktop/app/cpp/native_window.cpp b/desktop/app/cpp/native_window.cpp
new file mode 100644
index 0000000..36ebabb
--- /dev/null
+++ b/desktop/app/cpp/native_window.cpp
@@ -0,0 +1,247 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "native_window.h"
+
+#include <QtGui/QPlatformSurfaceEvent>
+
+#include <algorithm>
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <dwmapi.h>
+#include <windowsx.h>
+
+namespace {
+
+// Values from the Windows 11 SDK, defined here so older SDK headers work.
+constexpr DWORD kUseImmersiveDarkMode = 20; // DWMWA_USE_IMMERSIVE_DARK_MODE
+constexpr DWORD kCaptionColor = 35; // DWMWA_CAPTION_COLOR
+constexpr DWORD kSystemBackdropType = 38; // DWMWA_SYSTEMBACKDROP_TYPE
+constexpr int kBackdropNone = 1; // DWMSBT_NONE
+constexpr int kBackdropMica = 2; // DWMSBT_MAINWINDOW
+constexpr COLORREF kColorNone = 0xFFFFFFFE; // DWMWA_COLOR_NONE
+
+HWND hwndOf(const QWindow *window)
+{
+ return reinterpret_cast<HWND>(window->winId());
+}
+
+} // namespace
+
+NativeWindow::NativeWindow(QWindow *parent)
+ : QQuickWindow(parent)
+{
+ // Qt removes the system title bar and lets content fill the window.
+ setFlags(flags() | Qt::ExpandedClientAreaHint);
+ setColor(Qt::transparent);
+}
+
+void NativeWindow::setBackdrop(bool on)
+{
+ if (m_backdrop == on)
+ return;
+ m_backdrop = on;
+ applyFrame();
+ emit backdropChanged();
+}
+
+void NativeWindow::setDarkFrame(bool dark)
+{
+ if (m_darkFrame == dark)
+ return;
+ m_darkFrame = dark;
+ applyFrame();
+ emit darkFrameChanged();
+}
+
+void NativeWindow::setCaptionHeight(qreal height)
+{
+ if (qFuzzyCompare(m_captionHeight, height))
+ return;
+ m_captionHeight = height;
+ emit captionHeightChanged();
+}
+
+void NativeWindow::setMaximizeButton(QQuickItem *item)
+{
+ if (m_maximizeButton == item)
+ return;
+ m_maximizeButton = item;
+ emit maximizeButtonChanged();
+}
+
+void NativeWindow::setMaximizeState(bool hovered, bool pressed)
+{
+ if (m_maximizeHovered == hovered && m_maximizePressed == pressed)
+ return;
+ m_maximizeHovered = hovered;
+ m_maximizePressed = pressed;
+ emit maximizeStateChanged();
+}
+
+void NativeWindow::addCaptionHole(QQuickItem *item)
+{
+ if (item && std::none_of(m_holes.begin(), m_holes.end(), [item](const auto &h) { return h == item; }))
+ m_holes.emplace_back(item);
+}
+
+void NativeWindow::removeCaptionHole(QQuickItem *item)
+{
+ m_holes.erase(std::remove_if(m_holes.begin(), m_holes.end(),
+ [item](const auto &h) { return h.isNull() || h == item; }),
+ m_holes.end());
+}
+
+void NativeWindow::toggleMaximized()
+{
+ if (visibility() == QWindow::Maximized)
+ showNormal();
+ else
+ showMaximized();
+}
+
+void NativeWindow::bringToFront()
+{
+ if (visibility() == QWindow::Minimized || !isVisible())
+ showNormal();
+ raise();
+ requestActivate();
+ if (handle())
+ SetForegroundWindow(hwndOf(this));
+}
+
+void NativeWindow::flash()
+{
+ if (!handle())
+ return;
+ FLASHWINFO info { sizeof(FLASHWINFO), hwndOf(this), FLASHW_TRAY | FLASHW_TIMERNOFG, 0, 0 };
+ FlashWindowEx(&info);
+}
+
+bool NativeWindow::event(QEvent *event)
+{
+ if (event->type() == QEvent::PlatformSurface
+ && static_cast<QPlatformSurfaceEvent *>(event)->surfaceEventType()
+ == QPlatformSurfaceEvent::SurfaceCreated) {
+ const bool handled = QQuickWindow::event(event);
+ applyFrame();
+ return handled;
+ }
+ return QQuickWindow::event(event);
+}
+
+void NativeWindow::applyFrame()
+{
+ if (!handle())
+ return;
+ const HWND hwnd = hwndOf(this);
+ // No frame extension: Mica still shows behind transparent pixels (the
+ // swap chain is composited with DirectComposition), and DWM doesn't draw
+ // its own caption buttons over the app's.
+ const MARGINS margins { 0, 0, 0, 0 };
+ DwmExtendFrameIntoClientArea(hwnd, &margins);
+ const BOOL dark = m_darkFrame;
+ DwmSetWindowAttribute(hwnd, kUseImmersiveDarkMode, &dark, sizeof(dark));
+ const int backdrop = m_backdrop ? kBackdropMica : kBackdropNone;
+ DwmSetWindowAttribute(hwnd, kSystemBackdropType, &backdrop, sizeof(backdrop));
+ const COLORREF none = kColorNone;
+ DwmSetWindowAttribute(hwnd, kCaptionColor, &none, sizeof(none));
+}
+
+bool NativeWindow::itemContains(const QQuickItem *item, const QPointF &scenePoint) const
+{
+ if (!item || !item->isVisible())
+ return false;
+ return item->mapRectToScene(QRectF(0, 0, item->width(), item->height())).contains(scenePoint);
+}
+
+long NativeWindow::hitTest(int screenX, int screenY) const
+{
+ const HWND hwnd = hwndOf(this);
+ POINT pt { screenX, screenY };
+ ScreenToClient(hwnd, &pt);
+
+ // The system title bar is gone, and with it the top resize border.
+ if (!IsZoomed(hwnd)) {
+ const UINT dpi = GetDpiForWindow(hwnd);
+ const int border = GetSystemMetricsForDpi(SM_CYSIZEFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
+ if (pt.y < border) {
+ RECT client {};
+ GetClientRect(hwnd, &client);
+ if (pt.x < border * 2)
+ return HTTOPLEFT;
+ if (pt.x >= client.right - border * 2)
+ return HTTOPRIGHT;
+ return HTTOP;
+ }
+ }
+
+ const qreal dpr = devicePixelRatio();
+ const QPointF point(pt.x / dpr, pt.y / dpr);
+ if (itemContains(m_maximizeButton, point))
+ return HTMAXBUTTON;
+ if (point.y() >= m_captionHeight)
+ return HTCLIENT;
+ for (const auto &hole : m_holes) {
+ if (itemContains(hole, point))
+ return HTCLIENT;
+ }
+ return HTCAPTION;
+}
+
+bool NativeWindow::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
+{
+ if (eventType != "windows_generic_MSG")
+ return QQuickWindow::nativeEvent(eventType, message, result);
+ const MSG *msg = static_cast<const MSG *>(message);
+
+ switch (msg->message) {
+ case WM_NCHITTEST: {
+ const long hit = hitTest(GET_X_LPARAM(msg->lParam), GET_Y_LPARAM(msg->lParam));
+ if (hit != HTCLIENT) {
+ *result = hit;
+ return true;
+ }
+ break;
+ }
+ // The maximize button reports HTMAXBUTTON, so its input arrives as
+ // non-client messages. Handle them here and keep DefWindowProc from
+ // drawing and tracking a classic button.
+ case WM_NCMOUSEMOVE:
+ if (msg->wParam == HTMAXBUTTON) {
+ if (!m_maximizeHovered) {
+ TRACKMOUSEEVENT track { sizeof(track), TME_LEAVE | TME_NONCLIENT, msg->hwnd, 0 };
+ TrackMouseEvent(&track);
+ }
+ setMaximizeState(true, m_maximizePressed);
+ *result = 0;
+ return true;
+ }
+ setMaximizeState(false, false);
+ break;
+ case WM_NCMOUSELEAVE:
+ case WM_MOUSEMOVE:
+ setMaximizeState(false, false);
+ break;
+ case WM_NCLBUTTONDOWN:
+ case WM_NCLBUTTONDBLCLK:
+ if (msg->wParam == HTMAXBUTTON) {
+ setMaximizeState(true, true);
+ *result = 0;
+ return true;
+ }
+ break;
+ case WM_NCLBUTTONUP:
+ if (msg->wParam == HTMAXBUTTON) {
+ const bool wasPressed = m_maximizePressed;
+ setMaximizeState(true, false);
+ if (wasPressed)
+ toggleMaximized();
+ *result = 0;
+ return true;
+ }
+ break;
+ default:
+ break;
+ }
+ return QQuickWindow::nativeEvent(eventType, message, result);
+}
diff --git a/desktop/app/cpp/native_window.h b/desktop/app/cpp/native_window.h
new file mode 100644
index 0000000..c9d1bc9
--- /dev/null
+++ b/desktop/app/cpp/native_window.h
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include <QtCore/QPointer>
+#include <QtQml/qqmlregistration.h>
+#include <QtQuick/QQuickItem>
+#include <QtQuick/QQuickWindow>
+
+#include <vector>
+
+// A top-level window drawn edge to edge: the app draws its own title bar and
+// caption buttons, while Windows keeps the native behaviors (dragging,
+// double-click to maximize, Aero Snap, the system menu, and the Snap Layouts
+// flyout on the maximize button). Optionally shows the Windows 11 Mica
+// backdrop behind transparent content.
+class NativeWindow : public QQuickWindow
+{
+ Q_OBJECT
+ QML_ELEMENT
+
+ // Show Mica behind transparent areas.
+ Q_PROPERTY(bool backdrop READ backdrop WRITE setBackdrop NOTIFY backdropChanged)
+ // Dark backdrop tint and window border.
+ Q_PROPERTY(bool darkFrame READ darkFrame WRITE setDarkFrame NOTIFY darkFrameChanged)
+ // Height of the draggable title strip, in logical pixels.
+ Q_PROPERTY(qreal captionHeight READ captionHeight WRITE setCaptionHeight NOTIFY captionHeightChanged)
+ // The app's maximize button. Windows treats it as the system maximize
+ // button (Snap Layouts), so its mouse input arrives here, not in QML:
+ // QML styles it from `maximizeHovered` and `maximizePressed`.
+ Q_PROPERTY(QQuickItem *maximizeButton READ maximizeButton WRITE setMaximizeButton NOTIFY maximizeButtonChanged)
+ Q_PROPERTY(bool maximizeHovered READ maximizeHovered NOTIFY maximizeStateChanged)
+ Q_PROPERTY(bool maximizePressed READ maximizePressed NOTIFY maximizeStateChanged)
+
+public:
+ explicit NativeWindow(QWindow *parent = nullptr);
+
+ bool backdrop() const { return m_backdrop; }
+ void setBackdrop(bool on);
+ bool darkFrame() const { return m_darkFrame; }
+ void setDarkFrame(bool dark);
+ qreal captionHeight() const { return m_captionHeight; }
+ void setCaptionHeight(qreal height);
+ QQuickItem *maximizeButton() const { return m_maximizeButton; }
+ void setMaximizeButton(QQuickItem *item);
+ bool maximizeHovered() const { return m_maximizeHovered; }
+ bool maximizePressed() const { return m_maximizePressed; }
+
+ // Interactive items inside the title strip (buttons, search fields):
+ // clicks there go to the item instead of dragging the window.
+ Q_INVOKABLE void addCaptionHole(QQuickItem *item);
+ Q_INVOKABLE void removeCaptionHole(QQuickItem *item);
+
+ Q_INVOKABLE void toggleMaximized();
+ // Shows, restores and focuses the window, even when another app is in
+ // front (the caller must have the right to take the foreground).
+ Q_INVOKABLE void bringToFront();
+ // Flashes the taskbar button until the window is activated.
+ Q_INVOKABLE void flash();
+
+signals:
+ void backdropChanged();
+ void darkFrameChanged();
+ void captionHeightChanged();
+ void maximizeButtonChanged();
+ void maximizeStateChanged();
+
+protected:
+ bool event(QEvent *event) override;
+ bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override;
+
+private:
+ void applyFrame();
+ long hitTest(int screenX, int screenY) const;
+ bool itemContains(const QQuickItem *item, const QPointF &scenePoint) const;
+ void setMaximizeState(bool hovered, bool pressed);
+
+ bool m_backdrop = true;
+ bool m_darkFrame = false;
+ qreal m_captionHeight = 48;
+ QPointer<QQuickItem> m_maximizeButton;
+ bool m_maximizeHovered = false;
+ bool m_maximizePressed = false;
+ std::vector<QPointer<QQuickItem>> m_holes;
+};
diff --git a/desktop/app/qml/App.qml b/desktop/app/qml/App.qml
new file mode 100644
index 0000000..bced4ad
--- /dev/null
+++ b/desktop/app/qml/App.qml
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// Application root. The main window exists only while it's open: closing it
+// destroys it (freeing its GPU resources) and Nectarlink keeps running in
+// the tray. A tray click, a second launch or a ringing request reopens it.
+QtObject {
+ id: app
+
+ property MainWindow mainWindow: null
+ readonly property Component mainComponent: Component { MainWindow {} }
+ readonly property bool startMinimized: Qt.application.arguments.indexOf("--minimized") >= 0
+
+ function showMain() {
+ if (!mainWindow) {
+ mainWindow = mainComponent.createObject(null)
+ mainWindow.closeRequested.connect(app.onMainClosed)
+ }
+ mainWindow.bringToFront()
+ }
+
+ function onMainClosed() {
+ if (!Preferences.closeToTray) {
+ Qt.quit()
+ return
+ }
+ // Destroy after the close event has finished.
+ const window = mainWindow
+ mainWindow = null
+ Qt.callLater(() => window.destroy())
+ }
+
+ Component.onCompleted: if (!startMinimized) showMain()
+
+ // Qt follows the system color scheme unless told otherwise; the window
+ // frame and Mica tint must follow the app's theme instead.
+ readonly property Binding colorScheme: Binding {
+ target: Qt.styleHints
+ property: "colorScheme"
+ value: Theme.dark ? Qt.ColorScheme.Dark : Qt.ColorScheme.Light
+ }
+
+ readonly property Connections controller: Connections {
+ target: AppController
+ function onActivateRequested() { app.showMain() }
+ function onQuitRequested() { Qt.quit() }
+ function onRingingFromChanged() {
+ if (AppController.ringingFrom.length > 0) {
+ app.showMain()
+ app.mainWindow.flash()
+ }
+ }
+ }
+}
diff --git a/desktop/app/qml/Icons.qml b/desktop/app/qml/Icons.qml
new file mode 100644
index 0000000..d062619
--- /dev/null
+++ b/desktop/app/qml/Icons.qml
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+pragma Singleton
+import QtQuick
+
+// Stroke icons as SVG paths on a 24×24 grid (round caps and joins), drawn
+// by Icon. Same shapes as the design mockups.
+QtObject {
+ readonly property string home: "M3 11l9-7 9 7M5 10v10h14V10"
+ readonly property string messages: "M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z"
+ readonly property string bell: "M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8M10 20a2 2 0 0 0 4 0"
+ readonly property string photo: "M6 3h12a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3zM21 15l-5-5L5 21"
+ readonly property string apps: "M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z"
+ readonly property string deck: "M6 5h12a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3zM8 14h8"
+ readonly property string settings: "M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6zM12 2v3M12 19v3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M2 12h3M19 12h3M4.9 19.1L7 17M17 7l2.1-2.1"
+ readonly property string clipboard: "M9 3h6v4H9zM16 5h2a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2"
+ readonly property string mirror: "M4 4h10a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zM18.5 8h2a1.5 1.5 0 0 1 1.5 1.5v7a1.5 1.5 0 0 1-1.5 1.5h-2A1.5 1.5 0 0 1 17 16.5v-7A1.5 1.5 0 0 1 18.5 8zM6 18h6"
+ readonly property string send: "M22 2L11 13M22 2l-7 20-4-9-9-4z"
+ readonly property string ring: "M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8M10 20a2 2 0 0 0 4 0M2 8c0-2 1-4 2-5M22 8c0-2-1-4-2-5"
+ readonly property string mic: "M12 2a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0V5a3 3 0 0 1 3-3zM5 11a7 7 0 0 0 14 0M12 18v4"
+ readonly property string lock: "M7 11h10a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2zM8 11V8a4 4 0 0 1 8 0v3"
+ readonly property string mark: "M12 2.5l8.2 4.75v9.5L12 21.5l-8.2-4.75v-9.5zM9 12h6"
+ readonly property string back: "M15 6l-6 6 6 6"
+ readonly property string chevronRight: "M9 6l6 6-6 6"
+ readonly property string battery: "M4 7h14a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2zM22 11v2"
+ readonly property string phone: "M8 2h8a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2zM11 18h2"
+ readonly property string laptop: "M5 5h14a1 1 0 0 1 1 1v10H4V6a1 1 0 0 1 1-1zM2 19h20"
+ readonly property string desktop: "M4 4h16a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zM9 21h6M12 17v4"
+ readonly property string wifi: "M2 9a15 15 0 0 1 20 0M5 12.5a10 10 0 0 1 14 0M8.5 16a5 5 0 0 1 7 0M12 19.5h.01"
+ readonly property string plus: "M12 5v14M5 12h14"
+ readonly property string close: "M6 6l12 12M18 6L6 18"
+ readonly property string check: "M5 12.5l4.5 4.5L19 7.5"
+ readonly property string refresh: "M20 11a8 8 0 1 0-2.3 5.7M20 4v7h-7"
+ readonly property string unlink: "M9 15l-2 2a3 3 0 0 1-4.2-4.2l3-3a3 3 0 0 1 4.2 0M15 9l2-2a3 3 0 0 1 4.2 4.2l-3 3a3 3 0 0 1-4.2 0M3 3l18 18"
+ readonly property string copy: "M9 9h10a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-8a2 2 0 0 1-2-2V9zM5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"
+ readonly property string warning: "M12 3l10 18H2zM12 10v4M12 17.5h.01"
+ readonly property string info: "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zM12 11v6M12 7.5h.01"
+ readonly property string palette: "M12 3a9 9 0 1 0 0 18c1 0 1.5-.8 1.5-1.6 0-.6-.4-1-.4-1.6 0-.9.7-1.6 1.6-1.6H17a4 4 0 0 0 4-4c0-5-4-9.2-9-9.2zM7.5 11.5h.01M10 7.5h.01M15 7.5h.01"
+ readonly property string power: "M12 2v10M5.6 5.6a9 9 0 1 0 12.8 0"
+ readonly property string folder: "M3 6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"
+ readonly property string sparkle: "M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z"
+}
diff --git a/desktop/app/qml/MainWindow.qml b/desktop/app/qml/MainWindow.qml
new file mode 100644
index 0000000..2f9067b
--- /dev/null
+++ b/desktop/app/qml/MainWindow.qml
@@ -0,0 +1,193 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// The main window: navigation rail, title bar and pages. Before any device
+// is paired it shows the welcome (pairing) screen instead.
+NativeWindow {
+ id: window
+ signal closeRequested
+
+ readonly property bool welcome: AppController.status === "ready" && !AppController.hasDevices
+ property string page: "home"
+
+ width: 1100
+ height: 720
+ minimumWidth: Theme.layout.minWindow[0]
+ minimumHeight: Theme.layout.minWindow[1]
+ title: "Nectarlink"
+ backdrop: Preferences.backdrop
+ darkFrame: Theme.dark
+ captionHeight: Theme.topBarHeight
+
+ // QQuickWindow's `closing` is a revisioned member, hidden on subclasses
+ // in a 1.0 module; Connections reaches it through the meta-object.
+ Connections {
+ target: window
+ function onClosing(close) {
+ close.accepted = true
+ window.closeRequested()
+ }
+ }
+
+ function openPairing() { pairingSheet.open() }
+
+ // Window background: translucent over Mica, opaque otherwise.
+ Rectangle {
+ anchors.fill: parent
+ color: Preferences.backdrop ? Qt.rgba(Theme.surface.r, Theme.surface.g, Theme.surface.b, Theme.dark ? 0.7 : 0.62)
+ : Theme.surface
+ Behavior on color { ColorAnimation { duration: Theme.fadeNormal } }
+ }
+
+ // ---- Navigation rail ----
+ Rectangle {
+ id: rail
+ visible: !window.welcome
+ width: Theme.railWidth
+ height: parent.height
+ color: Preferences.backdrop ? "transparent" : Theme.railColor
+
+ Rectangle {
+ id: mark
+ anchors.horizontalCenter: parent.horizontalCenter
+ y: 16
+ width: 38; height: 38
+ radius: Theme.radiusSm
+ color: Theme.graphite ? Theme.surfaceContent : Theme.primary
+ Icon {
+ anchors.centerIn: parent
+ path: Icons.mark
+ color: Theme.graphite ? Theme.surface : Theme.primaryContent
+ }
+ }
+ Column {
+ anchors.horizontalCenter: parent.horizontalCenter
+ anchors.top: mark.bottom
+ anchors.topMargin: 22
+ spacing: 6
+ NavItem {
+ iconPath: Icons.home
+ text: qsTr("Home")
+ selected: window.page === "home"
+ onClicked: window.page = "home"
+ }
+ NavItem {
+ iconPath: Icons.settings
+ text: qsTr("Settings")
+ selected: window.page === "settings"
+ onClicked: window.page = "settings"
+ }
+ }
+ IconButton {
+ anchors.horizontalCenter: parent.horizontalCenter
+ anchors.bottom: parent.bottom
+ anchors.bottomMargin: 18
+ iconPath: Icons.plus
+ label: qsTr("Pair a new device")
+ tonal: true
+ onClicked: window.openPairing()
+ }
+ Divider { anchors.right: parent.right; width: 1; height: parent.height }
+ }
+
+ // ---- Title bar and pages ----
+ Item {
+ id: main
+ visible: !window.welcome
+ anchors.left: rail.right
+ anchors.right: parent.right
+ height: parent.height
+
+ Item {
+ id: topBar
+ width: parent.width - captionButtons.width
+ height: Theme.topBarHeight
+ Txt {
+ id: pageTitle
+ anchors.left: parent.left
+ anchors.leftMargin: Theme.contentPadding
+ anchors.verticalCenter: parent.verticalCenter
+ text: window.page === "home" ? qsTr("Home") : qsTr("Settings")
+ role: "headline"
+ size: 20
+ }
+ }
+ Divider { anchors.top: topBar.bottom; width: parent.width }
+
+ Item {
+ id: pages
+ anchors.top: topBar.bottom
+ anchors.bottom: parent.bottom
+ width: parent.width
+ clip: true
+
+ HomePage {
+ anchors.fill: parent
+ active: window.page === "home"
+ onPairRequested: window.openPairing()
+ }
+ SettingsPage {
+ anchors.fill: parent
+ active: window.page === "settings"
+ onPairRequested: window.openPairing()
+ }
+ }
+ }
+
+ // ---- First run ----
+ WelcomePage {
+ anchors.fill: parent
+ visible: window.welcome || AppController.status !== "ready"
+ }
+
+ // ---- Overlays ----
+ Sheet {
+ id: pairingSheet
+ cardWidth: 480
+ onOpenedChanged: if (!opened) Pairing.cancel()
+ PairingPanel {
+ width: parent.width
+ running: pairingSheet.opened
+ onFinished: pairingSheet.close()
+ onCancelled: pairingSheet.close()
+ }
+ }
+
+ Sheet {
+ id: ringingSheet
+ opened: AppController.ringingFrom.length > 0
+ dismissable: false
+ cardWidth: 380
+ Column {
+ width: parent.width
+ spacing: 16
+ Avatar { anchors.horizontalCenter: parent.horizontalCenter; width: 56; height: 56; iconPath: Icons.ring; emphasized: true }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ text: qsTr("%1 is ringing this PC").arg(AppController.ringingFrom)
+ role: "headline"
+ wrapMode: Text.WordWrap
+ }
+ Button {
+ anchors.horizontalCenter: parent.horizontalCenter
+ text: qsTr("Stop ringing")
+ onClicked: AppController.stopRinging()
+ }
+ }
+ }
+
+ CaptionButtons {
+ id: captionButtons
+ window: window
+ anchors.top: parent.top
+ anchors.right: parent.right
+ }
+
+ Toast { id: toast }
+ Connections {
+ target: AppController
+ function onToast(message) { toast.show(message) }
+ }
+}
diff --git a/desktop/app/qml/Theme.qml b/desktop/app/qml/Theme.qml
new file mode 100644
index 0000000..fd5dd95
--- /dev/null
+++ b/desktop/app/qml/Theme.qml
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+pragma Singleton
+import QtQuick
+import app.nectarlink
+
+// The active theme: Bloom (Material You, seed presets) or Graphite (paper and
+// slate), light or dark, resolved from Preferences and the system. Colors
+// come from Tokens (generated from docs/design/tokens.json); Material's
+// "onX" roles are named "xContent" because QML reserves the "on" prefix.
+QtObject {
+ id: theme
+
+ readonly property bool graphite: Preferences.theme === "graphite"
+ readonly property bool dark: Preferences.colorMode === "dark"
+ || (Preferences.colorMode === "system" && AppController.systemDark)
+ readonly property bool reduceMotion: AppController.reduceMotion
+
+ readonly property var bloomSeeds: Tokens.data.themes.bloom.seeds
+ readonly property string seed: bloomSeeds[Preferences.seed] ? Preferences.seed : Tokens.data.themes.bloom.defaultSeed
+ readonly property var palette: graphite
+ ? Tokens.data.themes.graphite.variants[dark ? "slate" : "paper"]
+ : bloomSeeds[seed][dark ? "dark" : "light"]
+ readonly property var status: graphite ? palette : Tokens.data.themes.bloom.status[dark ? "dark" : "light"]
+
+ // ---- Color roles ----
+ readonly property color primary: palette.primary
+ readonly property color primaryContent: palette.onPrimary
+ readonly property color primaryContainer: palette.primaryContainer
+ readonly property color primaryContainerContent: palette.onPrimaryContainer
+ readonly property color secondaryContainer: palette.secondaryContainer
+ readonly property color secondaryContainerContent: palette.onSecondaryContainer
+ readonly property color surface: palette.surface
+ readonly property color surfaceLow: palette.surfaceContainerLow
+ readonly property color surfaceContainer: palette.surfaceContainer
+ readonly property color surfaceContainerHigh: palette.surfaceContainerHigh
+ readonly property color surfaceContainerHighest: palette.surfaceContainerHighest
+ readonly property color surfaceContent: palette.onSurface
+ readonly property color surfaceContentVariant: palette.onSurfaceVariant
+ readonly property color outline: palette.outline
+ readonly property color outlineVariant: palette.outlineVariant
+ // Success never gets its own (green) color: it uses the theme's ink.
+ readonly property color success: primary
+ readonly property color warning: status.warning
+ readonly property color error: status.error
+ readonly property color errorContent: status.onError
+
+ // ---- Component colors (docs/design/assets/nl.css) ----
+ readonly property color cardColor: graphite ? "transparent" : surfaceContainer
+ readonly property color cardBorder: graphite ? outlineVariant : "transparent"
+ readonly property color tileColor: graphite ? "transparent" : surfaceContainerHigh
+ readonly property color heroColor: graphite ? "transparent"
+ : Qt.tint(surface, Qt.rgba(primaryContainer.r, primaryContainer.g, primaryContainer.b, 0.62))
+ readonly property color heroContent: graphite ? surfaceContent : primaryContainerContent
+ readonly property color railColor: graphite ? "transparent" : surfaceLow
+ readonly property color indicator: graphite ? surfaceContent : secondaryContainer
+ readonly property color indicatorContent: graphite ? surface : secondaryContainerContent
+ readonly property color buttonShadow: graphite ? palette.buttonShadow : "transparent"
+ readonly property color scrim: Qt.rgba(0, 0, 0, dark ? 0.5 : 0.32)
+
+ // ---- Shape ----
+ readonly property var shape: graphite ? Tokens.data.themes.graphite.shape : Tokens.data.themes.bloom.shape
+ readonly property int radiusXs: shape.xs
+ readonly property int radiusSm: shape.sm
+ readonly property int radiusMd: shape.md
+ readonly property int radiusLg: shape.lg
+ readonly property int radiusXl: shape.xl
+ // "Pill": half the height of whatever uses it, in Bloom.
+ function pill(height) { return graphite ? shape.full : height / 2 }
+
+ // ---- Type ----
+ // Bundled fonts (Figtree, Instrument Serif, Space Mono, Caveat) replace
+ // these system fallbacks once added to the build.
+ readonly property string fontUi: "Segoe UI Variable Text"
+ readonly property string fontDisplay: graphite ? "Georgia" : "Segoe UI Variable Display"
+ readonly property string fontMono: "Cascadia Mono"
+ readonly property var typography: Tokens.data.typography
+ readonly property var labelStyle: graphite ? Tokens.data.themes.graphite.label : Tokens.data.themes.bloom.label
+
+ // ---- Layout and spacing ----
+ readonly property var layout: Tokens.data.layout.desktop
+ readonly property int railWidth: layout.railWidth
+ readonly property int topBarHeight: layout.topBarHeight
+ readonly property int contentPadding: layout.contentPadding
+ readonly property int gutter: layout.gutter
+ function space(step) { return Tokens.data.spacing.scale[step] }
+
+ // ---- Motion ----
+ // QML springs take a strength and a damping ratio; these are tuned to
+ // match the token springs (gentle / standard / snappy).
+ readonly property real springGentle: 2.4
+ readonly property real dampingGentle: 0.36
+ readonly property real springStandard: 3.6
+ readonly property real dampingStandard: 0.32
+ readonly property real springSnappy: 5.6
+ readonly property real dampingSnappy: 0.34
+ readonly property int fadeFast: Tokens.data.motion.fade.fast
+ readonly property int fadeNormal: Tokens.data.motion.fade.normal
+ readonly property real hoverLift: reduceMotion ? 0 : Tokens.data.motion.hoverLift
+ readonly property real pressScale: reduceMotion ? 1 : Tokens.data.motion.pressScale
+}
diff --git a/desktop/app/qml/Tokens.qml b/desktop/app/qml/Tokens.qml
new file mode 100644
index 0000000..bed9106
--- /dev/null
+++ b/desktop/app/qml/Tokens.qml
@@ -0,0 +1,419 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Generated from docs/design/tokens.json by `cargo xtask tokens`. Do not edit.
+pragma Singleton
+import QtQuick
+
+QtObject {
+ readonly property var data: ({
+ "elevation": {
+ "bloom": {
+ "level0": "none",
+ "level1": "0 1px 2px rgba(0,0,0,.06)",
+ "window": "0 1px 2px rgba(0,0,0,.06), 0 24px 60px -20px rgba(0,0,0,.18)"
+ },
+ "graphite": {
+ "level0": "none",
+ "level1": "none",
+ "window": "0 30px 70px -30px rgba(0,0,0,.35)"
+ }
+ },
+ "icons": {
+ "set": "Material Symbols Rounded (Apache-2.0)",
+ "size": 20,
+ "stroke": "outlined, 400 weight; filled when selected"
+ },
+ "layout": {
+ "desktop": {
+ "contentPadding": 22,
+ "gutter": 16,
+ "minWindow": [
+ 880,
+ 600
+ ],
+ "railWidth": 80,
+ "topBarHeight": 52
+ },
+ "phone": {
+ "gutter": 10,
+ "screenPadding": 16,
+ "tabBarHeight": 64
+ }
+ },
+ "motion": {
+ "description": "Springs everywhere; durations are only for fades. Respect reduced-motion: replace movement with 120 ms fades.",
+ "fade": {
+ "fast": 120,
+ "normal": 200
+ },
+ "hoverLift": 2,
+ "pressScale": 0.97,
+ "spring": {
+ "gentle": {
+ "damping": 26,
+ "stiffness": 220,
+ "use": "page and panel transitions"
+ },
+ "snappy": {
+ "damping": 34,
+ "stiffness": 620,
+ "use": "toggles, chips, buttons, hover lift"
+ },
+ "standard": {
+ "damping": 30,
+ "stiffness": 380,
+ "use": "cards, sheets, expanding a notification into a conversation"
+ }
+ }
+ },
+ "spacing": {
+ "scale": [
+ 0,
+ 2,
+ 4,
+ 6,
+ 8,
+ 10,
+ 12,
+ 16,
+ 20,
+ 24,
+ 32,
+ 40,
+ 48,
+ 64
+ ],
+ "unit": 4
+ },
+ "themes": {
+ "bloom": {
+ "defaultSeed": "honey",
+ "description": "Default. Minimal Material You: neutral surfaces, color only where it carries meaning.",
+ "dynamicColor": true,
+ "fonts": {
+ "display": "Figtree",
+ "label": "Figtree",
+ "mono": "Space Mono",
+ "ui": "Figtree"
+ },
+ "label": {
+ "case": "none",
+ "size": 12.5,
+ "tracking": 0,
+ "weight": 600
+ },
+ "seeds": {
+ "honey": {
+ "dark": {
+ "onPrimary": "#4A2800",
+ "onPrimaryContainer": "#FFDDB8",
+ "onSecondaryContainer": "#F3E0CB",
+ "onSurface": "#EBE1D9",
+ "onSurfaceVariant": "#D5C3B5",
+ "outline": "#9E8E81",
+ "outlineVariant": "#51453A",
+ "primary": "#FFB95F",
+ "primaryContainer": "#693C00",
+ "secondaryContainer": "#574330",
+ "surface": "#17130E",
+ "surfaceContainer": "#241F1A",
+ "surfaceContainerHigh": "#2E2924",
+ "surfaceContainerHighest": "#39342E",
+ "surfaceContainerLow": "#120E0A"
+ },
+ "light": {
+ "onPrimary": "#FFFFFF",
+ "onPrimaryContainer": "#2C1600",
+ "onSecondaryContainer": "#261A0C",
+ "onSurface": "#1F1B16",
+ "onSurfaceVariant": "#51453A",
+ "outline": "#837468",
+ "outlineVariant": "#D5C3B5",
+ "primary": "#8A5100",
+ "primaryContainer": "#FFDDB8",
+ "secondaryContainer": "#F3E0CB",
+ "surface": "#FFF8F3",
+ "surfaceContainer": "#F5ECE4",
+ "surfaceContainerHigh": "#EFE6DE",
+ "surfaceContainerHighest": "#E9E1D9",
+ "surfaceContainerLow": "#FBF2EB"
+ },
+ "seed": "#B7791F"
+ },
+ "lavender": {
+ "dark": {
+ "onPrimary": "#36275D",
+ "onPrimaryContainer": "#E9DDFF",
+ "onSecondaryContainer": "#E8DEF8",
+ "onSurface": "#E6E0E9",
+ "onSurfaceVariant": "#CAC4CF",
+ "outline": "#948F99",
+ "outlineVariant": "#49454E",
+ "primary": "#CFBDFE",
+ "primaryContainer": "#4D3D75",
+ "secondaryContainer": "#4A4458",
+ "surface": "#141218",
+ "surfaceContainer": "#211F24",
+ "surfaceContainerHigh": "#2B292F",
+ "surfaceContainerHighest": "#36343A",
+ "surfaceContainerLow": "#0F0D13"
+ },
+ "light": {
+ "onPrimary": "#FFFFFF",
+ "onPrimaryContainer": "#201047",
+ "onSecondaryContainer": "#1D192B",
+ "onSurface": "#1D1B20",
+ "onSurfaceVariant": "#49454E",
+ "outline": "#7A757F",
+ "outlineVariant": "#CAC4CF",
+ "primary": "#65558F",
+ "primaryContainer": "#E9DDFF",
+ "secondaryContainer": "#E8DEF8",
+ "surface": "#FDF7FF",
+ "surfaceContainer": "#F2ECF4",
+ "surfaceContainerHigh": "#ECE6EE",
+ "surfaceContainerHighest": "#E6E0E9",
+ "surfaceContainerLow": "#F7F2FA"
+ },
+ "seed": "#7E6AA8"
+ },
+ "ocean": {
+ "dark": {
+ "onPrimary": "#003354",
+ "onPrimaryContainer": "#CEE5FF",
+ "onSecondaryContainer": "#D5E4F7",
+ "onSurface": "#E0E2E8",
+ "onSurfaceVariant": "#C2C7CF",
+ "outline": "#8C9199",
+ "outlineVariant": "#42474E",
+ "primary": "#9BCBFB",
+ "primaryContainer": "#0F4A73",
+ "secondaryContainer": "#3B4858",
+ "surface": "#101418",
+ "surfaceContainer": "#1C2024",
+ "surfaceContainerHigh": "#262A2F",
+ "surfaceContainerHighest": "#31353A",
+ "surfaceContainerLow": "#0B0F13"
+ },
+ "light": {
+ "onPrimary": "#FFFFFF",
+ "onPrimaryContainer": "#001D33",
+ "onSecondaryContainer": "#0E1D2A",
+ "onSurface": "#181C20",
+ "onSurfaceVariant": "#42474E",
+ "outline": "#72777F",
+ "outlineVariant": "#C2C7CF",
+ "primary": "#2F628C",
+ "primaryContainer": "#CEE5FF",
+ "secondaryContainer": "#D5E4F7",
+ "surface": "#F7F9FF",
+ "surfaceContainer": "#ECEEF4",
+ "surfaceContainerHigh": "#E6E8EE",
+ "surfaceContainerHighest": "#E0E2E8",
+ "surfaceContainerLow": "#F1F4FA"
+ },
+ "seed": "#3D7DA8"
+ },
+ "sage": {
+ "dark": {
+ "onPrimary": "#0A390F",
+ "onPrimaryContainer": "#BCF0B4",
+ "onSecondaryContainer": "#D6E8CF",
+ "onSurface": "#E0E4DA",
+ "onSurfaceVariant": "#C2C8BD",
+ "outline": "#8C9388",
+ "outlineVariant": "#424940",
+ "primary": "#A1D39A",
+ "primaryContainer": "#234F24",
+ "secondaryContainer": "#3B4B38",
+ "surface": "#10140F",
+ "surfaceContainer": "#1D211B",
+ "surfaceContainerHigh": "#272B25",
+ "surfaceContainerHighest": "#32362F",
+ "surfaceContainerLow": "#0C100B"
+ },
+ "light": {
+ "onPrimary": "#FFFFFF",
+ "onPrimaryContainer": "#002204",
+ "onSecondaryContainer": "#111F0F",
+ "onSurface": "#191D17",
+ "onSurfaceVariant": "#424940",
+ "outline": "#72796F",
+ "outlineVariant": "#C2C8BD",
+ "primary": "#3B6939",
+ "primaryContainer": "#BCF0B4",
+ "secondaryContainer": "#D6E8CF",
+ "surface": "#F7FBF1",
+ "surfaceContainer": "#EBEFE5",
+ "surfaceContainerHigh": "#E6E9E0",
+ "surfaceContainerHighest": "#E0E4DA",
+ "surfaceContainerLow": "#F1F5EB"
+ },
+ "seed": "#5B8C5A"
+ }
+ },
+ "shape": {
+ "full": 999,
+ "lg": 20,
+ "md": 16,
+ "sm": 12,
+ "xl": 28,
+ "xs": 8
+ },
+ "status": {
+ "dark": {
+ "error": "#FFB4AB",
+ "onError": "#690005",
+ "success": "{primary}",
+ "warning": "#F2C14E"
+ },
+ "light": {
+ "error": "#BA1A1A",
+ "onError": "#FFFFFF",
+ "success": "{primary}",
+ "warning": "#9A6700"
+ }
+ }
+ },
+ "graphite": {
+ "description": "Built-in alternative, from github.com/thtbee/graphite. Monochrome ink on paper / chalk on slate; dynamic color off.",
+ "dynamicColor": false,
+ "fonts": {
+ "display": "Instrument Serif",
+ "label": "Space Mono",
+ "mono": "Space Mono",
+ "note": "Caveat",
+ "ui": "Figtree"
+ },
+ "label": {
+ "case": "upper",
+ "size": 10.5,
+ "tracking": 0.12,
+ "weight": 400
+ },
+ "rules": [
+ "Cards use 1px outlineVariant borders, no fills, no elevation.",
+ "Primary buttons are ink-filled with the flat offset buttonShadow.",
+ "Crop marks frame hero imagery; 'FIG. NN // ...' annotations label sections.",
+ "At most one handwritten (Caveat) margin note per screen, only for delight moments.",
+ "Never use Graphite's art effects in the app: no smudge physics, no gritty lettering, no scroll sound.",
+ "Success and completed states use ink (Paper) or chalk (Slate), never green."
+ ],
+ "shape": {
+ "full": 3,
+ "lg": 4,
+ "md": 4,
+ "sm": 3,
+ "xl": 6,
+ "xs": 2
+ },
+ "variants": {
+ "paper": {
+ "buttonShadow": "3px 3px 0 #D5CFC2",
+ "error": "#9E2B25",
+ "grain": 0.22,
+ "grid": "rgba(74,71,67,0.06)",
+ "onError": "#F5F2EB",
+ "onPrimary": "#F5F2EB",
+ "onPrimaryContainer": "#1A1918",
+ "onSecondaryContainer": "#1A1918",
+ "onSurface": "#1A1918",
+ "onSurfaceVariant": "#5E5A54",
+ "outline": "#4A4743",
+ "outlineVariant": "#D5CFC2",
+ "primary": "#1A1918",
+ "primaryContainer": "#E8E3D7",
+ "secondaryContainer": "#E8E3D7",
+ "success": "#1A1918",
+ "surface": "#F5F2EB",
+ "surfaceContainer": "#F5F2EB",
+ "surfaceContainerHigh": "#EFEBE2",
+ "surfaceContainerHighest": "#E8E3D7",
+ "surfaceContainerLow": "#F1EDE4",
+ "warning": "#8A6A1F"
+ },
+ "slate": {
+ "buttonShadow": "3px 3px 0 #26272A",
+ "error": "#F0A39C",
+ "grain": 0.12,
+ "grid": "rgba(200,208,216,0.035)",
+ "onError": "#0D0D0E",
+ "onPrimary": "#0D0D0E",
+ "onPrimaryContainer": "#E8EAED",
+ "onSecondaryContainer": "#E8EAED",
+ "onSurface": "#E8EAED",
+ "onSurfaceVariant": "#9A9CA1",
+ "outline": "#7E8084",
+ "outlineVariant": "#26272A",
+ "primary": "#E8EAED",
+ "primaryContainer": "#1A1A1D",
+ "secondaryContainer": "#1A1A1D",
+ "success": "#E8EAED",
+ "surface": "#0D0D0E",
+ "surfaceContainer": "#0D0D0E",
+ "surfaceContainerHigh": "#141416",
+ "surfaceContainerHighest": "#1A1A1D",
+ "surfaceContainerLow": "#0B0B0C",
+ "warning": "#E2C47A"
+ }
+ }
+ }
+ },
+ "typography": {
+ "body": {
+ "lineHeight": 1.5,
+ "size": 14,
+ "tracking": 0,
+ "weight": 400
+ },
+ "bodySmall": {
+ "lineHeight": 1.45,
+ "size": 12.5,
+ "tracking": 0,
+ "weight": 400
+ },
+ "caption": {
+ "lineHeight": 1.3,
+ "size": 11,
+ "tracking": 0,
+ "weight": 500
+ },
+ "code": {
+ "font": "mono",
+ "lineHeight": 1.3,
+ "size": 13,
+ "tracking": 0.14,
+ "weight": 700
+ },
+ "displayLarge": {
+ "lineHeight": 1.05,
+ "size": 44,
+ "tracking": -0.025,
+ "weight": 650
+ },
+ "displaySmall": {
+ "lineHeight": 1.1,
+ "size": 30,
+ "tracking": -0.02,
+ "weight": 650
+ },
+ "headline": {
+ "lineHeight": 1.2,
+ "size": 22,
+ "tracking": -0.015,
+ "weight": 650
+ },
+ "label": {
+ "lineHeight": 1.3,
+ "size": 12.5,
+ "tracking": 0,
+ "weight": 600
+ },
+ "title": {
+ "lineHeight": 1.35,
+ "size": 16,
+ "tracking": 0,
+ "weight": 600
+ }
+ }
+ })
+}
diff --git a/desktop/app/qml/components/Avatar.qml b/desktop/app/qml/components/Avatar.qml
new file mode 100644
index 0000000..2a1c14c
--- /dev/null
+++ b/desktop/app/qml/components/Avatar.qml
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A round device or app badge: an icon, or the first letter of a name.
+Rectangle {
+ id: avatar
+ property string name
+ property string iconPath
+ property bool emphasized: false
+
+ implicitWidth: 36
+ implicitHeight: 36
+ radius: Theme.graphite ? Theme.radiusSm : width / 2
+ color: Theme.graphite ? "transparent" : (emphasized ? Theme.primaryContainer : Theme.surfaceContainerHighest)
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+
+ readonly property color ink: Theme.graphite ? Theme.surfaceContent
+ : (emphasized ? Theme.primaryContainerContent : Theme.surfaceContentVariant)
+ Icon {
+ visible: avatar.iconPath.length > 0
+ anchors.centerIn: parent
+ width: avatar.width * 0.5; height: width
+ path: avatar.iconPath
+ color: avatar.ink
+ }
+ Txt {
+ visible: avatar.iconPath.length === 0
+ anchors.centerIn: parent
+ text: avatar.name.length > 0 ? avatar.name.charAt(0).toUpperCase() : ""
+ role: "label"
+ font.weight: 700
+ color: avatar.ink
+ }
+}
diff --git a/desktop/app/qml/components/Button.qml b/desktop/app/qml/components/Button.qml
new file mode 100644
index 0000000..f4b814e
--- /dev/null
+++ b/desktop/app/qml/components/Button.qml
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A pill button. Variants: "fill" (primary action), "tonal", "outline",
+// "text". Sizes: "md" (40 px) and "sm" (32 px). Works with mouse, touch and
+// keyboard (Tab to focus, Enter or Space to press).
+FocusScope {
+ id: button
+ property string text
+ property string iconPath
+ property string variant: "fill"
+ property string size: "md"
+ property bool busy: false
+ signal clicked
+
+ readonly property bool small: size === "sm"
+ readonly property bool interactive: enabled && !busy
+ readonly property color background: {
+ if (variant === "fill")
+ return Theme.graphite ? Theme.surfaceContent : Theme.primary
+ if (variant === "tonal")
+ return Theme.secondaryContainer
+ return "transparent"
+ }
+ readonly property color foreground: {
+ if (variant === "fill")
+ return Theme.graphite ? Theme.surface : Theme.primaryContent
+ if (variant === "tonal")
+ return Theme.secondaryContainerContent
+ if (variant === "text")
+ return Theme.graphite ? Theme.surfaceContent : Theme.primary
+ return Theme.surfaceContent
+ }
+
+ implicitHeight: small ? 32 : 40
+ implicitWidth: row.implicitWidth + (variant === "text" ? 20 : (small ? 26 : 36))
+ activeFocusOnTab: true
+ opacity: enabled ? 1 : 0.38
+
+ Accessible.role: Accessible.Button
+ Accessible.name: text
+ Accessible.onPressAction: if (interactive) button.clicked()
+ Keys.onPressed: (event) => {
+ if (interactive && (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space)) {
+ button.clicked()
+ event.accepted = true
+ }
+ }
+
+ // Graphite's flat offset shadow under filled buttons.
+ Rectangle {
+ visible: Theme.graphite && button.variant === "fill"
+ x: 3; y: 3
+ width: parent.width; height: parent.height
+ radius: body.radius
+ color: Theme.buttonShadow
+ }
+
+ Rectangle {
+ id: body
+ width: parent.width
+ height: parent.height
+ radius: Theme.pill(height)
+ color: button.background
+ border.width: button.variant === "outline" ? 1 : 0
+ border.color: Theme.outline
+ scale: tap.pressed && button.interactive ? Theme.pressScale : 1
+ Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }
+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }
+
+ // Hover and press state layer.
+ Rectangle {
+ anchors.fill: parent
+ radius: parent.radius
+ color: button.foreground
+ opacity: !button.interactive ? 0 : (tap.pressed ? 0.12 : (hover.hovered ? 0.08 : 0))
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }
+ }
+
+ Row {
+ id: row
+ anchors.centerIn: parent
+ spacing: 8
+ Spinner {
+ visible: button.busy
+ anchors.verticalCenter: parent.verticalCenter
+ width: 16; height: 16
+ color: button.foreground
+ }
+ Icon {
+ visible: button.iconPath.length > 0 && !button.busy
+ anchors.verticalCenter: parent.verticalCenter
+ width: button.small ? 16 : 18; height: width
+ path: button.iconPath
+ color: button.foreground
+ }
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ text: button.text
+ role: "label"
+ color: button.foreground
+ size: Theme.graphite ? 11 : (button.small ? 13 : 14)
+ font.underline: Theme.graphite && button.variant === "text"
+ }
+ }
+ }
+
+ // Keyboard focus ring.
+ Rectangle {
+ anchors.fill: body
+ anchors.margins: -3
+ radius: body.radius + 3
+ color: "transparent"
+ border.width: 2
+ border.color: Theme.primary
+ visible: button.activeFocus
+ }
+
+ HoverHandler { id: hover; cursorShape: button.interactive ? Qt.PointingHandCursor : Qt.ArrowCursor }
+ TapHandler {
+ id: tap
+ enabled: button.interactive
+ onTapped: button.clicked()
+ }
+}
diff --git a/desktop/app/qml/components/CaptionButtons.qml b/desktop/app/qml/components/CaptionButtons.qml
new file mode 100644
index 0000000..f8df244
--- /dev/null
+++ b/desktop/app/qml/components/CaptionButtons.qml
@@ -0,0 +1,97 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// Minimize, maximize/restore and close, drawn like Windows 11's own (same
+// size and glyphs) in the app's colors. The maximize button is registered
+// with the window so Windows shows Snap Layouts when hovering it.
+Row {
+ id: buttons
+ required property NativeWindow window
+ readonly property bool maximized: window.visibility === Window.Maximized
+
+ height: 36
+ z: 1000
+
+ CaptionButton {
+ id: minimize
+ glyph: ""
+ label: qsTr("Minimize")
+ onActivated: buttons.window.showMinimized()
+ Component.onCompleted: buttons.window.addCaptionHole(minimize)
+ }
+ CaptionButton {
+ id: maximize
+ glyph: buttons.maximized ? "" : ""
+ label: buttons.maximized ? qsTr("Restore") : qsTr("Maximize")
+ // Mouse input for this button goes through Windows (Snap Layouts).
+ nativeInput: true
+ hovered: buttons.window.maximizeHovered
+ pressed: buttons.window.maximizePressed
+ onActivated: buttons.window.toggleMaximized()
+ Component.onCompleted: buttons.window.maximizeButton = maximize
+ }
+ CaptionButton {
+ id: close
+ glyph: ""
+ label: qsTr("Close")
+ danger: true
+ onActivated: buttons.window.close()
+ Component.onCompleted: buttons.window.addCaptionHole(close)
+ }
+
+ component CaptionButton: Item {
+ id: button
+ property string glyph
+ property string label
+ property bool danger: false
+ property bool nativeInput: false
+ property bool hovered: !nativeInput && hover.hovered
+ property bool pressed: !nativeInput && tap.pressed
+ signal activated
+
+ width: 46
+ height: buttons.height
+ activeFocusOnTab: true
+
+ Accessible.role: Accessible.Button
+ Accessible.name: label
+ Accessible.onPressAction: button.activated()
+ Keys.onPressed: (event) => {
+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {
+ button.activated()
+ event.accepted = true
+ }
+ }
+
+ // Windows' close button turns red on hover in every theme.
+ readonly property color dangerColor: "#C42B1C"
+ Rectangle {
+ anchors.fill: parent
+ color: button.danger && (button.hovered || button.pressed)
+ ? (button.pressed ? Qt.lighter(button.dangerColor, 1.15) : button.dangerColor)
+ : Theme.surfaceContent
+ opacity: button.danger && (button.hovered || button.pressed) ? 1
+ : (button.pressed ? 0.12 : (button.hovered ? 0.07 : 0))
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }
+ }
+ Text {
+ anchors.centerIn: parent
+ text: button.glyph
+ font.family: "Segoe Fluent Icons"
+ font.pixelSize: 10
+ color: button.danger && (button.hovered || button.pressed) ? "#FFFFFF" : Theme.surfaceContent
+ opacity: buttons.window.active || button.hovered ? 1 : 0.45
+ }
+ Rectangle {
+ anchors.fill: parent
+ anchors.margins: 2
+ color: "transparent"
+ border.width: 2
+ border.color: Theme.primary
+ visible: button.activeFocus
+ }
+ HoverHandler { id: hover; enabled: !button.nativeInput }
+ TapHandler { id: tap; enabled: !button.nativeInput; onTapped: button.activated() }
+ }
+}
diff --git a/desktop/app/qml/components/Card.qml b/desktop/app/qml/components/Card.qml
new file mode 100644
index 0000000..42273d4
--- /dev/null
+++ b/desktop/app/qml/components/Card.qml
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A content surface: filled in Bloom, hairline-bordered in Graphite.
+Rectangle {
+ property int padding: 16
+ default property alias content: inner.data
+
+ radius: Theme.radiusLg
+ color: Theme.cardColor
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.cardBorder
+ implicitHeight: inner.childrenRect.height + padding * 2
+ Behavior on color { ColorAnimation { duration: Theme.fadeNormal } }
+
+ Item {
+ id: inner
+ anchors.fill: parent
+ anchors.margins: parent.padding
+ }
+}
diff --git a/desktop/app/qml/components/Chip.qml b/desktop/app/qml/components/Chip.qml
new file mode 100644
index 0000000..b1ddd41
--- /dev/null
+++ b/desktop/app/qml/components/Chip.qml
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A small pill with optional icon. `selected` uses the indicator colors.
+Rectangle {
+ id: chip
+ property string text
+ property string iconPath
+ property bool selected: false
+
+ implicitHeight: 30
+ implicitWidth: row.implicitWidth + 24
+ radius: Theme.pill(height)
+ color: Theme.graphite ? (selected ? Theme.surfaceContent : "transparent")
+ : (selected ? Theme.secondaryContainer : Theme.surfaceContainerHigh)
+ border.width: Theme.graphite ? 1 : 0
+ border.color: selected ? Theme.surfaceContent : Theme.outlineVariant
+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }
+
+ Row {
+ id: row
+ anchors.centerIn: parent
+ spacing: 6
+ Icon {
+ visible: chip.iconPath.length > 0
+ anchors.verticalCenter: parent.verticalCenter
+ width: 15; height: 15
+ path: chip.iconPath
+ color: label.color
+ }
+ Txt {
+ id: label
+ anchors.verticalCenter: parent.verticalCenter
+ text: chip.text
+ role: "label"
+ color: Theme.graphite ? (chip.selected ? Theme.surface : Theme.surfaceContent)
+ : (chip.selected ? Theme.secondaryContainerContent : Theme.surfaceContent)
+ }
+ }
+}
diff --git a/desktop/app/qml/components/CodeDigits.qml b/desktop/app/qml/components/CodeDigits.qml
new file mode 100644
index 0000000..91b777b
--- /dev/null
+++ b/desktop/app/qml/components/CodeDigits.qml
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// The 6-digit pairing code, one digit per tile, as both screens show it.
+Row {
+ id: digits
+ property string code
+ spacing: 8
+
+ Accessible.role: Accessible.StaticText
+ Accessible.name: code.split("").join(" ")
+
+ Repeater {
+ model: digits.code.split("")
+ delegate: Rectangle {
+ required property string modelData
+ width: 44; height: 56
+ radius: Theme.radiusMd
+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHigh
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+ Txt {
+ anchors.centerIn: parent
+ text: parent.modelData
+ role: "code"
+ size: 26
+ font.letterSpacing: 0
+ }
+ }
+ }
+}
diff --git a/desktop/app/qml/components/Divider.qml b/desktop/app/qml/components/Divider.qml
new file mode 100644
index 0000000..1343a43
--- /dev/null
+++ b/desktop/app/qml/components/Divider.qml
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A hairline separator.
+Rectangle {
+ implicitWidth: 1
+ implicitHeight: 1
+ color: Theme.outlineVariant
+}
diff --git a/desktop/app/qml/components/Icon.qml b/desktop/app/qml/components/Icon.qml
new file mode 100644
index 0000000..78d96e1
--- /dev/null
+++ b/desktop/app/qml/components/Icon.qml
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import QtQuick.Shapes
+import app.nectarlink
+
+// A stroke icon from Icons (an SVG path on a 24×24 grid).
+Item {
+ id: icon
+ property string path
+ property color color: Theme.surfaceContent
+ property real stroke: 1.8
+
+ implicitWidth: 20
+ implicitHeight: 20
+
+ Shape {
+ anchors.centerIn: parent
+ width: 24
+ height: 24
+ scale: Math.min(icon.width, icon.height) / 24
+ preferredRendererType: Shape.CurveRenderer
+ ShapePath {
+ strokeColor: icon.color
+ strokeWidth: icon.stroke
+ fillColor: "transparent"
+ capStyle: ShapePath.RoundCap
+ joinStyle: ShapePath.RoundJoin
+ PathSvg { path: icon.path }
+ }
+ }
+}
diff --git a/desktop/app/qml/components/IconButton.qml b/desktop/app/qml/components/IconButton.qml
new file mode 100644
index 0000000..6a19db9
--- /dev/null
+++ b/desktop/app/qml/components/IconButton.qml
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A round icon-only button with a tooltip-style accessible name.
+FocusScope {
+ id: button
+ property string iconPath
+ property string label
+ property bool tonal: false
+ property color iconColor: tonal ? Theme.secondaryContainerContent : Theme.surfaceContentVariant
+ signal clicked
+
+ implicitWidth: 36
+ implicitHeight: 36
+ activeFocusOnTab: true
+ opacity: enabled ? 1 : 0.38
+
+ Accessible.role: Accessible.Button
+ Accessible.name: label
+ Accessible.onPressAction: if (enabled) button.clicked()
+ Keys.onPressed: (event) => {
+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {
+ button.clicked()
+ event.accepted = true
+ }
+ }
+
+ Rectangle {
+ id: body
+ anchors.fill: parent
+ radius: Theme.pill(height)
+ color: button.tonal ? Theme.secondaryContainer : "transparent"
+ scale: tap.pressed ? Theme.pressScale : 1
+ Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }
+
+ Rectangle {
+ anchors.fill: parent
+ radius: parent.radius
+ color: Theme.surfaceContent
+ opacity: tap.pressed ? 0.12 : (hover.hovered ? 0.07 : 0)
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }
+ }
+ Icon {
+ anchors.centerIn: parent
+ width: 18; height: 18
+ path: button.iconPath
+ color: button.iconColor
+ }
+ }
+ Rectangle {
+ anchors.fill: body
+ anchors.margins: -3
+ radius: body.radius + 3
+ color: "transparent"
+ border.width: 2
+ border.color: Theme.primary
+ visible: button.activeFocus
+ }
+
+ HoverHandler { id: hover; cursorShape: Qt.PointingHandCursor }
+ TapHandler { id: tap; onTapped: button.clicked() }
+}
diff --git a/desktop/app/qml/components/ListRow.qml b/desktop/app/qml/components/ListRow.qml
new file mode 100644
index 0000000..ea7909b
--- /dev/null
+++ b/desktop/app/qml/components/ListRow.qml
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A settings-style row: optional icon, title and description, and a
+// trailing control placed in `trailing`.
+Item {
+ id: row
+ property string iconPath
+ property string title
+ property string description
+ default property alias trailing: trailingSlot.data
+
+ implicitHeight: Math.max(56, texts.implicitHeight + 20)
+
+ Icon {
+ id: icon
+ visible: row.iconPath.length > 0
+ anchors.left: parent.left
+ anchors.verticalCenter: parent.verticalCenter
+ path: row.iconPath
+ color: Theme.surfaceContentVariant
+ }
+ Column {
+ id: texts
+ anchors.left: icon.visible ? icon.right : parent.left
+ anchors.leftMargin: icon.visible ? 14 : 0
+ anchors.right: trailingSlot.left
+ anchors.rightMargin: 16
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 2
+ Txt { width: parent.width; text: row.title; role: "title"; size: 14 }
+ Txt {
+ visible: row.description.length > 0
+ width: parent.width
+ text: row.description
+ role: "bodySmall"
+ muted: true
+ wrapMode: Text.WordWrap
+ elide: Text.ElideNone
+ }
+ }
+ Item {
+ id: trailingSlot
+ anchors.right: parent.right
+ anchors.verticalCenter: parent.verticalCenter
+ width: childrenRect.width
+ height: childrenRect.height
+ }
+}
diff --git a/desktop/app/qml/components/LockChip.qml b/desktop/app/qml/components/LockChip.qml
new file mode 100644
index 0000000..72fbd87
--- /dev/null
+++ b/desktop/app/qml/components/LockChip.qml
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// Shown on a locked feature: what unlocks it and how long it takes, e.g.
+// "Elevated · ~2 min". `feature` is AppController.featureState(...).
+Rectangle {
+ id: chip
+ property var feature: ({})
+
+ readonly property string label: {
+ const s = feature || {}
+ let what = ""
+ switch (s.action) {
+ case "raisePower": what = s.target === "elevated" ? qsTr("Elevated") : qsTr("Assist"); break
+ case "grantPermission": what = qsTr("Permission"); break
+ case "enableAddon": what = qsTr("Add-on"); break
+ case "enablePath": what = qsTr("Away mode"); break
+ case "enableToggle": what = qsTr("Turned off"); break
+ case "updateApp": what = qsTr("Update app"); break
+ default: what = s.state === "unsupported" ? qsTr("Not available") : ""
+ }
+ return s.minutes > 0 ? qsTr("%1 · ~%2 min").arg(what).arg(s.minutes) : what
+ }
+
+ visible: label.length > 0
+ implicitHeight: 22
+ implicitWidth: row.implicitWidth + 16
+ radius: Theme.pill(height)
+ color: "transparent"
+ border.width: 1
+ border.color: Theme.outlineVariant
+
+ Row {
+ id: row
+ anchors.centerIn: parent
+ spacing: 5
+ Icon {
+ anchors.verticalCenter: parent.verticalCenter
+ width: 13; height: 13
+ path: Icons.lock
+ color: Theme.surfaceContentVariant
+ }
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ text: chip.label
+ role: "caption"
+ muted: true
+ }
+ }
+}
diff --git a/desktop/app/qml/components/NavItem.qml b/desktop/app/qml/components/NavItem.qml
new file mode 100644
index 0000000..cb4f9ef
--- /dev/null
+++ b/desktop/app/qml/components/NavItem.qml
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A navigation rail destination: an icon in a pill indicator above a label.
+FocusScope {
+ id: item
+ property string iconPath
+ property string text
+ property bool selected: false
+ signal clicked
+
+ implicitWidth: 72
+ implicitHeight: 56
+ activeFocusOnTab: true
+
+ Accessible.role: Accessible.PageTab
+ Accessible.name: text
+ Accessible.selected: selected
+ Accessible.onPressAction: item.clicked()
+ Keys.onPressed: (event) => {
+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {
+ item.clicked()
+ event.accepted = true
+ }
+ }
+
+ Rectangle {
+ id: pill
+ anchors.horizontalCenter: parent.horizontalCenter
+ y: 2
+ width: 52; height: 30
+ radius: Theme.pill(height)
+ color: item.selected ? Theme.indicator : (hover.hovered ? Theme.surfaceContainerHigh : "transparent")
+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }
+ scale: tap.pressed ? Theme.pressScale : 1
+ Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }
+ Icon {
+ anchors.centerIn: parent
+ path: item.iconPath
+ color: item.selected ? Theme.indicatorContent : Theme.surfaceContentVariant
+ }
+ }
+ Txt {
+ anchors.horizontalCenter: parent.horizontalCenter
+ anchors.top: pill.bottom
+ anchors.topMargin: 4
+ text: item.text
+ role: "caption"
+ font.weight: Theme.graphite ? 400 : 600
+ color: item.selected ? Theme.surfaceContent : Theme.surfaceContentVariant
+ }
+ Rectangle {
+ anchors.fill: pill
+ anchors.margins: -3
+ radius: pill.radius + 3
+ color: "transparent"
+ border.width: 2
+ border.color: Theme.primary
+ visible: item.activeFocus
+ }
+ HoverHandler { id: hover; cursorShape: Qt.PointingHandCursor }
+ TapHandler { id: tap; onTapped: item.clicked() }
+}
diff --git a/desktop/app/qml/components/QrCode.qml b/desktop/app/qml/components/QrCode.qml
new file mode 100644
index 0000000..490c9d5
--- /dev/null
+++ b/desktop/app/qml/components/QrCode.qml
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import QtQuick.Shapes
+import app.nectarlink
+
+// A QR code from Pairing.qrPath: vector modules on a white tile with the
+// quiet zone scanners need. Always dark on light, in every theme, so it
+// scans reliably; modules snap to whole pixels for crisp edges.
+Rectangle {
+ id: qr
+ property string path
+ property int modules: 21
+ // Quiet zone around the code, in modules (the spec's minimum is 4; the
+ // tile's own margin adds to it).
+ readonly property int quietZone: 2
+
+ readonly property int cell: Math.max(1, Math.floor(width / (modules + quietZone * 2)))
+
+ radius: Theme.radiusLg
+ color: "#FFFFFF"
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+
+ Shape {
+ width: qr.modules
+ height: qr.modules
+ x: Math.round((qr.width - qr.modules * qr.cell) / 2)
+ y: Math.round((qr.height - qr.modules * qr.cell) / 2)
+ scale: qr.cell
+ transformOrigin: Item.TopLeft
+ ShapePath {
+ strokeWidth: -1
+ fillColor: "#1A1918"
+ PathSvg { path: qr.path }
+ }
+ }
+}
diff --git a/desktop/app/qml/components/Segmented.qml b/desktop/app/qml/components/Segmented.qml
new file mode 100644
index 0000000..c4dd4ff
--- /dev/null
+++ b/desktop/app/qml/components/Segmented.qml
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A segmented choice: `options` is a list of { value, label }.
+Rectangle {
+ id: segmented
+ property var options: []
+ property string value
+ signal picked(string value)
+
+ implicitHeight: 36
+ implicitWidth: row.implicitWidth + 6
+ radius: Theme.pill(height)
+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHigh
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+
+ Accessible.role: Accessible.PageTabList
+
+ Row {
+ id: row
+ anchors.centerIn: parent
+ spacing: 2
+ Repeater {
+ model: segmented.options
+ delegate: FocusScope {
+ id: option
+ required property var modelData
+ readonly property bool selected: modelData.value === segmented.value
+ width: label.implicitWidth + 26
+ height: segmented.height - 6
+ activeFocusOnTab: true
+ Accessible.role: Accessible.PageTab
+ Accessible.name: modelData.label
+ Accessible.selected: selected
+ Accessible.onPressAction: segmented.picked(modelData.value)
+ Keys.onPressed: (event) => {
+ if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter || event.key === Qt.Key_Space) {
+ segmented.picked(modelData.value)
+ event.accepted = true
+ }
+ }
+ Rectangle {
+ anchors.fill: parent
+ radius: Theme.pill(height)
+ color: option.selected ? (Theme.graphite ? Theme.surfaceContent : Theme.surface) : "transparent"
+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }
+ border.width: option.activeFocus ? 2 : 0
+ border.color: Theme.primary
+ }
+ Txt {
+ id: label
+ anchors.centerIn: parent
+ text: option.modelData.label
+ role: "label"
+ color: option.selected ? (Theme.graphite ? Theme.surface : Theme.surfaceContent) : Theme.surfaceContentVariant
+ }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ TapHandler { onTapped: segmented.picked(option.modelData.value) }
+ }
+ }
+ }
+}
diff --git a/desktop/app/qml/components/Sheet.qml b/desktop/app/qml/components/Sheet.qml
new file mode 100644
index 0000000..acd0baa
--- /dev/null
+++ b/desktop/app/qml/components/Sheet.qml
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A modal dialog over the window: a scrim and a card that springs in.
+// Escape or a click on the scrim closes it (unless `dismissable` is false).
+Item {
+ id: sheet
+ property bool opened: false
+ property bool dismissable: true
+ property real cardWidth: 460
+ default property alias content: body.data
+ signal dismissed
+
+ function open() { opened = true }
+ function close() { opened = false }
+
+ anchors.fill: parent
+ visible: opened || fade.running
+ z: 100
+
+ Rectangle {
+ id: scrim
+ anchors.fill: parent
+ color: Theme.scrim
+ opacity: sheet.opened ? 1 : 0
+ Behavior on opacity { NumberAnimation { id: fade; duration: Theme.fadeNormal } }
+ TapHandler {
+ onTapped: if (sheet.dismissable) { sheet.close(); sheet.dismissed() }
+ }
+ }
+
+ Rectangle {
+ id: card
+ anchors.centerIn: parent
+ width: Math.min(sheet.cardWidth, parent.width - 48)
+ height: Math.min(body.childrenRect.height + 48, parent.height - 48)
+ radius: Theme.radiusXl
+ color: Theme.surface
+ border.width: 1
+ border.color: Theme.outlineVariant
+ opacity: sheet.opened ? 1 : 0
+ scale: sheet.opened || Theme.reduceMotion ? 1 : 0.96
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }
+ Behavior on scale { SpringAnimation { spring: Theme.springStandard; damping: Theme.dampingStandard } }
+ clip: true
+
+ // Swallow clicks so they don't reach the scrim.
+ TapHandler {}
+ Item {
+ id: body
+ anchors.fill: parent
+ anchors.margins: 24
+ }
+ }
+
+ focus: opened
+ Keys.onEscapePressed: if (sheet.dismissable) { sheet.close(); sheet.dismissed() }
+}
diff --git a/desktop/app/qml/components/Spinner.qml b/desktop/app/qml/components/Spinner.qml
new file mode 100644
index 0000000..1c02bc6
--- /dev/null
+++ b/desktop/app/qml/components/Spinner.qml
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import QtQuick.Shapes
+import app.nectarlink
+
+// An indeterminate progress ring. Pulses instead of spinning when the
+// user asked for reduced motion.
+Item {
+ id: spinner
+ property color color: Theme.primary
+ implicitWidth: 20
+ implicitHeight: 20
+
+ Shape {
+ anchors.fill: parent
+ preferredRendererType: Shape.CurveRenderer
+ RotationAnimator on rotation {
+ running: spinner.visible && !Theme.reduceMotion
+ from: 0; to: 360; duration: 900
+ loops: Animation.Infinite
+ }
+ SequentialAnimation on opacity {
+ running: spinner.visible && Theme.reduceMotion
+ loops: Animation.Infinite
+ NumberAnimation { to: 0.35; duration: 600 }
+ NumberAnimation { to: 1; duration: 600 }
+ }
+ ShapePath {
+ strokeColor: spinner.color
+ strokeWidth: Math.max(2, spinner.width / 10)
+ fillColor: "transparent"
+ capStyle: ShapePath.RoundCap
+ PathAngleArc {
+ centerX: spinner.width / 2; centerY: spinner.height / 2
+ radiusX: spinner.width / 2 - 2; radiusY: spinner.height / 2 - 2
+ startAngle: 0; sweepAngle: 270
+ }
+ }
+ }
+}
diff --git a/desktop/app/qml/components/StatusDot.qml b/desktop/app/qml/components/StatusDot.qml
new file mode 100644
index 0000000..71eeded
--- /dev/null
+++ b/desktop/app/qml/components/StatusDot.qml
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// Connection indicator: a dot with a soft halo when online (never green:
+// the theme's primary carries "connected").
+Item {
+ property bool online: false
+ implicitWidth: 13
+ implicitHeight: 13
+
+ Rectangle {
+ anchors.centerIn: parent
+ width: 13; height: 13; radius: 6.5
+ color: Theme.success
+ opacity: parent.online ? 0.22 : 0
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }
+ }
+ Rectangle {
+ anchors.centerIn: parent
+ width: 7; height: 7; radius: 3.5
+ color: parent.online ? Theme.success : Theme.outline
+ Behavior on color { ColorAnimation { duration: Theme.fadeNormal } }
+ }
+}
diff --git a/desktop/app/qml/components/Toast.qml b/desktop/app/qml/components/Toast.qml
new file mode 100644
index 0000000..0311a26
--- /dev/null
+++ b/desktop/app/qml/components/Toast.qml
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A short message at the bottom of the window that hides itself.
+Rectangle {
+ id: toast
+ property int timeout: 4000
+
+ function show(message) {
+ label.text = message
+ shown = true
+ timer.restart()
+ }
+
+ property bool shown: false
+ anchors.horizontalCenter: parent.horizontalCenter
+ anchors.bottom: parent.bottom
+ anchors.bottomMargin: shown ? 24 : -height
+ Behavior on anchors.bottomMargin { SpringAnimation { spring: Theme.springStandard; damping: Theme.dampingStandard } }
+ opacity: shown ? 1 : 0
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeFast } }
+ z: 200
+
+ width: Math.min(label.implicitWidth + 40, parent.width - 48)
+ height: 44
+ radius: Theme.pill(height)
+ color: Theme.surfaceContent
+
+ Accessible.role: Accessible.AlertMessage
+ Accessible.name: label.text
+
+ Txt {
+ id: label
+ anchors.centerIn: parent
+ width: parent.width - 40
+ horizontalAlignment: Text.AlignHCenter
+ role: "body"
+ color: Theme.surface
+ }
+ Timer { id: timer; interval: toast.timeout; onTriggered: toast.shown = false }
+}
diff --git a/desktop/app/qml/components/Toggle.qml b/desktop/app/qml/components/Toggle.qml
new file mode 100644
index 0000000..7f54a79
--- /dev/null
+++ b/desktop/app/qml/components/Toggle.qml
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// A Material switch. Click, Space or Enter flips it; `toggled` reports the
+// user's choice (bind `checked` to the source of truth).
+FocusScope {
+ id: toggle
+ property bool checked: false
+ property string label
+ signal toggled(bool checked)
+
+ implicitWidth: 46
+ implicitHeight: 28
+ activeFocusOnTab: true
+ opacity: enabled ? 1 : 0.38
+
+ Accessible.role: Accessible.CheckBox
+ Accessible.name: label
+ Accessible.checkable: true
+ Accessible.checked: checked
+ Accessible.onToggleAction: toggle.toggled(!toggle.checked)
+ Keys.onPressed: (event) => {
+ if (event.key === Qt.Key_Space || event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {
+ toggle.toggled(!toggle.checked)
+ event.accepted = true
+ }
+ }
+
+ Rectangle {
+ id: track
+ anchors.fill: parent
+ radius: Theme.graphite ? Theme.radiusSm : height / 2
+ color: toggle.checked ? Theme.primary : Theme.surfaceContainerHighest
+ border.width: toggle.checked ? 0 : 1.5
+ border.color: Theme.outline
+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }
+
+ Rectangle {
+ id: thumb
+ property real size: toggle.checked ? 19 : (tap.pressed ? 22 : 15)
+ width: size; height: size
+ radius: Theme.graphite ? Theme.radiusXs : size / 2
+ anchors.verticalCenter: parent.verticalCenter
+ x: toggle.checked ? parent.width - width - 4.5 : 6.5
+ color: toggle.checked ? Theme.primaryContent : Theme.outline
+ Behavior on x { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }
+ Behavior on size { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }
+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }
+ }
+ }
+ Rectangle {
+ anchors.fill: track
+ anchors.margins: -3
+ radius: track.radius + 3
+ color: "transparent"
+ border.width: 2
+ border.color: Theme.primary
+ visible: toggle.activeFocus
+ }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ TapHandler { id: tap; onTapped: toggle.toggled(!toggle.checked) }
+}
diff --git a/desktop/app/qml/components/Txt.qml b/desktop/app/qml/components/Txt.qml
new file mode 100644
index 0000000..8d91714
--- /dev/null
+++ b/desktop/app/qml/components/Txt.qml
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// Text in one of the design's type roles: displayLarge, displaySmall,
+// headline, title, body, bodySmall, label, caption, code.
+Text {
+ id: txt
+ property string role: "body"
+ // Secondary text uses the variant color.
+ property bool muted: false
+
+ readonly property var spec: Theme.typography[role] || Theme.typography.body
+ readonly property bool isDisplay: role === "displayLarge" || role === "displaySmall" || role === "headline"
+ // Graphite labels are mono, uppercase and tracked (docs/design/README.md).
+ readonly property bool graphiteLabel: Theme.graphite && (role === "label" || role === "caption")
+
+ // Pixel size; set this (not font.pixelSize) to resize, so the role's
+ // tracking scales with it.
+ property int size: Math.round(graphiteLabel ? Theme.labelStyle.size : spec.size)
+
+ color: muted ? Theme.surfaceContentVariant : Theme.surfaceContent
+ font.family: role === "code" || graphiteLabel ? Theme.fontMono : (isDisplay ? Theme.fontDisplay : Theme.fontUi)
+ font.pixelSize: size
+ font.weight: graphiteLabel ? Theme.labelStyle.weight : (isDisplay && Theme.graphite ? 400 : spec.weight)
+ font.letterSpacing: (graphiteLabel ? Theme.labelStyle.tracking : spec.tracking) * size
+ font.capitalization: graphiteLabel ? Font.AllUppercase : Font.MixedCase
+ // Token line heights are CSS-style (a multiple of the font size), not
+ // a multiple of the font's own line spacing.
+ lineHeight: Math.round(size * spec.lineHeight)
+ lineHeightMode: Text.FixedHeight
+ textFormat: Text.PlainText
+ elide: Text.ElideRight
+ Behavior on color { ColorAnimation { duration: Theme.fadeNormal } }
+}
diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qml
new file mode 100644
index 0000000..45cf1fd
--- /dev/null
+++ b/desktop/app/qml/pages/HomePage.qml
@@ -0,0 +1,371 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// Home: the paired phone at a glance (status, battery, power level) and
+// quick actions. Actions reflect the capability matrix: what isn't
+// available shows what unlocks it.
+Item {
+ id: page
+ property bool active: true
+ property int current: 0
+ signal pairRequested
+
+ opacity: active ? 1 : 0
+ visible: opacity > 0
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }
+ transform: Translate {
+ y: page.active || Theme.reduceMotion ? 0 : 12
+ Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }
+ }
+
+ onCurrentChanged: if (current >= DeviceList.count) current = 0
+ Connections {
+ target: DeviceList
+ function onCountChanged() { if (page.current >= DeviceList.count) page.current = Math.max(0, DeviceList.count - 1) }
+ }
+
+ function relativeTime(unixSeconds) {
+ if (!unixSeconds)
+ return qsTr("never")
+ const minutes = Math.round((Date.now() / 1000 - unixSeconds) / 60)
+ if (minutes < 1) return qsTr("just now")
+ if (minutes < 60) return qsTr("%n min ago", "", minutes)
+ const hours = Math.round(minutes / 60)
+ if (hours < 24) return qsTr("%n h ago", "", hours)
+ return new Date(unixSeconds * 1000).toLocaleDateString(Qt.locale(), Locale.ShortFormat)
+ }
+
+ Flickable {
+ anchors.fill: parent
+ contentHeight: column.height + Theme.contentPadding * 2
+ boundsBehavior: Flickable.StopAtBounds
+ clip: true
+
+ Column {
+ id: column
+ x: Theme.contentPadding
+ y: Theme.contentPadding
+ width: parent.width - Theme.contentPadding * 2
+ spacing: Theme.gutter
+
+ // Device switcher (only with more than one device).
+ Row {
+ spacing: 8
+ visible: DeviceList.count > 1
+ Repeater {
+ model: DeviceList
+ delegate: Chip {
+ required property int index
+ required property string name
+ required property string kind
+ text: name
+ iconPath: kind === "tablet" || kind === "phone" ? Icons.phone : Icons.laptop
+ selected: index === page.current
+ TapHandler { onTapped: page.current = index }
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ }
+ }
+ }
+
+ Repeater {
+ model: DeviceList
+ delegate: DeviceHome {
+ required property int index
+ width: column.width
+ visible: index === page.current
+ }
+ }
+ }
+ }
+
+ component DeviceHome: Row {
+ id: home
+ required property string deviceId
+ required property string name
+ required property string kind
+ required property string osVersion
+ required property string model
+ required property bool online
+ required property string path
+ required property int rttMs
+ required property int battery
+ required property bool charging
+ required property string power
+ required property real lastSeen
+ required property real pairedAt
+
+ // Re-read capabilities whenever any matrix changes.
+ function feature(id) {
+ return AppController.capsRevision >= 0 ? AppController.featureState(deviceId, id) : ({})
+ }
+ property bool ringing: false
+ Timer { id: ringTimeout; interval: 30000; onTriggered: home.ringing = false }
+
+ spacing: Theme.gutter
+ readonly property real sideWidth: 300
+
+ Column {
+ width: home.width - home.sideWidth - home.spacing
+ spacing: Theme.gutter
+
+ // ---- Hero ----
+ Rectangle {
+ width: parent.width
+ height: 190
+ radius: Theme.radiusXl
+ color: Theme.heroColor
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+
+ Rectangle {
+ id: phoneArt
+ x: 24
+ anchors.verticalCenter: parent.verticalCenter
+ width: 86; height: 150
+ radius: 20
+ border.width: 3
+ border.color: Theme.graphite ? Theme.surfaceContent : Theme.primaryContainerContent
+ gradient: Gradient {
+ GradientStop { position: 0; color: Theme.graphite ? Theme.surfaceContainerHigh : Theme.primary }
+ GradientStop { position: 1; color: Theme.graphite ? Theme.surfaceContainerHighest : Qt.darker(Theme.primary, 2.0) }
+ }
+ Rectangle {
+ anchors.horizontalCenter: parent.horizontalCenter
+ y: 8
+ width: 22; height: 5; radius: 2.5
+ color: phoneArt.border.color
+ }
+ }
+ Column {
+ anchors.left: phoneArt.right
+ anchors.leftMargin: 24
+ anchors.right: parent.right
+ anchors.rightMargin: 24
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 8
+ Txt {
+ width: parent.width
+ text: home.name
+ role: "displaySmall"
+ color: Theme.heroContent
+ }
+ Txt {
+ width: parent.width
+ role: "body"
+ color: Theme.heroContent
+ opacity: 0.78
+ text: [home.model, home.osVersion.length > 0 ? qsTr("Android %1").arg(home.osVersion) : ""]
+ .filter(s => s.length > 0).join(" · ")
+ }
+ Flow {
+ width: parent.width
+ spacing: 8
+ Chip {
+ visible: home.battery >= 0
+ iconPath: Icons.battery
+ text: home.charging ? qsTr("%1% · charging").arg(home.battery) : qsTr("%1%").arg(home.battery)
+ }
+ Chip {
+ iconPath: home.online ? Icons.wifi : Icons.unlink
+ text: home.online
+ ? (home.rttMs >= 1
+ ? (home.path === "relay" ? qsTr("Away · %1 ms") : qsTr("Wi‑Fi · %1 ms")).arg(home.rttMs)
+ : (home.path === "relay" ? qsTr("Away") : qsTr("Wi‑Fi")))
+ : (home.lastSeen > 0 ? qsTr("Offline · seen %1").arg(page.relativeTime(home.lastSeen))
+ : qsTr("Not connected yet"))
+ }
+ Chip {
+ visible: home.power === "assist" || home.power === "elevated"
+ iconPath: Icons.sparkle
+ text: home.power === "elevated" ? qsTr("Elevated") : qsTr("Assist")
+ }
+ }
+ }
+ }
+
+ // ---- Quick actions ----
+ Grid {
+ id: actions
+ width: parent.width
+ columns: width > 640 ? 4 : 2
+ spacing: 12
+ readonly property real tileWidth: (width - spacing * (columns - 1)) / columns
+
+ ActionTile {
+ width: actions.tileWidth
+ title: home.ringing ? qsTr("Stop ringing") : qsTr("Find phone")
+ subtitle: qsTr("Rings even on silent")
+ iconPath: Icons.ring
+ feature: home.feature("device.find_phone")
+ active: home.ringing
+ onClicked: {
+ home.ringing = !home.ringing
+ if (home.ringing) ringTimeout.restart()
+ AppController.ring(home.deviceId, home.ringing)
+ }
+ }
+ ActionTile {
+ width: actions.tileWidth
+ title: qsTr("Send clipboard")
+ subtitle: qsTr("To the phone")
+ iconPath: Icons.clipboard
+ feature: home.feature("clipboard.pc_to_phone")
+ ready: false
+ }
+ ActionTile {
+ width: actions.tileWidth
+ title: qsTr("Mirror screen")
+ subtitle: qsTr("View and control")
+ iconPath: Icons.mirror
+ feature: home.feature("mirroring.view")
+ ready: false
+ }
+ ActionTile {
+ width: actions.tileWidth
+ title: qsTr("Send files")
+ subtitle: qsTr("Or drop anywhere")
+ iconPath: Icons.send
+ feature: home.feature("files.send")
+ ready: false
+ }
+ }
+ }
+
+ // ---- Details ----
+ Column {
+ width: home.sideWidth
+ spacing: Theme.gutter
+
+ Card {
+ width: parent.width
+ Column {
+ width: parent.width
+ spacing: 12
+ Txt { text: qsTr("Connection"); role: "label"; muted: true }
+ Row {
+ spacing: 10
+ StatusDot { anchors.verticalCenter: parent.verticalCenter; online: home.online }
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ role: "body"
+ text: home.online
+ ? (home.path === "relay" ? qsTr("Connected while away") : qsTr("Connected on this network"))
+ : qsTr("Not connected")
+ }
+ }
+ Txt {
+ width: parent.width
+ wrapMode: Text.WordWrap
+ role: "bodySmall"
+ muted: true
+ text: home.online
+ ? (home.rttMs >= 1 ? qsTr("Round trip %1 ms. End-to-end encrypted.").arg(home.rttMs)
+ : qsTr("Round trip under 1 ms. End-to-end encrypted."))
+ : home.lastSeen > 0
+ ? qsTr("Last seen %1. They reconnect on their own when both are on the same network.")
+ .arg(page.relativeTime(home.lastSeen))
+ : qsTr("Open Nectarlink on %1. They connect on their own when both are on the same network.")
+ .arg(home.name)
+ }
+ }
+ }
+ Card {
+ width: parent.width
+ Column {
+ width: parent.width
+ spacing: 12
+ Txt { text: qsTr("This PC"); role: "label"; muted: true }
+ Txt { width: parent.width; text: AppController.deviceName; role: "title" }
+ Txt {
+ width: parent.width
+ role: "bodySmall"
+ muted: true
+ text: qsTr("Paired with %1 since %2")
+ .arg(home.name)
+ .arg(new Date(home.pairedAt * 1000).toLocaleDateString(Qt.locale(), Locale.ShortFormat))
+ wrapMode: Text.WordWrap
+ }
+ Button {
+ variant: "tonal"
+ size: "sm"
+ iconPath: Icons.plus
+ text: qsTr("Pair another device")
+ onClicked: page.pairRequested()
+ }
+ }
+ }
+ }
+ }
+
+ // A quick action. Unavailable actions are dimmed and say what unlocks them.
+ component ActionTile: Rectangle {
+ id: tile
+ property string title
+ property string subtitle
+ property string iconPath
+ property var feature: ({})
+ property bool active: false
+ // False until this PC implements the action (shown as coming soon).
+ property bool ready: true
+ signal clicked
+
+ readonly property bool available: feature.state === "available" && ready
+
+ height: 108
+ radius: Theme.radiusLg
+ color: tile.active ? Theme.primary : Theme.tileColor
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+ scale: tap.pressed && available ? Theme.pressScale : 1
+ Behavior on scale { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }
+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }
+ transform: Translate {
+ y: hover.hovered && tile.available && !tap.pressed ? -Theme.hoverLift : 0
+ Behavior on y { SpringAnimation { spring: Theme.springSnappy; damping: Theme.dampingSnappy } }
+ }
+
+ Accessible.role: Accessible.Button
+ Accessible.name: title
+ Accessible.description: available ? subtitle : lock.label
+ Accessible.onPressAction: if (tile.available) tile.clicked()
+
+ readonly property color ink: tile.active ? Theme.primaryContent : Theme.surfaceContent
+ Column {
+ anchors.fill: parent
+ anchors.margins: 14
+ spacing: 12
+ Rectangle {
+ width: 36; height: 36
+ radius: Theme.graphite ? Theme.radiusSm : Theme.radiusMd
+ color: tile.active ? Qt.rgba(1, 1, 1, 0.18) : (Theme.graphite ? "transparent" : Theme.secondaryContainer)
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+ opacity: tile.available ? 1 : 0.55
+ Icon {
+ anchors.centerIn: parent
+ path: tile.iconPath
+ color: tile.active ? Theme.primaryContent : Theme.secondaryContainerContent
+ }
+ }
+ Column {
+ width: parent.width
+ spacing: 3
+ Txt { width: parent.width; text: tile.title; role: "title"; size: 14; color: tile.ink; opacity: tile.available ? 1 : 0.6 }
+ Txt { width: parent.width; visible: tile.available; text: tile.subtitle; role: "bodySmall"; color: tile.ink; opacity: 0.75 }
+ // Not built yet, or capabilities unknown until the device has
+ // connected once.
+ Txt {
+ width: parent.width
+ visible: !tile.available && !lock.visible
+ text: tile.ready ? qsTr("When connected") : qsTr("Coming soon")
+ role: "bodySmall"
+ muted: true
+ }
+ LockChip { id: lock; visible: tile.ready && !tile.available && label.length > 0; feature: tile.feature }
+ }
+ }
+ HoverHandler { id: hover; cursorShape: tile.available ? Qt.PointingHandCursor : Qt.ArrowCursor }
+ TapHandler { id: tap; enabled: tile.available; onTapped: tile.clicked() }
+ }
+}
diff --git a/desktop/app/qml/pages/PairingPanel.qml b/desktop/app/qml/pages/PairingPanel.qml
new file mode 100644
index 0000000..95ee842
--- /dev/null
+++ b/desktop/app/qml/pages/PairingPanel.qml
@@ -0,0 +1,276 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// Pairing a phone: a QR code to scan (refreshed automatically), nearby
+// pairing with a 6-digit code check, and the outcome. While `running`, this
+// PC is in pairing mode.
+Item {
+ id: panel
+ property bool running: false
+ // Show "Cancel" (in a dialog) or not (first run).
+ property bool cancellable: true
+ signal finished
+ signal cancelled
+
+ property bool showNearby: false
+ readonly property string state_: Pairing.state
+
+ implicitHeight: content.implicitHeight
+
+ onRunningChanged: {
+ showNearby = false
+ if (running)
+ Pairing.start()
+ }
+ Component.onCompleted: if (running) Pairing.start()
+
+ // Leave the success message up briefly, then close.
+ Timer {
+ interval: 1400
+ running: panel.state_ === "paired" && panel.running
+ onTriggered: panel.finished()
+ }
+
+ // Seconds left on the current code, for the "refreshes in" hint.
+ property int secondsLeft: 0
+ Timer {
+ interval: 1000
+ repeat: true
+ triggeredOnStart: true
+ running: panel.running && panel.state_ === "hosting"
+ onTriggered: panel.secondsLeft = Math.max(0, Math.round((Pairing.expiresAt - Date.now()) / 1000))
+ }
+
+ Column {
+ id: content
+ width: parent.width
+ spacing: 18
+
+ // ---- Header ----
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ role: "displaySmall"
+ size: 26
+ wrapMode: Text.WordWrap
+ text: {
+ switch (panel.state_) {
+ case "comparing": return qsTr("Check the code")
+ case "paired": return qsTr("Paired")
+ case "failed": return qsTr("Pairing didn't work")
+ default: return panel.showNearby ? qsTr("Pair nearby") : qsTr("Scan with your phone")
+ }
+ }
+ }
+
+ // ---- QR code ----
+ Column {
+ width: parent.width
+ spacing: 14
+ visible: (panel.state_ === "hosting" || panel.state_ === "starting" || panel.state_ === "idle") && !panel.showNearby
+
+ Item {
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: 236; height: 236
+ QrCode {
+ anchors.fill: parent
+ visible: panel.state_ === "hosting"
+ path: Pairing.qrPath
+ modules: Pairing.qrSize
+ Accessible.role: Accessible.Graphic
+ Accessible.name: qsTr("Pairing QR code")
+ }
+ Spinner {
+ anchors.centerIn: parent
+ visible: panel.state_ !== "hosting"
+ width: 28; height: 28
+ }
+ }
+ Row {
+ anchors.horizontalCenter: parent.horizontalCenter
+ spacing: 14
+ Repeater {
+ model: [qsTr("Install Nectarlink"), qsTr("Tap “Pair with PC”"), qsTr("Scan this code")]
+ delegate: Row {
+ required property int index
+ required property string modelData
+ spacing: 6
+ Rectangle {
+ width: 20; height: 20; radius: Theme.graphite ? Theme.radiusXs : 10
+ color: Theme.graphite ? "transparent" : Theme.secondaryContainer
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+ Txt { anchors.centerIn: parent; text: index + 1; role: "caption"; font.weight: 700 }
+ }
+ Txt { anchors.verticalCenter: parent.verticalCenter; text: modelData; role: "bodySmall"; muted: true }
+ }
+ }
+ }
+ Txt {
+ anchors.horizontalCenter: parent.horizontalCenter
+ role: "caption"
+ muted: true
+ visible: panel.state_ === "hosting"
+ text: qsTr("Code refreshes in %1:%2 · Works on this network")
+ .arg(Math.floor(panel.secondsLeft / 60)).arg(("0" + panel.secondsLeft % 60).slice(-2))
+ }
+ Button {
+ anchors.horizontalCenter: parent.horizontalCenter
+ variant: "tonal"
+ size: "sm"
+ iconPath: Icons.wifi
+ text: qsTr("Pair nearby instead")
+ onClicked: panel.showNearby = true
+ }
+ }
+
+ // ---- Nearby devices ----
+ Column {
+ width: parent.width
+ spacing: 10
+ visible: panel.showNearby && (panel.state_ === "hosting" || panel.state_ === "starting")
+
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ role: "body"
+ muted: true
+ text: qsTr("On your phone, open Nectarlink and choose “Pair nearby”. It shows up here.")
+ }
+ Repeater {
+ model: Pairing.nearby
+ delegate: Rectangle {
+ required property var modelData
+ width: parent.width
+ height: 56
+ radius: Theme.radiusMd
+ color: Theme.tileColor
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+ Avatar {
+ id: deviceIcon
+ anchors.left: parent.left; anchors.leftMargin: 12
+ anchors.verticalCenter: parent.verticalCenter
+ iconPath: Icons.phone
+ }
+ Txt {
+ anchors.left: deviceIcon.right; anchors.leftMargin: 12
+ anchors.right: pairButton.left; anchors.rightMargin: 12
+ anchors.verticalCenter: parent.verticalCenter
+ text: modelData.name
+ role: "title"
+ }
+ Button {
+ id: pairButton
+ anchors.right: parent.right; anchors.rightMargin: 10
+ anchors.verticalCenter: parent.verticalCenter
+ size: "sm"
+ text: qsTr("Pair")
+ onClicked: Pairing.pairNearby(modelData.id)
+ }
+ }
+ }
+ Row {
+ anchors.horizontalCenter: parent.horizontalCenter
+ spacing: 8
+ visible: Pairing.nearby.length === 0
+ Spinner { width: 16; height: 16; anchors.verticalCenter: parent.verticalCenter }
+ Txt { text: qsTr("Looking for devices…"); role: "bodySmall"; muted: true }
+ }
+ Button {
+ anchors.horizontalCenter: parent.horizontalCenter
+ variant: "text"
+ size: "sm"
+ text: qsTr("Show the QR code")
+ onClicked: panel.showNearby = false
+ }
+ }
+
+ // ---- Working ----
+ Row {
+ anchors.horizontalCenter: parent.horizontalCenter
+ spacing: 10
+ visible: panel.state_ === "connecting" || panel.state_ === "confirmed"
+ Spinner { width: 18; height: 18; anchors.verticalCenter: parent.verticalCenter }
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ role: "body"
+ text: panel.state_ === "connecting"
+ ? qsTr("Connecting to %1…").arg(Pairing.peerName)
+ : qsTr("Waiting for %1…").arg(Pairing.peerName)
+ }
+ }
+
+ // ---- Code check ----
+ Column {
+ width: parent.width
+ spacing: 16
+ visible: panel.state_ === "comparing" || panel.state_ === "confirmed"
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ role: "body"
+ muted: true
+ text: qsTr("Make sure %1 shows the same code. This keeps anyone else from pairing in between.")
+ .arg(Pairing.peerName.length > 0 ? Pairing.peerName : qsTr("your phone"))
+ }
+ CodeDigits { anchors.horizontalCenter: parent.horizontalCenter; code: Pairing.code }
+ Row {
+ anchors.horizontalCenter: parent.horizontalCenter
+ spacing: 10
+ visible: panel.state_ === "comparing"
+ Button { variant: "outline"; text: qsTr("They don't match"); onClicked: Pairing.confirm(false) }
+ Button { text: qsTr("Codes match"); onClicked: Pairing.confirm(true) }
+ }
+ }
+
+ // ---- Outcome ----
+ Column {
+ width: parent.width
+ spacing: 12
+ visible: panel.state_ === "paired" || panel.state_ === "failed"
+ Avatar {
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: 56; height: 56
+ emphasized: panel.state_ === "paired"
+ iconPath: panel.state_ === "paired" ? Icons.check : Icons.warning
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ role: "body"
+ muted: panel.state_ === "failed"
+ text: {
+ if (panel.state_ === "paired")
+ return qsTr("%1 is paired with this PC.").arg(Pairing.peerName)
+ switch (Pairing.failure) {
+ case "rejected": return qsTr("The codes didn't match, so nothing was paired. Try again.")
+ case "declined": return qsTr("Pairing was declined on one of the devices.")
+ case "unreachable": return qsTr("Couldn't reach the phone. Make sure both devices are on the same network.")
+ case "expired": return qsTr("The code expired.")
+ default: return qsTr("Something went wrong. Try again.")
+ }
+ }
+ }
+ Button {
+ anchors.horizontalCenter: parent.horizontalCenter
+ visible: panel.state_ === "failed"
+ text: qsTr("Try again")
+ iconPath: Icons.refresh
+ onClicked: { panel.showNearby = false; Pairing.start() }
+ }
+ }
+
+ Button {
+ anchors.horizontalCenter: parent.horizontalCenter
+ visible: panel.cancellable && panel.state_ !== "paired"
+ variant: "text"
+ text: qsTr("Cancel")
+ onClicked: panel.cancelled()
+ }
+ }
+}
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
new file mode 100644
index 0000000..c2928f8
--- /dev/null
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -0,0 +1,272 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// Settings: appearance, behavior, paired devices and what they may do, and
+// details for support.
+Item {
+ id: page
+ property bool active: false
+ signal pairRequested
+
+ opacity: active ? 1 : 0
+ visible: opacity > 0
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }
+ transform: Translate {
+ y: page.active || Theme.reduceMotion ? 0 : 12
+ Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }
+ }
+
+ readonly property var toggleNames: ({
+ notifications: qsTr("Notifications"),
+ messages: qsTr("Messages"),
+ calls: qsTr("Calls"),
+ clipboard: qsTr("Clipboard"),
+ photos: qsTr("Photos"),
+ pc_actions: qsTr("Lock and sleep this PC"),
+ remote_files: qsTr("Browse this PC's files while away")
+ })
+
+ Flickable {
+ anchors.fill: parent
+ contentHeight: column.height + Theme.contentPadding * 2
+ boundsBehavior: Flickable.StopAtBounds
+ clip: true
+
+ Column {
+ id: column
+ x: Theme.contentPadding
+ y: Theme.contentPadding
+ width: Math.min(720, parent.width - Theme.contentPadding * 2)
+ spacing: Theme.gutter
+
+ // ---- Appearance ----
+ Txt { text: qsTr("Appearance"); role: "label"; muted: true }
+ Card {
+ width: parent.width
+ Column {
+ width: parent.width
+ ListRow {
+ width: parent.width
+ iconPath: Icons.palette
+ title: qsTr("Theme")
+ description: qsTr("Bloom is soft and colorful; Graphite is ink on paper.")
+ Segmented {
+ options: [{ value: "bloom", label: qsTr("Bloom") }, { value: "graphite", label: qsTr("Graphite") }]
+ value: Preferences.theme
+ onPicked: (value) => Preferences.theme = value
+ }
+ }
+ Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.info
+ title: qsTr("Mode")
+ Segmented {
+ options: [
+ { value: "system", label: qsTr("System") },
+ { value: "light", label: qsTr("Light") },
+ { value: "dark", label: qsTr("Dark") }
+ ]
+ value: Preferences.colorMode
+ onPicked: (value) => Preferences.colorMode = value
+ }
+ }
+ Divider { width: parent.width; visible: !Theme.graphite }
+ ListRow {
+ width: parent.width
+ visible: !Theme.graphite
+ iconPath: Icons.sparkle
+ title: qsTr("Color")
+ Row {
+ spacing: 10
+ Repeater {
+ model: Object.keys(Tokens.data.themes.bloom.seeds)
+ delegate: Rectangle {
+ id: swatch
+ required property string modelData
+ readonly property bool selected: Theme.seed === modelData
+ width: 26; height: 26; radius: 13
+ color: Tokens.data.themes.bloom.seeds[modelData].seed
+ border.width: selected ? 2 : 0
+ border.color: Theme.surfaceContent
+ Accessible.role: Accessible.RadioButton
+ Accessible.name: modelData
+ Accessible.checked: selected
+ Accessible.onPressAction: Preferences.seed = modelData
+ HoverHandler { cursorShape: Qt.PointingHandCursor }
+ TapHandler { onTapped: Preferences.seed = swatch.modelData }
+ }
+ }
+ }
+ }
+ Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.desktop
+ title: qsTr("Mica backdrop")
+ description: qsTr("Let the desktop's colors show softly through the window.")
+ Toggle {
+ label: qsTr("Mica backdrop")
+ checked: Preferences.backdrop
+ onToggled: (on) => Preferences.backdrop = on
+ }
+ }
+ }
+ }
+
+ // ---- Behavior ----
+ Txt { text: qsTr("Behavior"); role: "label"; muted: true }
+ Card {
+ width: parent.width
+ ListRow {
+ width: parent.width
+ iconPath: Icons.power
+ title: qsTr("Keep running when the window is closed")
+ description: qsTr("Nectarlink stays in the notification area so your phone can reach this PC.")
+ Toggle {
+ label: qsTr("Keep running when the window is closed")
+ checked: Preferences.closeToTray
+ onToggled: (on) => Preferences.closeToTray = on
+ }
+ }
+ }
+
+ // ---- Devices ----
+ Row {
+ width: parent.width
+ Txt { text: qsTr("Devices"); role: "label"; muted: true; anchors.verticalCenter: parent.verticalCenter }
+ }
+ Repeater {
+ model: DeviceList
+ delegate: Card {
+ id: deviceCard
+ required property string deviceId
+ required property string name
+ required property bool online
+ width: column.width
+
+ // Re-read when toggles (and so capabilities) change.
+ readonly property var toggles: AppController.capsRevision >= 0 && AppController.togglesRevision >= 0
+ ? AppController.deviceToggles(deviceId) : []
+
+ Column {
+ width: parent.width
+ spacing: 4
+ Row {
+ width: parent.width
+ spacing: 12
+ Avatar { iconPath: Icons.phone; emphasized: deviceCard.online }
+ Column {
+ anchors.verticalCenter: parent.verticalCenter
+ width: parent.width - 36 - 12 - unpair.width - 12
+ Txt { width: parent.width; text: deviceCard.name; role: "title" }
+ Txt {
+ text: deviceCard.online ? qsTr("Connected") : qsTr("Not connected")
+ role: "bodySmall"
+ muted: true
+ }
+ }
+ Button {
+ id: unpair
+ anchors.verticalCenter: parent.verticalCenter
+ variant: "outline"
+ size: "sm"
+ iconPath: Icons.unlink
+ text: qsTr("Unpair")
+ onClicked: {
+ unpairSheet.deviceId = deviceCard.deviceId
+ unpairSheet.deviceName = deviceCard.name
+ unpairSheet.open()
+ }
+ }
+ }
+ Item { width: 1; height: 8 }
+ Repeater {
+ model: deviceCard.toggles
+ delegate: ListRow {
+ required property var modelData
+ width: parent.width
+ title: page.toggleNames[modelData.name] || modelData.name
+ Toggle {
+ label: page.toggleNames[modelData.name] || modelData.name
+ checked: modelData.on
+ onToggled: (on) => AppController.setDeviceToggle(deviceCard.deviceId, modelData.name, on)
+ }
+ }
+ }
+ }
+ }
+ }
+ Button {
+ variant: "tonal"
+ iconPath: Icons.plus
+ text: qsTr("Pair a new device")
+ onClicked: page.pairRequested()
+ }
+
+ // ---- About ----
+ Txt { text: qsTr("About"); role: "label"; muted: true }
+ Card {
+ width: parent.width
+ Column {
+ width: parent.width
+ spacing: 8
+ Txt { text: qsTr("Nectarlink %1").arg(AppController.version); role: "title" }
+ Txt { text: qsTr("This PC: %1").arg(AppController.deviceName); role: "bodySmall"; muted: true }
+ TextEdit {
+ width: parent.width
+ readOnly: true
+ selectByMouse: true
+ wrapMode: TextEdit.WrapAnywhere
+ text: AppController.deviceId
+ color: Theme.surfaceContentVariant
+ selectionColor: Theme.primaryContainer
+ selectedTextColor: Theme.primaryContainerContent
+ font.family: Theme.fontMono
+ font.pixelSize: 12
+ Accessible.name: qsTr("Device ID")
+ }
+ Button {
+ variant: "outline"
+ size: "sm"
+ iconPath: Icons.folder
+ text: qsTr("Open the logs folder")
+ onClicked: Qt.openUrlExternally(AppController.logsUrl())
+ }
+ }
+ }
+ }
+ }
+
+ Sheet {
+ id: unpairSheet
+ property string deviceId
+ property string deviceName
+ cardWidth: 400
+ Column {
+ width: parent.width
+ spacing: 16
+ Txt { width: parent.width; text: qsTr("Unpair %1?").arg(unpairSheet.deviceName); role: "headline"; wrapMode: Text.WordWrap }
+ Txt {
+ width: parent.width
+ wrapMode: Text.WordWrap
+ role: "body"
+ muted: true
+ text: qsTr("Both devices forget each other. You can pair them again any time.")
+ }
+ Row {
+ anchors.right: parent.right
+ spacing: 10
+ Button { variant: "text"; text: qsTr("Cancel"); onClicked: unpairSheet.close() }
+ Button {
+ text: qsTr("Unpair")
+ onClicked: {
+ AppController.unpair(unpairSheet.deviceId)
+ unpairSheet.close()
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/desktop/app/qml/pages/WelcomePage.qml b/desktop/app/qml/pages/WelcomePage.qml
new file mode 100644
index 0000000..8c5fc99
--- /dev/null
+++ b/desktop/app/qml/pages/WelcomePage.qml
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// First run: pair a phone. Also covers the moment before the core is ready
+// and the (rare) case where it failed to start.
+Item {
+ id: page
+
+ readonly property string status: AppController.status
+
+ Column {
+ anchors.centerIn: parent
+ width: Math.min(460, parent.width - 48)
+ spacing: 22
+
+ Rectangle {
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: 52; height: 52
+ radius: Theme.radiusMd
+ color: Theme.graphite ? Theme.surfaceContent : Theme.primary
+ Icon {
+ anchors.centerIn: parent
+ width: 26; height: 26
+ path: Icons.mark
+ color: Theme.graphite ? Theme.surface : Theme.primaryContent
+ }
+ }
+ Column {
+ width: parent.width
+ spacing: 6
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ text: qsTr("Welcome to Nectarlink")
+ role: "displaySmall"
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ role: "body"
+ muted: true
+ text: page.status === "failed"
+ ? qsTr("Nectarlink couldn't start.")
+ : qsTr("Your phone and this PC, together. Pair once and they find each other from then on.")
+ }
+ }
+
+ Card {
+ width: parent.width
+ padding: 24
+ visible: page.status === "ready"
+ PairingPanel {
+ width: parent.width
+ cancellable: false
+ running: page.visible && page.status === "ready"
+ }
+ }
+
+ Spinner {
+ anchors.horizontalCenter: parent.horizontalCenter
+ visible: page.status === "starting"
+ width: 28; height: 28
+ }
+
+ Column {
+ width: parent.width
+ spacing: 12
+ visible: page.status === "failed"
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ role: "code"
+ size: 12
+ muted: true
+ text: AppController.error
+ }
+ Button {
+ anchors.horizontalCenter: parent.horizontalCenter
+ variant: "tonal"
+ iconPath: Icons.folder
+ text: qsTr("Open the logs folder")
+ onClicked: Qt.openUrlExternally(AppController.logsUrl())
+ }
+ }
+ }
+}
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
new file mode 100644
index 0000000..ffffa10
--- /dev/null
+++ b/desktop/app/src/bridge/app.rs
@@ -0,0 +1,384 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `AppController`: app-wide state and commands for QML (core status, this
+//! PC, capabilities, ringing, appearance) plus the tray icon.
+
+use std::{
+ pin::Pin,
+ sync::{Mutex, OnceLock},
+};
+
+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 crate::{
+ core_host,
+ state::{Changes, CoreStatus},
+ win::{self, sound, tray},
+};
+
+#[cxx_qt::bridge]
+pub mod qobject {
+ unsafe extern "C++" {
+ include!("cxx-qt-lib/qstring.h");
+ type QString = cxx_qt_lib::QString;
+ include!("cxx-qt-lib/qmap.h");
+ type QMap_QString_QVariant = cxx_qt_lib::QMap<cxx_qt_lib::QMapPair_QString_QVariant>;
+ include!("cxx-qt-lib/qlist.h");
+ type QList_QVariant = cxx_qt_lib::QList<cxx_qt_lib::QVariant>;
+ }
+
+ #[auto_cxx_name]
+ unsafe extern "RustQt" {
+ #[qobject]
+ #[qml_element]
+ #[qml_singleton]
+ /// "starting", "ready" or "failed".
+ #[qproperty(QString, status)]
+ #[qproperty(QString, error)]
+ /// This PC's name and device ID, as phones see them.
+ #[qproperty(QString, device_name)]
+ #[qproperty(QString, device_id)]
+ #[qproperty(bool, has_devices)]
+ /// Bumped whenever any capability matrix changes, so bindings that
+ /// call `featureState` re-evaluate.
+ #[qproperty(i32, caps_revision)]
+ /// Bumped when a device toggle is changed from this PC.
+ #[qproperty(i32, toggles_revision)]
+ /// Name of the device making this PC ring ("" when not ringing).
+ #[qproperty(QString, ringing_from)]
+ #[qproperty(bool, system_dark)]
+ #[qproperty(bool, reduce_motion)]
+ #[qproperty(QString, version)]
+ type AppController = super::AppControllerRust;
+
+ /// Asks a paired device to ring (or stop).
+ #[qinvokable]
+ fn ring(self: Pin<&mut AppController>, device: &QString, on: bool);
+ /// Stops this PC ringing.
+ #[qinvokable]
+ fn stop_ringing(self: Pin<&mut AppController>);
+ #[qinvokable]
+ fn unpair(self: Pin<&mut AppController>, device: &QString);
+
+ /// `{ state, limit, action, target, minutes, reason }` for a feature
+ /// of a device (see docs/architecture/capabilities.md).
+ #[qinvokable]
+ fn feature_state(self: &AppController, device: &QString, feature: &QString) -> QMap_QString_QVariant;
+ /// `[{ name, on }]`: what the user allows this device to do.
+ #[qinvokable]
+ fn device_toggles(self: &AppController, device: &QString) -> QList_QVariant;
+ #[qinvokable]
+ fn set_device_toggle(self: Pin<&mut AppController>, device: &QString, name: &QString, on: bool);
+
+ /// The folder with the app's logs, as a file URL.
+ #[qinvokable]
+ fn logs_url(self: &AppController) -> QString;
+
+ /// A short message for the user (e.g. a command failed).
+ #[qsignal]
+ fn toast(self: Pin<&mut AppController>, message: QString);
+ /// Show the main window (tray click, second launch).
+ #[qsignal]
+ fn activate_requested(self: Pin<&mut AppController>);
+ /// The user chose Quit in the tray.
+ #[qsignal]
+ fn quit_requested(self: Pin<&mut AppController>);
+ }
+
+ impl cxx_qt::Threading for AppController {}
+ impl cxx_qt::Initialize for AppController {}
+}
+
+#[derive(Default)]
+pub struct AppControllerRust {
+ status: QString,
+ error: QString,
+ device_name: QString,
+ device_id: QString,
+ has_devices: bool,
+ caps_revision: i32,
+ toggles_revision: i32,
+ ringing_from: QString,
+ system_dark: bool,
+ reduce_motion: bool,
+ version: QString,
+ tray: Option<tray::Tray>,
+}
+
+/// The controller's thread handle, so other threads (second launch) can
+/// reach it.
+static CONTROLLER: OnceLock<Mutex<Option<CxxQtThread<qobject::AppController>>>> = OnceLock::new();
+
+fn controller() -> Option<CxxQtThread<qobject::AppController>> {
+ CONTROLLER.get()?.lock().unwrap_or_else(|e| e.into_inner()).clone()
+}
+
+/// Asks the UI to show the main window (from any thread).
+pub fn request_activation() {
+ if let Some(qt) = controller() {
+ let _ = qt.queue(|object| object.activate_requested());
+ }
+}
+
+/// Shows a toast (from any thread).
+fn toast(message: impl Into<String>) {
+ let message = message.into();
+ if let Some(qt) = controller() {
+ let _ = qt.queue(move |object| object.toast(QString::from(&message)));
+ }
+}
+
+/// Explains a failed command in a sentence the user understands.
+fn describe(error: &Error) -> String {
+ match error {
+ Error::Offline => "The device isn't connected right now.".into(),
+ Error::NotPaired => "That device isn't paired anymore.".into(),
+ Error::Timeout => "The device didn't answer in time.".into(),
+ Error::Denied | Error::Declined => "The device declined.".into(),
+ Error::Unsupported => "The device's app doesn't support that yet.".into(),
+ other => format!("Something went wrong: {other}"),
+ }
+}
+
+impl cxx_qt::Initialize for qobject::AppController {
+ fn initialize(mut self: Pin<&mut Self>) {
+ self.as_mut().set_version(QString::from(env!("CARGO_PKG_VERSION")));
+ self.as_mut().refresh_appearance();
+ let qt = self.qt_thread();
+ *CONTROLLER.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner()) = Some(qt.clone());
+ super::subscribe(
+ qt.clone(),
+ Changes::STATUS | Changes::DEVICES | Changes::CAPABILITIES | Changes::RINGING,
+ Self::refresh,
+ );
+
+ let labels = tray::MenuLabels {
+ open: "Open Nectarlink".into(),
+ find_phone: "Find my phone".into(),
+ quit: "Quit Nectarlink".into(),
+ };
+ match tray::Tray::create("Nectarlink", labels, move |event| on_tray_event(&qt, event)) {
+ Ok(tray) => self.rust_mut().tray = Some(tray),
+ Err(e) => tracing::warn!(error = %e, "no tray icon"),
+ }
+ }
+}
+
+fn on_tray_event(qt: &CxxQtThread<qobject::AppController>, event: tray::TrayEvent) {
+ match event {
+ tray::TrayEvent::Open => {
+ let _ = qt.queue(|object| object.activate_requested());
+ }
+ tray::TrayEvent::Quit => {
+ let _ = qt.queue(|object| object.quit_requested());
+ }
+ tray::TrayEvent::FindPhone => {
+ let phone = core_host::host().hub.read(|s| {
+ s.devices
+ .iter()
+ .find(|d| matches!(d.link, LinkState::Online { .. }))
+ .or(s.devices.first())
+ .map(|d| d.id)
+ });
+ if let Some(phone) = phone {
+ ring_device(phone, true);
+ }
+ }
+ tray::TrayEvent::Resumed => {
+ tracing::info!("resumed from sleep; reconnecting");
+ if let Some(node) = core_host::node() {
+ core_host::spawn(async move { node.network_changed().await });
+ }
+ }
+ tray::TrayEvent::AppearanceChanged => {
+ let _ = qt.queue(|object| object.refresh_appearance());
+ }
+ }
+}
+
+fn ring_device(device: DeviceId, on: bool) {
+ let Some(node) = core_host::node() else { return };
+ core_host::spawn(async move {
+ if let Err(e) = node.ring(device, on).await {
+ toast(describe(&e));
+ }
+ });
+}
+
+impl qobject::AppController {
+ fn refresh(mut self: Pin<&mut Self>) {
+ let hub = &core_host::host().hub;
+ let (status, devices, ringing, online, caps_version) = hub.read(|s| {
+ let ringing = s.ringing_from.and_then(|id| s.name_of(&id)).unwrap_or_default();
+ let online = s.devices.iter().filter(|d| matches!(d.link, LinkState::Online { .. })).count();
+ (s.core_status(), s.devices.len(), ringing, online, s.matrices_version)
+ });
+ let (status_text, error) = match &status {
+ CoreStatus::Starting => ("starting", String::new()),
+ CoreStatus::Ready { device_id, name } => {
+ self.as_mut().set_device_name(QString::from(name));
+ self.as_mut().set_device_id(QString::from(&device_id.to_string()));
+ ("ready", String::new())
+ }
+ CoreStatus::Failed(message) => ("failed", message.clone()),
+ };
+ self.as_mut().set_status(QString::from(status_text));
+ self.as_mut().set_error(QString::from(&error));
+ self.as_mut().set_has_devices(devices > 0);
+ self.as_mut().set_ringing_from(QString::from(&ringing));
+ // Truncation is fine: QML only compares revisions for equality.
+ self.as_mut().set_caps_revision(caps_version as i32);
+
+ if let Some(tray) = self.rust().tray.as_ref() {
+ tray.set_find_phone_enabled(devices > 0);
+ tray.set_tooltip(&match (devices, online) {
+ (0, _) => "Nectarlink · no devices paired".to_owned(),
+ (_, 0) => "Nectarlink · not connected".to_owned(),
+ (_, 1) => "Nectarlink · 1 device connected".to_owned(),
+ (_, n) => format!("Nectarlink · {n} devices connected"),
+ });
+ }
+ }
+
+ fn refresh_appearance(mut self: Pin<&mut Self>) {
+ self.as_mut().set_system_dark(win::system_dark());
+ self.as_mut().set_reduce_motion(win::reduce_motion());
+ }
+
+ pub fn ring(self: Pin<&mut Self>, device: &QString, on: bool) {
+ if let Some(id) = super::parse_device(device) {
+ ring_device(id, on);
+ }
+ }
+
+ pub fn stop_ringing(self: Pin<&mut Self>) {
+ sound::stop_ringing();
+ core_host::host()
+ .hub
+ .update(|s| if s.ringing_from.take().is_some() { Changes::RINGING } else { Changes::NONE });
+ }
+
+ pub fn unpair(self: Pin<&mut Self>, device: &QString) {
+ let (Some(id), Some(node)) = (super::parse_device(device), core_host::node()) else { return };
+ core_host::spawn(async move {
+ if let Err(e) = node.unpair(id).await {
+ toast(describe(&e));
+ }
+ });
+ }
+
+ pub fn feature_state(&self, device: &QString, feature: &QString) -> QMap<QMapPair_QString_QVariant> {
+ let feature = String::from(feature);
+ let state = super::parse_device(device).and_then(|id| {
+ core_host::host().hub.read(|s| s.matrices.get(&id).and_then(|m| m.state(&feature)))
+ });
+ feature_state_map(state)
+ }
+
+ pub fn device_toggles(&self, device: &QString) -> QList<QVariant> {
+ let mut list = QList::default();
+ let (Some(id), Some(node)) = (super::parse_device(device), core_host::node()) else { return list };
+ for (name, on) in node.device_toggles(id).unwrap_or_default() {
+ let mut item = QHash::<QHashPair_QString_QVariant>::default();
+ item.insert(QString::from("name"), QVariant::from(&QString::from(name)));
+ item.insert(QString::from("on"), QVariant::from(&on));
+ list.append(QVariant::from(&item));
+ }
+ list
+ }
+
+ pub fn set_device_toggle(mut self: Pin<&mut Self>, device: &QString, name: &QString, on: bool) {
+ let (Some(id), Some(node)) = (super::parse_device(device), core_host::node()) else { return };
+ if let Err(e) = node.set_device_toggle(id, &String::from(name), on) {
+ toast(describe(&e));
+ }
+ let revision = self.toggles_revision.wrapping_add(1);
+ self.as_mut().set_toggles_revision(revision);
+ }
+
+ pub fn logs_url(&self) -> QString {
+ let dir = crate::logging::logs_dir(&core_host::host().data_dir);
+ QString::from(&format!("file:///{}", dir.to_string_lossy().replace('\\', "/")))
+ }
+}
+
+impl Drop for AppControllerRust {
+ fn drop(&mut self) {
+ if let Some(cell) = CONTROLLER.get() {
+ *cell.lock().unwrap_or_else(|e| e.into_inner()) = None;
+ }
+ }
+}
+
+/// Flattens a feature state for QML.
+fn feature_state_map(state: Option<FeatureState>) -> QMap<QMapPair_QString_QVariant> {
+ let mut map = QMap::<QMapPair_QString_QVariant>::default();
+ 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);
+ put("action", text(action));
+ put("target", text(&target));
+ put(
+ "minutes",
+ QVariant::from(&match upgrade.effort {
+ Effort::Instant => 0i32,
+ Effort::Minutes(m) => i32::from(m),
+ }),
+ );
+ };
+ match state {
+ None => put("state", text("unknown")),
+ Some(FeatureState::Available) => put("state", text("available")),
+ Some(FeatureState::Partial { limit, upgrade }) => {
+ put("state", text("partial"));
+ put("limit", text(limit));
+ if let Some(upgrade) = upgrade {
+ upgrade_fields(&mut put, &upgrade);
+ }
+ }
+ Some(FeatureState::Locked { upgrade }) => {
+ put("state", text("locked"));
+ upgrade_fields(&mut put, &upgrade);
+ }
+ 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));
+ }
+ }
+ 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()),
+ }
+}
diff --git a/desktop/app/src/bridge/devices.rs b/desktop/app/src/bridge/devices.rs
new file mode 100644
index 0000000..98b3fd4
--- /dev/null
+++ b/desktop/app/src/bridge/devices.rs
@@ -0,0 +1,364 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `DeviceList`: the paired devices as a Qt list model, updated in place
+//! (insert, remove, change) so QML delegates keep their state and animate.
+
+use std::pin::Pin;
+
+use cxx_qt::{CxxQtType, Threading};
+use cxx_qt_lib::{QByteArray, QHash, QHashPair_i32_QByteArray, QList, QModelIndex, QString, QVariant};
+use nectarlink_core::{ConnectionPath, DeviceKind, LinkState, PowerLevel};
+
+use crate::{
+ core_host,
+ state::{Changes, DeviceView},
+};
+
+#[cxx_qt::bridge]
+pub mod qobject {
+ unsafe extern "C++" {
+ include!(<QtCore/QAbstractListModel>);
+ type QAbstractListModel;
+
+ include!("cxx-qt-lib/qmodelindex.h");
+ type QModelIndex = cxx_qt_lib::QModelIndex;
+ include!("cxx-qt-lib/qvariant.h");
+ type QVariant = cxx_qt_lib::QVariant;
+ include!("cxx-qt-lib/qhash.h");
+ type QHash_i32_QByteArray = cxx_qt_lib::QHash<cxx_qt_lib::QHashPair_i32_QByteArray>;
+ include!("cxx-qt-lib/qlist.h");
+ type QList_i32 = cxx_qt_lib::QList<i32>;
+ }
+
+ unsafe extern "RustQt" {
+ #[qobject]
+ #[base = QAbstractListModel]
+ #[qml_element]
+ #[qml_singleton]
+ #[qproperty(i32, count)]
+ type DeviceList = super::DeviceListRust;
+ }
+
+ // Inherited from QAbstractListModel.
+ unsafe extern "RustQt" {
+ #[inherit]
+ #[cxx_name = "beginInsertRows"]
+ unsafe fn begin_insert_rows(self: Pin<&mut DeviceList>, parent: &QModelIndex, first: i32, last: i32);
+ #[inherit]
+ #[cxx_name = "endInsertRows"]
+ unsafe fn end_insert_rows(self: Pin<&mut DeviceList>);
+ #[inherit]
+ #[cxx_name = "beginRemoveRows"]
+ unsafe fn begin_remove_rows(self: Pin<&mut DeviceList>, parent: &QModelIndex, first: i32, last: i32);
+ #[inherit]
+ #[cxx_name = "endRemoveRows"]
+ unsafe fn end_remove_rows(self: Pin<&mut DeviceList>);
+ #[inherit]
+ #[cxx_name = "beginResetModel"]
+ unsafe fn begin_reset_model(self: Pin<&mut DeviceList>);
+ #[inherit]
+ #[cxx_name = "endResetModel"]
+ unsafe fn end_reset_model(self: Pin<&mut DeviceList>);
+ #[inherit]
+ fn index(self: &DeviceList, row: i32, column: i32, parent: &QModelIndex) -> QModelIndex;
+
+ #[inherit]
+ #[qsignal]
+ #[cxx_name = "dataChanged"]
+ fn data_changed(
+ self: Pin<&mut DeviceList>,
+ top_left: &QModelIndex,
+ bottom_right: &QModelIndex,
+ roles: &QList_i32,
+ );
+ }
+
+ unsafe extern "RustQt" {
+ #[qinvokable]
+ #[cxx_override]
+ fn data(self: &DeviceList, index: &QModelIndex, role: i32) -> QVariant;
+ #[qinvokable]
+ #[cxx_override]
+ #[cxx_name = "roleNames"]
+ fn role_names(self: &DeviceList) -> QHash_i32_QByteArray;
+ #[qinvokable]
+ #[cxx_override]
+ #[cxx_name = "rowCount"]
+ fn row_count(self: &DeviceList, parent: &QModelIndex) -> i32;
+ /// The row of a device ID, or -1.
+ #[qinvokable]
+ #[cxx_name = "rowOf"]
+ fn row_of(self: &DeviceList, device_id: &QString) -> i32;
+ }
+
+ unsafe extern "C++" {
+ include!("cxx-qt-lib/qstring.h");
+ type QString = cxx_qt_lib::QString;
+ }
+
+ impl cxx_qt::Threading for DeviceList {}
+ impl cxx_qt::Initialize for DeviceList {}
+}
+
+#[derive(Default)]
+pub struct DeviceListRust {
+ count: i32,
+ rows: Vec<DeviceView>,
+}
+
+/// Model roles (Qt::UserRole + n).
+const ROLES: &[&str] = &[
+ "deviceId",
+ "name",
+ "kind",
+ "os",
+ "osVersion",
+ "model",
+ "online",
+ "path",
+ "rttMs",
+ "battery",
+ "charging",
+ "power",
+ "lastSeen",
+ "pairedAt",
+ "accent",
+];
+const USER_ROLE: i32 = 0x0100;
+
+fn role_value(device: &DeviceView, role: &str) -> QVariant {
+ let text = |s: &str| QVariant::from(&QString::from(s));
+ match role {
+ "deviceId" => text(&device.id.to_string()),
+ "name" => text(&device.info.name),
+ "kind" => text(match device.info.kind {
+ DeviceKind::Phone => "phone",
+ DeviceKind::Tablet => "tablet",
+ DeviceKind::Desktop => "desktop",
+ DeviceKind::Laptop => "laptop",
+ DeviceKind::Unknown => "unknown",
+ }),
+ "os" => text(&device.info.os),
+ "osVersion" => text(&device.info.os_ver),
+ "model" => text(device.info.model.as_deref().unwrap_or_default()),
+ "online" => QVariant::from(&matches!(device.link, LinkState::Online { .. })),
+ "path" => text(match device.link {
+ LinkState::Online { path: ConnectionPath::Lan, .. } => "lan",
+ LinkState::Online { path: ConnectionPath::Relay, .. } => "relay",
+ LinkState::Connecting => "connecting",
+ LinkState::Offline { .. } => "offline",
+ }),
+ "rttMs" => QVariant::from(&match device.link {
+ LinkState::Online { rtt_ms, .. } => i32::try_from(rtt_ms).unwrap_or(i32::MAX),
+ _ => -1,
+ }),
+ "battery" => QVariant::from(&device.battery.as_ref().map_or(-1, |b| i32::from(b.level))),
+ "charging" => QVariant::from(&device.battery.as_ref().is_some_and(|b| b.charging)),
+ "power" => text(match device.power {
+ PowerLevel::Assist => "assist",
+ PowerLevel::Elevated => "elevated",
+ PowerLevel::NotApplicable => "n/a",
+ PowerLevel::Basic | PowerLevel::Unknown => "basic",
+ }),
+ "lastSeen" => QVariant::from(&match device.link {
+ LinkState::Offline { last_seen: Some(at) } => at as f64,
+ _ => 0.0,
+ }),
+ "pairedAt" => QVariant::from(&(device.paired_at as f64)),
+ "accent" => {
+ text(&device.info.accent.map(|argb| format!("#{:06X}", argb & 0x00FF_FFFF)).unwrap_or_default())
+ }
+ _ => QVariant::default(),
+ }
+}
+
+impl cxx_qt::Initialize for qobject::DeviceList {
+ fn initialize(self: Pin<&mut Self>) {
+ super::subscribe(self.qt_thread(), Changes::DEVICES, Self::refresh);
+ }
+}
+
+impl qobject::DeviceList {
+ fn refresh(mut self: Pin<&mut Self>) {
+ let new = core_host::host().hub.read(|s| s.devices.clone());
+ let root = QModelIndex::default();
+ match diff(&self.rows, &new) {
+ None => {
+ // SAFETY: begin/end pairs are balanced around the swap.
+ unsafe {
+ self.as_mut().begin_reset_model();
+ self.as_mut().rust_mut().rows = new;
+ self.as_mut().end_reset_model();
+ }
+ }
+ Some(edits) => {
+ for edit in edits {
+ match edit {
+ Edit::Remove(row) => {
+ let r = row as i32;
+ // SAFETY: row exists; begin/end are balanced.
+ unsafe {
+ self.as_mut().begin_remove_rows(&root, r, r);
+ self.as_mut().rust_mut().rows.remove(row);
+ self.as_mut().end_remove_rows();
+ }
+ }
+ Edit::Insert(row) => {
+ let r = row as i32;
+ // SAFETY: row <= len; begin/end are balanced.
+ unsafe {
+ self.as_mut().begin_insert_rows(&root, r, r);
+ self.as_mut().rust_mut().rows.insert(row, new[row].clone());
+ self.as_mut().end_insert_rows();
+ }
+ }
+ Edit::Change(row) => {
+ self.as_mut().rust_mut().rows[row] = new[row].clone();
+ let index = self.index(row as i32, 0, &root);
+ self.as_mut().data_changed(&index, &index, &QList::default());
+ }
+ }
+ }
+ }
+ }
+ let count = self.rows.len() as i32;
+ self.set_count(count);
+ }
+
+ pub fn data(&self, index: &QModelIndex, role: i32) -> QVariant {
+ let row = usize::try_from(index.row()).ok();
+ let role = usize::try_from(role - USER_ROLE).ok().and_then(|r| ROLES.get(r));
+ match (row.and_then(|r| self.rows.get(r)), role) {
+ (Some(device), Some(role)) => role_value(device, role),
+ _ => QVariant::default(),
+ }
+ }
+
+ pub fn role_names(&self) -> QHash<QHashPair_i32_QByteArray> {
+ let mut roles = QHash::<QHashPair_i32_QByteArray>::default();
+ for (i, name) in ROLES.iter().enumerate() {
+ roles.insert(USER_ROLE + i as i32, QByteArray::from(*name));
+ }
+ roles
+ }
+
+ pub fn row_count(&self, _parent: &QModelIndex) -> i32 {
+ self.rows.len() as i32
+ }
+
+ pub fn row_of(&self, device_id: &QString) -> i32 {
+ let id = String::from(device_id);
+ self.rows.iter().position(|d| d.id.to_string() == id).map_or(-1, |r| r as i32)
+ }
+}
+
+/// One step turning the current rows into the new ones.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Edit {
+ Remove(usize),
+ Insert(usize),
+ Change(usize),
+}
+
+/// Edits from `old` to `new`, applied in order. `None` when the devices that
+/// stay changed their relative order (then the model is reset).
+fn diff(old: &[DeviceView], new: &[DeviceView]) -> Option<Vec<Edit>> {
+ let mut edits = Vec::new();
+ // Removals, from the end so earlier indices stay valid.
+ for (row, device) in old.iter().enumerate().rev() {
+ if !new.iter().any(|d| d.id == device.id) {
+ edits.push(Edit::Remove(row));
+ }
+ }
+ let kept: Vec<&DeviceView> = old.iter().filter(|d| new.iter().any(|n| n.id == d.id)).collect();
+ let mut next_kept = 0;
+ for (row, device) in new.iter().enumerate() {
+ match kept.get(next_kept) {
+ Some(k) if k.id == device.id => {
+ if *k != device {
+ edits.push(Edit::Change(row));
+ }
+ next_kept += 1;
+ }
+ // Devices already in the list must come in the same order.
+ _ if kept.iter().any(|k| k.id == device.id) => return None,
+ _ => edits.push(Edit::Insert(row)),
+ }
+ }
+ Some(edits)
+}
+
+#[cfg(test)]
+mod tests {
+ use nectarlink_core::{DeviceId, DeviceInfo};
+
+ use super::*;
+
+ fn device(n: u8, name: &str) -> DeviceView {
+ DeviceView {
+ id: DeviceId([n; 32]),
+ info: DeviceInfo {
+ name: name.into(),
+ kind: DeviceKind::Phone,
+ os: "android".into(),
+ os_ver: "16".into(),
+ model: None,
+ accent: None,
+ },
+ paired_at: i64::from(n),
+ link: LinkState::Offline { last_seen: None },
+ battery: None,
+ power: PowerLevel::Basic,
+ }
+ }
+
+ /// Applies edits the way the model does and checks the result.
+ fn apply(old: &[DeviceView], new: &[DeviceView]) -> Vec<DeviceView> {
+ let mut rows = old.to_vec();
+ for edit in diff(old, new).expect("incremental") {
+ match edit {
+ Edit::Remove(r) => {
+ rows.remove(r);
+ }
+ Edit::Insert(r) => rows.insert(r, new[r].clone()),
+ Edit::Change(r) => rows[r] = new[r].clone(),
+ }
+ }
+ rows
+ }
+
+ #[test]
+ fn inserts_removes_and_changes() {
+ let (a, b, c, d) = (device(1, "a"), device(2, "b"), device(3, "c"), device(4, "d"));
+ let old = vec![a.clone(), b.clone(), c.clone()];
+ let mut b2 = b.clone();
+ b2.info.name = "b2".into();
+ let new = vec![a.clone(), b2.clone(), d.clone()];
+ assert_eq!(diff(&old, &new).unwrap(), [Edit::Remove(2), Edit::Change(1), Edit::Insert(2)]);
+ assert_eq!(apply(&old, &new), new);
+
+ assert_eq!(apply(&[], &new), new);
+ assert_eq!(apply(&new, &[]), Vec::<DeviceView>::new());
+ assert_eq!(diff(&new, &new).unwrap(), []);
+ let interleaved = vec![d.clone(), a.clone(), c.clone(), b2.clone()];
+ assert_eq!(apply(&[a.clone(), b2.clone()], &interleaved), interleaved);
+ }
+
+ #[test]
+ fn reordering_falls_back_to_a_reset() {
+ let (a, b) = (device(1, "a"), device(2, "b"));
+ assert_eq!(diff(&[a.clone(), b.clone()], &[b, a]), None);
+ }
+
+ #[test]
+ fn roles_cover_the_device() {
+ let mut d = device(5, "Pixel");
+ d.link = LinkState::Online { path: ConnectionPath::Lan, rtt_ms: 7 };
+ d.battery = Some(nectarlink_core::Battery { level: 64, charging: true, plugged: None });
+ d.info.accent = Some(0xFF8A5100);
+ assert_eq!(role_value(&d, "name").value::<QString>().map(String::from).as_deref(), Some("Pixel"));
+ assert_eq!(role_value(&d, "online").value::<bool>(), Some(true));
+ assert_eq!(role_value(&d, "rttMs").value::<i32>(), Some(7));
+ assert_eq!(role_value(&d, "battery").value::<i32>(), Some(64));
+ assert_eq!(role_value(&d, "accent").value::<QString>().map(String::from).as_deref(), Some("#8A5100"));
+ }
+}
diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rs
new file mode 100644
index 0000000..7df4e0f
--- /dev/null
+++ b/desktop/app/src/bridge/mod.rs
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! The Qt objects QML talks to. Each one is a thin view over the shared
+//! [`crate::state::Hub`]: it subscribes to the parts it shows and refreshes
+//! on the Qt thread, coalesced so a burst of core events costs one refresh
+//! (spikes/s1-qt-rust, lesson 1).
+
+// cxx-qt generates FFI code with `unsafe`; these modules are the boundary.
+#[allow(unsafe_code)]
+pub mod app;
+#[allow(unsafe_code)]
+pub mod devices;
+#[allow(unsafe_code)]
+pub mod native;
+#[allow(unsafe_code)]
+pub mod pairing;
+#[allow(unsafe_code)]
+pub mod prefs;
+
+use std::{
+ pin::Pin,
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+ },
+};
+
+use cxx_qt::{CxxQtThread, Threading};
+use cxx_qt_lib::QString;
+use nectarlink_core::DeviceId;
+
+use crate::state::Changes;
+
+/// Subscribes `qt`'s object to `interest`: `refresh` runs on the Qt thread
+/// after changes, at most one call queued at a time. The subscription ends
+/// when the object is destroyed.
+pub(crate) fn subscribe<T>(qt: CxxQtThread<T>, interest: Changes, refresh: fn(Pin<&mut T>))
+where
+ T: Threading + 'static,
+{
+ let scheduled = Arc::new(AtomicBool::new(false));
+ crate::core_host::host().hub.subscribe(interest, move || {
+ if scheduled.swap(true, Ordering::AcqRel) {
+ return true; // a refresh is already queued and will see this change
+ }
+ let scheduled = scheduled.clone();
+ qt.queue(move |object| {
+ // Clear first so changes during the refresh schedule another.
+ scheduled.store(false, Ordering::Release);
+ refresh(object);
+ })
+ .is_ok()
+ });
+}
+
+/// Parses a device ID coming from QML.
+pub(crate) fn parse_device(id: &QString) -> Option<DeviceId> {
+ String::from(id).parse().ok()
+}
diff --git a/desktop/app/src/bridge/native.rs b/desktop/app/src/bridge/native.rs
new file mode 100644
index 0000000..ed6d1b2
--- /dev/null
+++ b/desktop/app/src/bridge/native.rs
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Qt calls that cxx-qt-lib doesn't wrap (see `cpp/app_helpers.cpp`).
+
+#[cxx::bridge]
+pub mod ffi {
+ unsafe extern "C++" {
+ include!("app_helpers.h");
+
+ /// Must run before `QGuiApplication` is created.
+ fn prepare_qt();
+ fn add_app_icon_image(size: i32, rgba: &[u8]);
+ fn apply_app_icon();
+ fn keep_running_without_windows();
+ }
+}
diff --git a/desktop/app/src/bridge/pairing.rs b/desktop/app/src/bridge/pairing.rs
new file mode 100644
index 0000000..1023e2c
--- /dev/null
+++ b/desktop/app/src/bridge/pairing.rs
@@ -0,0 +1,248 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `Pairing`: drives the pairing screen. Shows a QR code that refreshes
+//! itself until a phone pairs, lists nearby devices for code pairing, and
+//! handles the 6-digit code check.
+
+use std::{
+ pin::Pin,
+ time::{Duration, SystemTime, UNIX_EPOCH},
+};
+
+use cxx_qt::{CxxQtType, Threading};
+use cxx_qt_lib::{QHash, QHashPair_QString_QVariant, QList, QString, QVariant};
+use nectarlink_core::{DeviceId, PairingFailure};
+
+use crate::{
+ core_host, qr,
+ state::{Changes, PairingView},
+};
+
+/// Matches the core's pairing window (PAIRING_TTL).
+const QR_LIFETIME: Duration = Duration::from_secs(5 * 60);
+
+#[cxx_qt::bridge]
+pub mod qobject {
+ unsafe extern "C++" {
+ include!("cxx-qt-lib/qstring.h");
+ type QString = cxx_qt_lib::QString;
+ include!("cxx-qt-lib/qlist.h");
+ type QList_QVariant = cxx_qt_lib::QList<cxx_qt_lib::QVariant>;
+ }
+
+ #[auto_cxx_name]
+ unsafe extern "RustQt" {
+ #[qobject]
+ #[qml_element]
+ #[qml_singleton]
+ /// "idle", "starting", "hosting", "connecting", "comparing",
+ /// "confirmed", "paired" or "failed".
+ #[qproperty(QString, state)]
+ /// The QR code as an SVG path over a `qrSize`×`qrSize` grid.
+ #[qproperty(QString, qr_path)]
+ #[qproperty(i32, qr_size)]
+ /// When the QR code expires (ms since the epoch); it refreshes itself.
+ #[qproperty(f64, expires_at)]
+ /// The 6-digit code to compare, and the device it's shared with.
+ #[qproperty(QString, code)]
+ #[qproperty(QString, peer_name)]
+ /// Why pairing failed: "rejected", "declined", "expired",
+ /// "unreachable" or "other".
+ #[qproperty(QString, failure)]
+ /// Devices nearby in pairing mode: `[{ id, name }]`.
+ #[qproperty(QList_QVariant, nearby)]
+ type Pairing = super::PairingRust;
+
+ /// Shows a QR code (and accepts nearby pairing) until cancelled.
+ #[qinvokable]
+ fn start(self: Pin<&mut Pairing>);
+ /// Pairs with a nearby device that shows its pairing screen.
+ #[qinvokable]
+ fn pair_nearby(self: Pin<&mut Pairing>, device: &QString);
+ /// Answers the code comparison.
+ #[qinvokable]
+ fn confirm(self: Pin<&mut Pairing>, codes_match: bool);
+ /// Leaves pairing mode.
+ #[qinvokable]
+ fn cancel(self: Pin<&mut Pairing>);
+ }
+
+ impl cxx_qt::Threading for Pairing {}
+ impl cxx_qt::Initialize for Pairing {}
+}
+
+#[derive(Default)]
+pub struct PairingRust {
+ state: QString,
+ qr_path: QString,
+ qr_size: i32,
+ expires_at: f64,
+ code: QString,
+ peer_name: QString,
+ failure: QString,
+ nearby: QList<QVariant>,
+ /// The link currently shown, to re-encode only when it changes.
+ shown_uri: String,
+}
+
+impl cxx_qt::Initialize for qobject::Pairing {
+ fn initialize(mut self: Pin<&mut Self>) {
+ self.as_mut().set_state(QString::from("idle"));
+ super::subscribe(
+ self.qt_thread(),
+ Changes::PAIRING | Changes::DISCOVERED | Changes::DEVICES,
+ Self::refresh,
+ );
+ }
+}
+
+fn hub() -> &'static crate::state::Hub {
+ &core_host::host().hub
+}
+
+/// Asks the core for a fresh pairing link and shows it.
+fn host_qr() {
+ hub().update(|s| s.set_pairing(PairingView::Starting));
+ let Some(node) = core_host::node() else {
+ hub().update(|s| s.set_pairing(PairingView::Failed(PairingFailure::Other("not ready".into()))));
+ return;
+ };
+ core_host::spawn(async move {
+ let next = match node.pairing_start_qr().await {
+ Ok(uri) => {
+ PairingView::Hosting { uri: uri.to_uri(), expires_at: SystemTime::now() + QR_LIFETIME }
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "can't start pairing");
+ PairingView::Failed(PairingFailure::Other(e.to_string()))
+ }
+ };
+ // Don't resurrect a screen the user already left.
+ hub()
+ .update(|s| if s.pairing == PairingView::Starting { s.set_pairing(next) } else { Changes::NONE });
+ });
+}
+
+impl qobject::Pairing {
+ fn refresh(mut self: Pin<&mut Self>) {
+ let (view, nearby, names) = hub().read(|s| {
+ let peer = match &s.pairing {
+ PairingView::Connecting { peer }
+ | PairingView::Comparing { peer, .. }
+ | PairingView::Confirmed { peer, .. } => Some(*peer),
+ _ => None,
+ };
+ let nearby: Vec<(DeviceId, String)> =
+ s.discovered.iter().map(|d| (d.id, d.name.clone().unwrap_or_else(|| d.id.short()))).collect();
+ (s.pairing.clone(), nearby, peer.and_then(|p| s.name_of(&p)))
+ });
+
+ // An expired QR code is replaced right away; the user never sees
+ // "expired" while the pairing screen is open.
+ if view == PairingView::Failed(PairingFailure::Expired) && self.state == QString::from("hosting") {
+ host_qr();
+ return;
+ }
+
+ let state = match &view {
+ PairingView::Idle => "idle",
+ PairingView::Starting => "starting",
+ PairingView::Hosting { .. } => "hosting",
+ PairingView::Connecting { .. } => "connecting",
+ PairingView::Comparing { .. } => "comparing",
+ PairingView::Confirmed { .. } => "confirmed",
+ PairingView::Paired { .. } => "paired",
+ PairingView::Failed(_) => "failed",
+ };
+ match &view {
+ PairingView::Hosting { uri, expires_at } => {
+ if self.shown_uri != *uri {
+ match qr::encode(uri) {
+ Ok(code) => {
+ self.as_mut().set_qr_path(QString::from(&code.path));
+ self.as_mut().set_qr_size(code.size as i32);
+ }
+ Err(e) => tracing::error!(error = %e, "can't encode the pairing link"),
+ }
+ self.as_mut().rust_mut().shown_uri = uri.clone();
+ }
+ let ms = expires_at.duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as f64;
+ self.as_mut().set_expires_at(ms);
+ }
+ PairingView::Comparing { code, .. } | PairingView::Confirmed { code, .. } => {
+ self.as_mut().set_code(QString::from(code));
+ }
+ PairingView::Paired { name, .. } => self.as_mut().set_peer_name(QString::from(name)),
+ PairingView::Failed(failure) => {
+ let failure = match failure {
+ PairingFailure::Rejected => "rejected",
+ PairingFailure::Declined => "declined",
+ PairingFailure::Expired => "expired",
+ PairingFailure::Unreachable => "unreachable",
+ PairingFailure::Other(_) => "other",
+ };
+ self.as_mut().set_failure(QString::from(failure));
+ }
+ _ => {}
+ }
+ if let Some(name) = names {
+ self.as_mut().set_peer_name(QString::from(&name));
+ }
+
+ let mut list = QList::<QVariant>::default();
+ for (id, name) in nearby {
+ let mut item = QHash::<QHashPair_QString_QVariant>::default();
+ item.insert(QString::from("id"), QVariant::from(&QString::from(&id.to_string())));
+ item.insert(QString::from("name"), QVariant::from(&QString::from(&name)));
+ list.append(QVariant::from(&item));
+ }
+ self.as_mut().set_nearby(list);
+ // Last, so QML reacting to the state sees the details already set.
+ self.as_mut().set_state(QString::from(state));
+ }
+
+ pub fn start(self: Pin<&mut Self>) {
+ host_qr();
+ }
+
+ pub fn pair_nearby(self: Pin<&mut Self>, device: &QString) {
+ let (Some(peer), Some(node)) = (super::parse_device(device), core_host::node()) else { return };
+ hub().update(|s| s.set_pairing(PairingView::Connecting { peer }));
+ core_host::spawn(async move {
+ // Success and failure arrive as pairing events.
+ if let Err(e) = node.pairing_start_nearby(peer).await {
+ tracing::info!(error = %e, "nearby pairing ended");
+ hub().update(|s| match s.pairing {
+ PairingView::Connecting { .. } => {
+ s.set_pairing(PairingView::Failed(PairingFailure::Unreachable))
+ }
+ _ => Changes::NONE,
+ });
+ }
+ });
+ }
+
+ pub fn confirm(self: Pin<&mut Self>, codes_match: bool) {
+ let Some(node) = core_host::node() else { return };
+ let comparing = hub().read(|s| match &s.pairing {
+ PairingView::Comparing { peer, code } => Some((*peer, code.clone())),
+ _ => None,
+ });
+ let Some((peer, code)) = comparing else { return };
+ if let Err(e) = node.pairing_confirm(codes_match) {
+ tracing::warn!(error = %e, "can't answer the code check");
+ }
+ let next = if codes_match {
+ PairingView::Confirmed { peer, code }
+ } else {
+ PairingView::Failed(PairingFailure::Declined)
+ };
+ hub().update(|s| s.set_pairing(next));
+ }
+
+ pub fn cancel(self: Pin<&mut Self>) {
+ if let Some(node) = core_host::node() {
+ node.pairing_cancel();
+ }
+ hub().update(|s| s.set_pairing(PairingView::Idle));
+ }
+}
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
new file mode 100644
index 0000000..003a86d
--- /dev/null
+++ b/desktop/app/src/bridge/prefs.rs
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `Preferences`: the app's look and behavior, saved whenever it changes.
+
+use std::pin::Pin;
+
+use cxx_qt::CxxQtType;
+use cxx_qt_lib::QString;
+
+use crate::{
+ core_host,
+ settings::{ColorMode, Settings, Theme},
+};
+
+#[cxx_qt::bridge]
+pub mod qobject {
+ unsafe extern "C++" {
+ include!("cxx-qt-lib/qstring.h");
+ type QString = cxx_qt_lib::QString;
+ }
+
+ #[auto_cxx_name]
+ unsafe extern "RustQt" {
+ #[qobject]
+ #[qml_element]
+ #[qml_singleton]
+ /// "bloom" or "graphite".
+ #[qproperty(QString, theme)]
+ /// Bloom color preset: "honey", "sage", "lavender" or "ocean".
+ #[qproperty(QString, seed)]
+ /// "system", "light" or "dark".
+ #[qproperty(QString, color_mode)]
+ /// Mica behind the window.
+ #[qproperty(bool, backdrop)]
+ #[qproperty(bool, close_to_tray)]
+ type Preferences = super::PreferencesRust;
+ }
+
+ impl cxx_qt::Initialize for Preferences {}
+}
+
+#[derive(Default)]
+pub struct PreferencesRust {
+ theme: QString,
+ seed: QString,
+ color_mode: QString,
+ backdrop: bool,
+ close_to_tray: bool,
+}
+
+impl cxx_qt::Initialize for qobject::Preferences {
+ fn initialize(mut self: Pin<&mut Self>) {
+ let settings = Settings::load(&core_host::host().data_dir);
+ self.as_mut().set_theme(QString::from(match settings.theme {
+ Theme::Bloom => "bloom",
+ Theme::Graphite => "graphite",
+ }));
+ self.as_mut().set_seed(QString::from(&settings.seed));
+ self.as_mut().set_color_mode(QString::from(match settings.color_mode {
+ ColorMode::System => "system",
+ ColorMode::Light => "light",
+ ColorMode::Dark => "dark",
+ }));
+ self.as_mut().set_backdrop(settings.backdrop);
+ self.as_mut().set_close_to_tray(settings.close_to_tray);
+
+ // Save after any change (connected after loading, so loading doesn't
+ // rewrite the file).
+ self.as_mut().on_theme_changed(|p| p.save()).release();
+ self.as_mut().on_seed_changed(|p| p.save()).release();
+ self.as_mut().on_color_mode_changed(|p| p.save()).release();
+ self.as_mut().on_backdrop_changed(|p| p.save()).release();
+ self.as_mut().on_close_to_tray_changed(|p| p.save()).release();
+ }
+}
+
+impl qobject::Preferences {
+ fn save(self: Pin<&mut Self>) {
+ let p = self.rust();
+ let settings = Settings {
+ theme: if String::from(&p.theme) == "graphite" { Theme::Graphite } else { Theme::Bloom },
+ seed: String::from(&p.seed),
+ color_mode: match String::from(&p.color_mode).as_str() {
+ "light" => ColorMode::Light,
+ "dark" => ColorMode::Dark,
+ _ => ColorMode::System,
+ },
+ backdrop: p.backdrop,
+ close_to_tray: p.close_to_tray,
+ };
+ if let Err(e) = settings.save(&core_host::host().data_dir) {
+ tracing::warn!(error = %e, "can't save preferences");
+ }
+ }
+}
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
new file mode 100644
index 0000000..eababf4
--- /dev/null
+++ b/desktop/app/src/core_host.rs
@@ -0,0 +1,143 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Runs `nectarlink-core` beside Qt: a small Tokio runtime owns the [`Node`],
+//! core events are folded into the [`Hub`], and Qt objects issue commands
+//! through [`spawn`]. The UI starts before the node, which comes up in the
+//! background (startup is never blocked on the network).
+
+use std::{
+ future::Future,
+ path::PathBuf,
+ sync::{Arc, OnceLock},
+ time::Duration,
+};
+
+use nectarlink_core::{DeviceInfo, DeviceKind, LinkState, Node, NodeConfig, Platform};
+use tokio::{runtime::Runtime, sync::broadcast::error::RecvError};
+
+use crate::state::{Changes, CoreStatus, Hub};
+
+const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
+
+#[derive(Debug)]
+pub struct CoreHost {
+ runtime: Runtime,
+ node: OnceLock<Node>,
+ pub hub: Arc<Hub>,
+ pub data_dir: PathBuf,
+}
+
+static HOST: OnceLock<CoreHost> = OnceLock::new();
+
+/// The running host. Panics if called before [`start`].
+pub fn host() -> &'static CoreHost {
+ HOST.get().expect("core host is started in main before Qt")
+}
+
+/// The node, once it has started.
+pub fn node() -> Option<Node> {
+ host().node.get().cloned()
+}
+
+/// Runs a command on the core's runtime.
+pub fn spawn(fut: impl Future<Output = ()> + Send + 'static) {
+ host().runtime.spawn(fut);
+}
+
+/// Creates the runtime and starts the node in the background.
+pub fn start(data_dir: PathBuf, platform: Arc<dyn Platform>) -> std::io::Result<&'static CoreHost> {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .thread_name("nectarlink-core")
+ .enable_all()
+ .build()?;
+ let host = CoreHost { runtime, node: OnceLock::new(), hub: Hub::new(), data_dir: data_dir.clone() };
+ if HOST.set(host).is_err() {
+ panic!("core host started twice");
+ }
+ let host = self::host();
+ host.hub.update(|s| {
+ s.status = Some(CoreStatus::Starting);
+ Changes::STATUS
+ });
+ host.runtime.spawn(run(data_dir, platform));
+ Ok(host)
+}
+
+async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
+ let host = host();
+ let config = NodeConfig::new(&data_dir, this_device(), env!("CARGO_PKG_VERSION"));
+ let node = match Node::start(config, platform).await {
+ Ok(node) => node,
+ Err(e) => {
+ tracing::error!(error = %e, "core failed to start");
+ host.hub.update(|s| {
+ s.status = Some(CoreStatus::Failed(e.to_string()));
+ Changes::STATUS
+ });
+ return;
+ }
+ };
+ // Subscribe before reading the initial state so no event is missed.
+ let mut events = node.events();
+ let devices = node.paired_devices().unwrap_or_else(|e| {
+ tracing::warn!(error = %e, "can't list paired devices");
+ Vec::new()
+ });
+ // A device that never connected hasn't told us what it can do; its
+ // features stay "unknown" (not "locked") until its first hello.
+ let matrices: Vec<_> = devices
+ .iter()
+ .filter(|d| !matches!(d.link, LinkState::Offline { last_seen: None }))
+ .filter_map(|d| node.capabilities(d.id).ok())
+ .collect();
+ let status = CoreStatus::Ready { device_id: node.device_id(), name: this_device().name };
+ let _ = host.node.set(node);
+ host.hub.update(|s| {
+ let mut changes = s.set_devices(devices);
+ for m in matrices {
+ changes |= s.set_matrix(m);
+ }
+ s.status = Some(status);
+ changes |= Changes::STATUS | Changes::CAPABILITIES;
+ changes
+ });
+
+ loop {
+ match events.recv().await {
+ Ok(event) => host.hub.update(|s| s.apply(&event)),
+ Err(RecvError::Lagged(missed)) => {
+ // Resynchronize what can be re-read; transient events are lost.
+ tracing::warn!(missed, "UI fell behind core events; resyncing");
+ let devices =
+ host.node.get().map(|n| n.paired_devices().unwrap_or_default()).unwrap_or_default();
+ host.hub.update(|s| s.set_devices(devices));
+ }
+ Err(RecvError::Closed) => return,
+ }
+ }
+}
+
+/// How this PC presents itself to phones.
+fn this_device() -> DeviceInfo {
+ let name = hostname::get().ok().and_then(|h| h.into_string().ok()).unwrap_or_else(|| "Windows PC".into());
+ DeviceInfo {
+ name,
+ kind: if crate::win::is_laptop() { DeviceKind::Laptop } else { DeviceKind::Desktop },
+ os: "windows".into(),
+ os_ver: crate::win::os_version(),
+ model: None,
+ accent: None,
+ }
+}
+
+/// Stops the node (telling connected devices) and the runtime.
+pub fn shutdown() {
+ let Some(host) = HOST.get() else { return };
+ if let Some(node) = host.node.get().cloned() {
+ let done =
+ host.runtime.block_on(async { tokio::time::timeout(SHUTDOWN_TIMEOUT, node.shutdown()).await });
+ if done.is_err() {
+ tracing::warn!("core shutdown timed out");
+ }
+ }
+}
diff --git a/desktop/app/src/logging.rs b/desktop/app/src/logging.rs
new file mode 100644
index 0000000..a86a7b3
--- /dev/null
+++ b/desktop/app/src/logging.rs
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Logs go to `<data>\logs\nectarlink.log`, rotated at startup once large,
+//! so a bug report can include them. Set `RUST_LOG` to change verbosity.
+
+use std::{
+ fs,
+ path::{Path, PathBuf},
+ sync::Mutex,
+};
+
+use tracing_subscriber::{EnvFilter, fmt, prelude::*};
+
+const FILE_NAME: &str = "nectarlink.log";
+const PREVIOUS_FILE_NAME: &str = "nectarlink.1.log";
+const ROTATE_AT_BYTES: u64 = 4 * 1024 * 1024;
+const DEFAULT_FILTER: &str = "info,iroh=warn,iroh_quinn=warn,iroh_quinn_proto=warn,swarm_discovery=warn";
+
+pub fn logs_dir(data_dir: &Path) -> PathBuf {
+ data_dir.join("logs")
+}
+
+/// Starts logging. Failing to open the log file is not fatal: the app then
+/// logs to stderr only.
+pub fn init(data_dir: &Path) {
+ let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(DEFAULT_FILTER));
+ let file_layer = match open_log_file(&logs_dir(data_dir)) {
+ Ok(file) => Some(fmt::layer().with_ansi(false).with_writer(Mutex::new(file))),
+ Err(e) => {
+ eprintln!("nectarlink: can't open the log file: {e}");
+ None
+ }
+ };
+ // Debug builds also log to the terminal.
+ let stderr_layer = cfg!(debug_assertions).then(|| fmt::layer().with_writer(std::io::stderr));
+ let _ = tracing_subscriber::registry().with(filter).with(file_layer).with(stderr_layer).try_init();
+}
+
+fn open_log_file(dir: &Path) -> std::io::Result<fs::File> {
+ fs::create_dir_all(dir)?;
+ let path = dir.join(FILE_NAME);
+ if fs::metadata(&path).is_ok_and(|m| m.len() > ROTATE_AT_BYTES) {
+ let _ = fs::rename(&path, dir.join(PREVIOUS_FILE_NAME));
+ }
+ fs::OpenOptions::new().create(true).append(true).open(path)
+}
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
new file mode 100644
index 0000000..4583a94
--- /dev/null
+++ b/desktop/app/src/main.rs
@@ -0,0 +1,158 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Nectarlink for Windows.
+//!
+//! One process: Rust runs the core (`nectarlink-core`) and OS integration,
+//! Qt Quick draws the UI. Windows are created when opened and destroyed when
+//! closed; the app keeps running in the tray (docs/PLAN.md §5).
+
+// A GUI app: no console window in release builds.
+#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+
+mod bridge;
+mod core_host;
+mod logging;
+mod qr;
+mod settings;
+mod state;
+mod win;
+
+use std::{
+ path::PathBuf,
+ process::ExitCode,
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+ },
+ time::Duration,
+};
+
+use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QString, QUrl};
+use nectarlink_core::Platform;
+
+use crate::win::single_instance::{self, Instance};
+
+/// Rings the PC when a phone asks ("find my PC").
+#[derive(Debug)]
+struct DesktopPlatform;
+
+impl Platform for DesktopPlatform {
+ fn start_ringing(&self) {
+ win::sound::start_ringing();
+ }
+ fn stop_ringing(&self) {
+ win::sound::stop_ringing();
+ }
+}
+
+/// Command-line options (also used by shortcuts and autostart).
+#[derive(Debug, Default)]
+struct Options {
+ /// Where to keep data (default: %LOCALAPPDATA%\Nectarlink).
+ data_dir: Option<PathBuf>,
+ /// Start in the tray without opening the window (autostart).
+ minimized: bool,
+}
+
+fn parse_options() -> Options {
+ let mut options = Options::default();
+ let mut args = std::env::args().skip(1);
+ while let Some(arg) = args.next() {
+ match arg.as_str() {
+ "--data-dir" => options.data_dir = args.next().map(PathBuf::from),
+ "--minimized" => options.minimized = true,
+ // Qt reads its own arguments; ignore everything else.
+ _ => {}
+ }
+ }
+ options
+}
+
+fn default_data_dir() -> PathBuf {
+ dirs::data_local_dir().unwrap_or_else(std::env::temp_dir).join("Nectarlink")
+}
+
+/// Network changes come in bursts; tell the core once things settle.
+fn watch_network() {
+ static PENDING: AtomicBool = AtomicBool::new(false);
+ win::net::watch(|| {
+ if PENDING.swap(true, Ordering::AcqRel) {
+ return;
+ }
+ core_host::spawn(async {
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ PENDING.store(false, Ordering::Release);
+ if let Some(node) = core_host::node() {
+ tracing::debug!("network changed");
+ node.network_changed().await;
+ }
+ });
+ });
+}
+
+fn install_panic_logging() {
+ let default = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |info| {
+ tracing::error!("panic: {info}");
+ default(info);
+ }));
+}
+
+fn main() -> ExitCode {
+ let options = parse_options();
+ let data_dir = options.data_dir.clone().unwrap_or_else(default_data_dir);
+ if let Err(e) = std::fs::create_dir_all(&data_dir) {
+ eprintln!("nectarlink: can't create {}: {e}", data_dir.display());
+ return ExitCode::FAILURE;
+ }
+ logging::init(&data_dir);
+ install_panic_logging();
+ tracing::info!(version = env!("CARGO_PKG_VERSION"), minimized = options.minimized, "starting");
+
+ let instance = match single_instance::acquire(&data_dir) {
+ Ok(Instance::Primary(primary)) => Some(&*Box::leak(Box::new(primary))),
+ Ok(Instance::Secondary) => {
+ tracing::info!("already running; asked it to show itself");
+ return ExitCode::SUCCESS;
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "single-instance check failed; continuing");
+ None
+ }
+ };
+
+ if let Err(e) = core_host::start(data_dir, Arc::new(DesktopPlatform)) {
+ tracing::error!(error = %e, "can't start the core runtime");
+ return ExitCode::FAILURE;
+ }
+ watch_network();
+
+ bridge::native::ffi::prepare_qt();
+ let mut app = QGuiApplication::new();
+ if let Some(mut app) = app.as_mut() {
+ app.as_mut().set_application_name(&QString::from("Nectarlink"));
+ app.as_mut().set_application_version(&QString::from(env!("CARGO_PKG_VERSION")));
+ }
+ bridge::native::ffi::keep_running_without_windows();
+ for size in [16, 20, 24, 32, 40, 48, 64, 256] {
+ bridge::native::ffi::add_app_icon_image(size, &win::icon::render(size as usize));
+ }
+ bridge::native::ffi::apply_app_icon();
+
+ if let Some(instance) = instance {
+ instance.watch(bridge::app::request_activation);
+ }
+
+ let mut engine = QQmlApplicationEngine::new();
+ if let Some(engine) = engine.as_mut() {
+ engine.load(&QUrl::from("qrc:/qt/qml/app/nectarlink/qml/App.qml"));
+ }
+ let code = app.as_mut().map_or(1, |app| app.exec());
+
+ tracing::info!(code, "shutting down");
+ // QML first (it holds references into Qt), then the core.
+ drop(engine);
+ win::net::stop();
+ core_host::shutdown();
+ drop(app);
+ ExitCode::from(u8::try_from(code).unwrap_or(1))
+}
diff --git a/desktop/app/src/qr.rs b/desktop/app/src/qr.rs
new file mode 100644
index 0000000..043c867
--- /dev/null
+++ b/desktop/app/src/qr.rs
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! QR codes as one SVG path, so QML draws them crisp at any size and scale.
+
+use qrcode::{Color, EcLevel, QrCode};
+
+/// A QR code ready to draw: `path` covers the dark modules of a
+/// `size`×`size` grid (one unit per module, no quiet zone).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct QrPath {
+ pub size: usize,
+ pub path: String,
+}
+
+/// Encodes `text` with medium error correction (pairing links are short and
+/// get scanned off screens, where M is the usual choice).
+pub fn encode(text: &str) -> Result<QrPath, qrcode::types::QrError> {
+ let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::M)?;
+ let size = code.width();
+ let colors = code.to_colors();
+ let mut path = String::with_capacity(size * size);
+ for (y, row) in colors.chunks(size).enumerate() {
+ let mut x = 0;
+ while x < size {
+ if row[x] != Color::Dark {
+ x += 1;
+ continue;
+ }
+ // Merge horizontal runs into one rectangle each.
+ let start = x;
+ while x < size && row[x] == Color::Dark {
+ x += 1;
+ }
+ let run = x - start;
+ path.push_str(&format!("M{start} {y}h{run}v1h-{run}z"));
+ }
+ }
+ Ok(QrPath { size, path })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Turns the path back into a grid to check it matches the code.
+ fn rasterize(qr: &QrPath) -> Vec<bool> {
+ let mut grid = vec![false; qr.size * qr.size];
+ for rect in qr.path.split('z').filter(|r| !r.is_empty()) {
+ let nums: Vec<usize> = rect
+ .split(|c: char| !c.is_ascii_digit())
+ .filter(|s| !s.is_empty())
+ .map(|s| s.parse().unwrap())
+ .collect();
+ let [x, y, run, ..] = nums[..] else { panic!("bad rect {rect}") };
+ for i in x..x + run {
+ grid[y * qr.size + i] = true;
+ }
+ }
+ grid
+ }
+
+ #[test]
+ fn path_matches_the_code() {
+ let text = "nectarlink://pair?v=0&id=ybndrfg8ejkmcpqxot1uwisza345h769ybndrfg8ejkmcpqx&s=abcdefghijklmnopqrstuvwxyz";
+ let qr = encode(text).unwrap();
+ let code = QrCode::with_error_correction_level(text.as_bytes(), EcLevel::M).unwrap();
+ let expected: Vec<bool> = code.to_colors().into_iter().map(|c| c == Color::Dark).collect();
+ assert_eq!(qr.size, code.width());
+ assert_eq!(rasterize(&qr), expected);
+ }
+
+ #[test]
+ fn longer_text_needs_a_bigger_code() {
+ assert!(encode(&"x".repeat(200)).unwrap().size > encode("x").unwrap().size);
+ }
+}
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
new file mode 100644
index 0000000..e247388
--- /dev/null
+++ b/desktop/app/src/settings.rs
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! The desktop app's own preferences (look and behavior), stored as JSON next
+//! to the core's data. Device settings live in the core.
+
+use std::{
+ fs,
+ io::Write,
+ path::{Path, PathBuf},
+};
+
+use serde::{Deserialize, Serialize};
+
+const FILE_NAME: &str = "desktop-settings.json";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "lowercase")]
+pub enum Theme {
+ #[default]
+ Bloom,
+ Graphite,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "lowercase")]
+pub enum ColorMode {
+ #[default]
+ System,
+ Light,
+ Dark,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct Settings {
+ pub theme: Theme,
+ /// Bloom seed preset, e.g. "honey" (see docs/design/tokens.json).
+ pub seed: String,
+ pub color_mode: ColorMode,
+ /// Use the Windows 11 Mica backdrop.
+ pub backdrop: bool,
+ /// Closing the window keeps Nectarlink running in the tray.
+ pub close_to_tray: bool,
+}
+
+impl Default for Settings {
+ fn default() -> Self {
+ Settings {
+ theme: Theme::default(),
+ seed: "honey".into(),
+ color_mode: ColorMode::default(),
+ backdrop: true,
+ close_to_tray: true,
+ }
+ }
+}
+
+impl Settings {
+ fn path(dir: &Path) -> PathBuf {
+ dir.join(FILE_NAME)
+ }
+
+ /// Loads the settings, falling back to defaults if the file is missing.
+ /// A corrupt file is set aside (not deleted) so it can be inspected.
+ pub fn load(dir: &Path) -> Settings {
+ let path = Self::path(dir);
+ let text = match fs::read_to_string(&path) {
+ Ok(text) => text,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Settings::default(),
+ Err(e) => {
+ tracing::warn!(error = %e, "can't read settings; using defaults");
+ return Settings::default();
+ }
+ };
+ match serde_json::from_str(&text) {
+ Ok(settings) => settings,
+ Err(e) => {
+ tracing::warn!(error = %e, "settings file is corrupt; using defaults");
+ let _ = fs::rename(&path, path.with_extension("json.corrupt"));
+ Settings::default()
+ }
+ }
+ }
+
+ /// Saves atomically: a crash mid-write never leaves a half-written file.
+ pub fn save(&self, dir: &Path) -> std::io::Result<()> {
+ let path = Self::path(dir);
+ let tmp = path.with_extension("json.tmp");
+ {
+ let mut file = fs::File::create(&tmp)?;
+ file.write_all(serde_json::to_string_pretty(self)?.as_bytes())?;
+ file.sync_all()?;
+ }
+ fs::rename(&tmp, &path)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn round_trips_and_defaults() {
+ let dir = tempfile::tempdir().unwrap();
+ assert_eq!(Settings::load(dir.path()), Settings::default());
+
+ let settings = Settings {
+ theme: Theme::Graphite,
+ seed: "ocean".into(),
+ color_mode: ColorMode::Dark,
+ backdrop: false,
+ close_to_tray: false,
+ };
+ settings.save(dir.path()).unwrap();
+ assert_eq!(Settings::load(dir.path()), settings);
+ }
+
+ #[test]
+ fn missing_fields_take_defaults_and_corrupt_files_are_set_aside() {
+ let dir = tempfile::tempdir().unwrap();
+ fs::write(dir.path().join(FILE_NAME), r#"{ "theme": "graphite" }"#).unwrap();
+ let loaded = Settings::load(dir.path());
+ assert_eq!(loaded.theme, Theme::Graphite);
+ assert_eq!(loaded.seed, "honey");
+
+ fs::write(dir.path().join(FILE_NAME), "{ not json").unwrap();
+ assert_eq!(Settings::load(dir.path()), Settings::default());
+ assert!(dir.path().join("desktop-settings.json.corrupt").exists());
+ }
+}
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
new file mode 100644
index 0000000..cb5c327
--- /dev/null
+++ b/desktop/app/src/state.rs
@@ -0,0 +1,450 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! What the UI shows, kept in plain Rust: the core's events and the UI's own
+//! commands are folded into [`AppState`], and Qt objects are told which parts
+//! changed so they can refresh. Nothing here touches Qt, so it is unit-tested.
+
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex, MutexGuard},
+ time::SystemTime,
+};
+
+use nectarlink_core::{
+ Battery, CapabilityMatrix, DeviceId, DeviceInfo, DiscoveredDevice, LinkState, NodeEvent, PairedDevice,
+ PairingEvent, PairingFailure, PowerLevel,
+};
+
+/// Which parts of the state changed, so listeners refresh only what they show.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub struct Changes(u8);
+
+impl Changes {
+ pub const NONE: Changes = Changes(0);
+ pub const STATUS: Changes = Changes(1);
+ pub const DEVICES: Changes = Changes(1 << 1);
+ pub const DISCOVERED: Changes = Changes(1 << 2);
+ pub const PAIRING: Changes = Changes(1 << 3);
+ pub const CAPABILITIES: Changes = Changes(1 << 4);
+ pub const RINGING: Changes = Changes(1 << 5);
+
+ pub fn is_empty(self) -> bool {
+ self.0 == 0
+ }
+
+ pub fn intersects(self, other: Changes) -> bool {
+ self.0 & other.0 != 0
+ }
+}
+
+impl std::ops::BitOr for Changes {
+ type Output = Changes;
+ fn bitor(self, rhs: Changes) -> Changes {
+ Changes(self.0 | rhs.0)
+ }
+}
+
+impl std::ops::BitOrAssign for Changes {
+ fn bitor_assign(&mut self, rhs: Changes) {
+ self.0 |= rhs.0;
+ }
+}
+
+/// Whether the core is running.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum CoreStatus {
+ Starting,
+ Ready { device_id: DeviceId, name: String },
+ Failed(String),
+}
+
+/// A paired device as the UI shows it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DeviceView {
+ pub id: DeviceId,
+ pub info: DeviceInfo,
+ pub paired_at: i64,
+ pub link: LinkState,
+ pub battery: Option<Battery>,
+ pub power: PowerLevel,
+}
+
+impl From<PairedDevice> for DeviceView {
+ fn from(d: PairedDevice) -> Self {
+ DeviceView {
+ id: d.id,
+ info: d.info,
+ paired_at: d.paired_at,
+ link: d.link,
+ battery: None,
+ power: PowerLevel::Basic,
+ }
+ }
+}
+
+/// The pairing screen's state.
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub enum PairingView {
+ #[default]
+ Idle,
+ /// Asking the core for a pairing link.
+ Starting,
+ /// Showing a QR code for this link until `expires_at`.
+ Hosting {
+ uri: String,
+ expires_at: SystemTime,
+ },
+ /// Dialing a nearby device that is in pairing mode.
+ Connecting {
+ peer: DeviceId,
+ },
+ /// Both screens show this code; the user confirms it matches.
+ Comparing {
+ peer: DeviceId,
+ code: String,
+ },
+ /// This user confirmed; waiting for the other device.
+ Confirmed {
+ peer: DeviceId,
+ code: String,
+ },
+ Paired {
+ device: DeviceId,
+ name: String,
+ },
+ Failed(PairingFailure),
+}
+
+#[derive(Debug, Default)]
+pub struct AppState {
+ pub status: Option<CoreStatus>,
+ /// Paired devices, in pairing order.
+ pub devices: Vec<DeviceView>,
+ pub discovered: Vec<DiscoveredDevice>,
+ pub pairing: PairingView,
+ pub matrices: HashMap<DeviceId, CapabilityMatrix>,
+ /// Bumped whenever `matrices` changes.
+ pub matrices_version: u32,
+ /// The device that asked this PC to ring, while it rings.
+ pub ringing_from: Option<DeviceId>,
+}
+
+impl AppState {
+ pub fn core_status(&self) -> CoreStatus {
+ self.status.clone().unwrap_or(CoreStatus::Starting)
+ }
+
+ pub fn device(&self, id: &DeviceId) -> Option<&DeviceView> {
+ self.devices.iter().find(|d| d.id == *id)
+ }
+
+ fn device_mut(&mut self, id: &DeviceId) -> Option<&mut DeviceView> {
+ self.devices.iter_mut().find(|d| d.id == *id)
+ }
+
+ /// A name for any device we know of (paired or nearby).
+ pub fn name_of(&self, id: &DeviceId) -> Option<String> {
+ self.device(id)
+ .map(|d| d.info.name.clone())
+ .or_else(|| self.discovered.iter().find(|d| d.id == *id).and_then(|d| d.name.clone()))
+ }
+
+ /// Replaces the device list (at startup, from the core's store).
+ pub fn set_devices(&mut self, devices: Vec<PairedDevice>) -> Changes {
+ self.devices = devices.into_iter().map(DeviceView::from).collect();
+ self.devices.sort_by_key(|d| d.paired_at);
+ Changes::DEVICES
+ }
+
+ /// Folds one core event into the state.
+ pub fn apply(&mut self, event: &NodeEvent) -> Changes {
+ match event {
+ NodeEvent::DeviceAdded(device) => {
+ match self.device_mut(&device.id) {
+ Some(existing) => {
+ existing.info = device.info.clone();
+ existing.paired_at = device.paired_at;
+ }
+ None => {
+ self.devices.push(DeviceView::from(device.clone()));
+ self.devices.sort_by_key(|d| d.paired_at);
+ }
+ }
+ Changes::DEVICES
+ }
+ NodeEvent::DeviceRemoved(id) => {
+ let before = self.devices.len();
+ self.devices.retain(|d| d.id != *id);
+ let mut changes = Changes::NONE;
+ if self.devices.len() != before {
+ changes |= Changes::DEVICES;
+ }
+ if self.matrices.remove(id).is_some() {
+ self.matrices_version = self.matrices_version.wrapping_add(1);
+ changes |= Changes::CAPABILITIES;
+ }
+ if self.ringing_from == Some(*id) {
+ self.ringing_from = None;
+ changes |= Changes::RINGING;
+ }
+ changes
+ }
+ NodeEvent::LinkChanged { device, link } => self.update_device(device, |d| d.link = link.clone()),
+ NodeEvent::PeerInfoChanged { device, info } => {
+ self.update_device(device, |d| d.info = info.clone())
+ }
+ NodeEvent::PeerPowerChanged { device, power } => self.update_device(device, |d| d.power = *power),
+ NodeEvent::Battery { device, battery } => {
+ self.update_device(device, |d| d.battery = Some(battery.clone()))
+ }
+ NodeEvent::Capabilities(matrix) => {
+ if self.matrices.get(&matrix.device) == Some(matrix) {
+ return Changes::NONE;
+ }
+ self.set_matrix(matrix.clone())
+ }
+ NodeEvent::Ring { device, on } => {
+ let next = on.then_some(*device);
+ if self.ringing_from == next {
+ return Changes::NONE;
+ }
+ self.ringing_from = next;
+ Changes::RINGING
+ }
+ NodeEvent::Discovered(found) => {
+ match self.discovered.iter_mut().find(|d| d.id == found.id) {
+ Some(existing) if existing == found => return Changes::NONE,
+ Some(existing) => *existing = found.clone(),
+ None => self.discovered.push(found.clone()),
+ }
+ Changes::DISCOVERED
+ }
+ NodeEvent::DiscoveryExpired(id) => {
+ let before = self.discovered.len();
+ self.discovered.retain(|d| d.id != *id);
+ if self.discovered.len() == before { Changes::NONE } else { Changes::DISCOVERED }
+ }
+ NodeEvent::Pairing(event) => self.apply_pairing(event),
+ }
+ }
+
+ fn update_device(&mut self, id: &DeviceId, f: impl FnOnce(&mut DeviceView)) -> Changes {
+ let Some(device) = self.device_mut(id) else { return Changes::NONE };
+ let before = device.clone();
+ f(device);
+ if *device == before { Changes::NONE } else { Changes::DEVICES }
+ }
+
+ fn apply_pairing(&mut self, event: &PairingEvent) -> Changes {
+ let next = match event {
+ PairingEvent::SasCode { peer, code } => {
+ PairingView::Comparing { peer: *peer, code: code.clone() }
+ }
+ PairingEvent::Paired(device) => {
+ PairingView::Paired { device: device.id, name: device.info.name.clone() }
+ }
+ PairingEvent::Failed(failure) => {
+ // The core reports failures of attempts the UI isn't showing
+ // (e.g. a stranger's wrong code while idle); keep idle then.
+ if self.pairing == PairingView::Idle {
+ return Changes::NONE;
+ }
+ PairingView::Failed(failure.clone())
+ }
+ };
+ self.set_pairing(next)
+ }
+
+ pub fn set_matrix(&mut self, matrix: CapabilityMatrix) -> Changes {
+ self.matrices.insert(matrix.device, matrix);
+ self.matrices_version = self.matrices_version.wrapping_add(1);
+ Changes::CAPABILITIES
+ }
+
+ pub fn set_pairing(&mut self, next: PairingView) -> Changes {
+ if self.pairing == next {
+ return Changes::NONE;
+ }
+ self.pairing = next;
+ Changes::PAIRING
+ }
+}
+
+/// A Qt object interested in some parts of the state. `notify` schedules a
+/// refresh on the Qt thread and returns false once the object is gone.
+struct Listener {
+ interest: Changes,
+ notify: Box<dyn Fn() -> bool + Send + Sync>,
+}
+
+/// The shared state plus the listeners to tell about changes.
+#[derive(Default)]
+pub struct Hub {
+ state: Mutex<AppState>,
+ listeners: Mutex<Vec<Listener>>,
+}
+
+impl std::fmt::Debug for Hub {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Hub").finish_non_exhaustive()
+ }
+}
+
+fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
+ m.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+impl Hub {
+ pub fn new() -> Arc<Hub> {
+ Arc::new(Hub::default())
+ }
+
+ /// Changes the state and notifies the listeners interested in what changed.
+ pub fn update(&self, f: impl FnOnce(&mut AppState) -> Changes) {
+ let changes = f(&mut lock(&self.state));
+ if !changes.is_empty() {
+ self.notify(changes);
+ }
+ }
+
+ pub fn read<T>(&self, f: impl FnOnce(&AppState) -> T) -> T {
+ f(&lock(&self.state))
+ }
+
+ /// Registers a listener; it is called right away so it starts in sync.
+ pub fn subscribe(&self, interest: Changes, notify: impl Fn() -> bool + Send + Sync + 'static) {
+ if notify() {
+ lock(&self.listeners).push(Listener { interest, notify: Box::new(notify) });
+ }
+ }
+
+ fn notify(&self, changes: Changes) {
+ lock(&self.listeners).retain(|l| !l.interest.intersects(changes) || (l.notify)());
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ use nectarlink_core::{ConnectionPath, DeviceKind};
+
+ use super::*;
+
+ fn paired(n: u8, at: i64) -> PairedDevice {
+ PairedDevice {
+ id: DeviceId([n; 32]),
+ info: DeviceInfo {
+ name: format!("Phone {n}"),
+ kind: DeviceKind::Phone,
+ os: "android".into(),
+ os_ver: "16".into(),
+ model: None,
+ accent: None,
+ },
+ paired_at: at,
+ link: LinkState::Offline { last_seen: None },
+ }
+ }
+
+ #[test]
+ fn devices_follow_core_events() {
+ let mut s = AppState::default();
+ assert_eq!(s.apply(&NodeEvent::DeviceAdded(paired(2, 20))), Changes::DEVICES);
+ assert_eq!(s.apply(&NodeEvent::DeviceAdded(paired(1, 10))), Changes::DEVICES);
+ assert_eq!(
+ s.devices.iter().map(|d| d.paired_at).collect::<Vec<_>>(),
+ [10, 20],
+ "kept in pairing order"
+ );
+
+ let online = LinkState::Online { path: ConnectionPath::Lan, rtt_ms: 4 };
+ let id = DeviceId([1; 32]);
+ assert_eq!(s.apply(&NodeEvent::LinkChanged { device: id, link: online.clone() }), Changes::DEVICES);
+ assert_eq!(
+ s.apply(&NodeEvent::LinkChanged { device: id, link: online }),
+ Changes::NONE,
+ "no change, no refresh"
+ );
+ let battery = Battery { level: 50, charging: false, plugged: None };
+ s.apply(&NodeEvent::Battery { device: id, battery: battery.clone() });
+ assert_eq!(s.device(&id).unwrap().battery, Some(battery));
+
+ // Events about unknown devices are ignored.
+ assert_eq!(
+ s.apply(&NodeEvent::PeerPowerChanged { device: DeviceId([9; 32]), power: PowerLevel::Elevated }),
+ Changes::NONE
+ );
+
+ assert_eq!(s.apply(&NodeEvent::DeviceRemoved(id)), Changes::DEVICES);
+ assert_eq!(s.devices.len(), 1);
+ }
+
+ #[test]
+ fn pairing_flow() {
+ let mut s = AppState::default();
+ let peer = DeviceId([3; 32]);
+ // A failure nobody is looking at doesn't open the pairing screen.
+ assert_eq!(
+ s.apply(&NodeEvent::Pairing(PairingEvent::Failed(PairingFailure::Rejected))),
+ Changes::NONE
+ );
+
+ s.set_pairing(PairingView::Starting);
+ let code = PairingEvent::SasCode { peer, code: "123456".into() };
+ assert_eq!(s.apply(&NodeEvent::Pairing(code)), Changes::PAIRING);
+ assert_eq!(s.pairing, PairingView::Comparing { peer, code: "123456".into() });
+
+ let mut device = paired(3, 30);
+ device.info.name = "Pixel".into();
+ s.apply(&NodeEvent::Pairing(PairingEvent::Paired(device)));
+ assert_eq!(s.pairing, PairingView::Paired { device: peer, name: "Pixel".into() });
+
+ s.apply(&NodeEvent::Pairing(PairingEvent::Failed(PairingFailure::Expired)));
+ assert_eq!(s.pairing, PairingView::Failed(PairingFailure::Expired));
+ }
+
+ #[test]
+ fn ringing_and_discovery() {
+ let mut s = AppState::default();
+ let id = DeviceId([4; 32]);
+ assert_eq!(s.apply(&NodeEvent::Ring { device: id, on: true }), Changes::RINGING);
+ assert_eq!(s.ringing_from, Some(id));
+ assert_eq!(s.apply(&NodeEvent::Ring { device: id, on: true }), Changes::NONE);
+ s.apply(&NodeEvent::Ring { device: id, on: false });
+ assert_eq!(s.ringing_from, None);
+
+ let found = DiscoveredDevice { id, name: Some("Pixel".into()) };
+ assert_eq!(s.apply(&NodeEvent::Discovered(found.clone())), Changes::DISCOVERED);
+ assert_eq!(s.apply(&NodeEvent::Discovered(found)), Changes::NONE);
+ assert_eq!(s.name_of(&id).as_deref(), Some("Pixel"));
+ assert_eq!(s.apply(&NodeEvent::DiscoveryExpired(id)), Changes::DISCOVERED);
+ assert!(s.discovered.is_empty());
+ }
+
+ #[test]
+ fn hub_notifies_interested_listeners_and_drops_dead_ones() {
+ let hub = Hub::new();
+ let devices = Arc::new(AtomicUsize::new(0));
+ let pairing = Arc::new(AtomicUsize::new(0));
+ let d = devices.clone();
+ hub.subscribe(Changes::DEVICES, move || {
+ d.fetch_add(1, Ordering::SeqCst);
+ true
+ });
+ let p = pairing.clone();
+ hub.subscribe(Changes::PAIRING, move || p.fetch_add(1, Ordering::SeqCst) < 1);
+ assert_eq!((devices.load(Ordering::SeqCst), pairing.load(Ordering::SeqCst)), (1, 1), "initial sync");
+
+ hub.update(|s| s.apply(&NodeEvent::DeviceAdded(paired(1, 1))));
+ assert_eq!(devices.load(Ordering::SeqCst), 2);
+ assert_eq!(pairing.load(Ordering::SeqCst), 1, "not interested");
+
+ // The pairing listener reports it's gone on its next call...
+ hub.update(|s| s.set_pairing(PairingView::Starting));
+ hub.update(|s| s.set_pairing(PairingView::Idle));
+ // ...and isn't called again.
+ assert_eq!(pairing.load(Ordering::SeqCst), 2);
+ hub.update(|_| Changes::NONE);
+ assert_eq!(devices.load(Ordering::SeqCst), 2, "empty changes notify nobody");
+ }
+}
diff --git a/desktop/app/src/win/icon.rs b/desktop/app/src/win/icon.rs
new file mode 100644
index 0000000..6f5888d
--- /dev/null
+++ b/desktop/app/src/win/icon.rs
@@ -0,0 +1,112 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! The Nectarlink mark (a hexagon on a rounded square, as in the app's nav
+//! rail), drawn in code at any pixel size. Used for the tray and window
+//! icons, so they are sharp at every display scale without bitmap assets.
+
+/// Honey primary (docs/design/tokens.json) and the mark's ink.
+const BACKGROUND: [u8; 3] = [0x8A, 0x51, 0x00];
+const INK: [u8; 3] = [0xFF, 0xFF, 0xFF];
+
+/// Hexagon and bar of the mark, in a 24×24 design grid.
+const HEXAGON: [(f32, f32); 6] =
+ [(12.0, 2.5), (20.2, 7.25), (20.2, 16.75), (12.0, 21.5), (3.8, 16.75), (3.8, 7.25)];
+const BAR: ((f32, f32), (f32, f32)) = ((9.0, 12.0), (15.0, 12.0));
+
+/// Supersampling grid per pixel (SS×SS samples) for smooth edges.
+const SS: usize = 4;
+
+/// Renders the mark as straight-alpha RGBA, row by row, `size`×`size`.
+pub fn render(size: usize) -> Vec<u8> {
+ let s = size as f32;
+ let radius = s * 0.28;
+ // The glyph fills 62% of the tile, centered; stroke scales with it but
+ // never gets thinner than ~1.4 px so small sizes stay legible.
+ let glyph = s * 0.62;
+ let scale = glyph / 24.0;
+ let offset = (s - glyph) / 2.0;
+ let stroke = (1.8 * scale).max(1.4);
+ let hex: Vec<(f32, f32)> =
+ HEXAGON.iter().map(|&(x, y)| (offset + x * scale, offset + y * scale)).collect();
+ let bar = (
+ (offset + BAR.0.0 * scale, offset + BAR.0.1 * scale),
+ (offset + BAR.1.0 * scale, offset + BAR.1.1 * scale),
+ );
+
+ let mut out = vec![0u8; size * size * 4];
+ for py in 0..size {
+ for px in 0..size {
+ let (mut tile, mut ink) = (0usize, 0usize);
+ for sy in 0..SS {
+ for sx in 0..SS {
+ let x = px as f32 + (sx as f32 + 0.5) / SS as f32;
+ let y = py as f32 + (sy as f32 + 0.5) / SS as f32;
+ if !in_rounded_square(x, y, s, radius) {
+ continue;
+ }
+ tile += 1;
+ let on_hex = (0..hex.len())
+ .any(|i| dist_to_segment((x, y), hex[i], hex[(i + 1) % hex.len()]) <= stroke / 2.0);
+ if on_hex || dist_to_segment((x, y), bar.0, bar.1) <= stroke / 2.0 {
+ ink += 1;
+ }
+ }
+ }
+ let i = (py * size + px) * 4;
+ if tile == 0 {
+ continue;
+ }
+ // Ink over background, then the tile's coverage as alpha.
+ let t = ink as f32 / tile as f32;
+ for c in 0..3 {
+ out[i + c] = (BACKGROUND[c] as f32 * (1.0 - t) + INK[c] as f32 * t).round() as u8;
+ }
+ out[i + 3] = ((tile as f32 / (SS * SS) as f32) * 255.0).round() as u8;
+ }
+ }
+ out
+}
+
+fn in_rounded_square(x: f32, y: f32, size: f32, r: f32) -> bool {
+ let cx = x.clamp(r, size - r);
+ let cy = y.clamp(r, size - r);
+ (x - cx).powi(2) + (y - cy).powi(2) <= r * r
+}
+
+fn dist_to_segment(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 {
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let len2 = dx * dx + dy * dy;
+ let t = if len2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / len2).clamp(0.0, 1.0) };
+ let (qx, qy) = (a.0 + t * dx, a.1 + t * dy);
+ ((p.0 - qx).powi(2) + (p.1 - qy).powi(2)).sqrt()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn pixel(img: &[u8], size: usize, x: usize, y: usize) -> [u8; 4] {
+ let i = (y * size + x) * 4;
+ [img[i], img[i + 1], img[i + 2], img[i + 3]]
+ }
+
+ #[test]
+ fn corners_are_transparent_and_the_tile_is_opaque() {
+ let size = 32;
+ let img = render(size);
+ assert_eq!(img.len(), size * size * 4);
+ assert_eq!(pixel(&img, size, 0, 0)[3], 0, "rounded corner");
+ // Between the hexagon and the tile edge: solid background.
+ assert_eq!(pixel(&img, size, 3, 16), [BACKGROUND[0], BACKGROUND[1], BACKGROUND[2], 255]);
+ // The bar through the middle is (anti-aliased) ink on an opaque tile.
+ let mid = pixel(&img, size, 16, 16);
+ assert!(mid[0] > 200 && mid[3] == 255, "{mid:?}");
+ }
+
+ #[test]
+ fn renders_every_tray_size() {
+ for size in [16, 20, 24, 32, 48, 64, 256] {
+ let img = render(size);
+ assert!(img.chunks(4).any(|p| p[3] == 255), "{size}px has an opaque tile");
+ }
+ }
+}
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
new file mode 100644
index 0000000..7e7b574
--- /dev/null
+++ b/desktop/app/src/win/mod.rs
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Windows integration: system facts, single instance, tray, power and
+//! network notifications, ringing. Window chrome lives in C++
+//! (`cpp/native_window.cpp`) because it hooks Qt's native event handling.
+
+#![allow(unsafe_code)]
+
+pub mod icon;
+pub mod net;
+pub mod single_instance;
+pub mod sound;
+pub mod tray;
+
+use windows::{
+ Win32::{
+ Foundation::ERROR_SUCCESS,
+ System::{
+ Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS},
+ Registry::{
+ HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, RRF_RT_REG_DWORD, RRF_RT_REG_SZ, RegGetValueW,
+ },
+ },
+ UI::WindowsAndMessaging::{
+ SPI_GETCLIENTAREAANIMATION, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
+ },
+ },
+ core::{BOOL, HSTRING},
+};
+
+fn reg_dword(root: HKEY, key: &str, value: &str) -> Option<u32> {
+ let mut data = 0u32;
+ let mut size = std::mem::size_of::<u32>() as u32;
+ // SAFETY: data/size describe a live u32 buffer of the given size.
+ let status = unsafe {
+ RegGetValueW(
+ root,
+ &HSTRING::from(key),
+ &HSTRING::from(value),
+ RRF_RT_REG_DWORD,
+ None,
+ Some(std::ptr::from_mut(&mut data).cast()),
+ Some(&mut size),
+ )
+ };
+ (status == ERROR_SUCCESS).then_some(data)
+}
+
+fn reg_string(root: HKEY, key: &str, value: &str) -> Option<String> {
+ let mut buf = [0u16; 64];
+ let mut size = std::mem::size_of_val(&buf) as u32;
+ // SAFETY: buf/size describe a live UTF-16 buffer of the given byte size.
+ let status = unsafe {
+ RegGetValueW(
+ root,
+ &HSTRING::from(key),
+ &HSTRING::from(value),
+ RRF_RT_REG_SZ,
+ None,
+ Some(buf.as_mut_ptr().cast()),
+ Some(&mut size),
+ )
+ };
+ if status != ERROR_SUCCESS {
+ return None;
+ }
+ let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
+ Some(String::from_utf16_lossy(&buf[..len]))
+}
+
+const CURRENT_VERSION: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
+
+/// The Windows version as "10.0.<build>", which is what phones compare
+/// against for features that need a minimum build.
+pub fn os_version() -> String {
+ let major = reg_dword(HKEY_LOCAL_MACHINE, CURRENT_VERSION, "CurrentMajorVersionNumber").unwrap_or(10);
+ let minor = reg_dword(HKEY_LOCAL_MACHINE, CURRENT_VERSION, "CurrentMinorVersionNumber").unwrap_or(0);
+ let build = reg_string(HKEY_LOCAL_MACHINE, CURRENT_VERSION, "CurrentBuildNumber").unwrap_or_default();
+ format!("{major}.{minor}.{build}")
+}
+
+/// Whether this PC runs on a battery (so phones can show a laptop).
+pub fn is_laptop() -> bool {
+ let mut status = SYSTEM_POWER_STATUS::default();
+ // SAFETY: status is a live, writable struct.
+ let ok = unsafe { GetSystemPowerStatus(&mut status) }.is_ok();
+ // 128 = "no system battery", 255 = unknown.
+ ok && status.BatteryFlag != 128 && status.BatteryFlag != 255
+}
+
+/// Whether Windows is set to dark mode for apps.
+pub fn system_dark() -> bool {
+ reg_dword(
+ HKEY_CURRENT_USER,
+ r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize",
+ "AppsUseLightTheme",
+ ) == Some(0)
+}
+
+/// Whether the user turned off animations in Windows settings.
+pub fn reduce_motion() -> bool {
+ let mut enabled = BOOL(1);
+ // SAFETY: SPI_GETCLIENTAREAANIMATION writes a BOOL to the given pointer.
+ let ok = unsafe {
+ SystemParametersInfoW(
+ SPI_GETCLIENTAREAANIMATION,
+ 0,
+ Some(std::ptr::from_mut(&mut enabled).cast()),
+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
+ )
+ }
+ .is_ok();
+ ok && !enabled.as_bool()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reads_the_windows_version() {
+ let version = os_version();
+ let parts: Vec<&str> = version.split('.').collect();
+ assert_eq!(parts.len(), 3, "{version}");
+ assert!(parts[2].parse::<u32>().unwrap() >= 22000, "Nectarlink targets Windows 11: {version}");
+ }
+}
diff --git a/desktop/app/src/win/net.rs b/desktop/app/src/win/net.rs
new file mode 100644
index 0000000..7866408
--- /dev/null
+++ b/desktop/app/src/win/net.rs
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Network change notifications (Wi-Fi switched, cable plugged, VPN up), so
+//! paired devices reconnect right away instead of after their backoff.
+
+use std::{
+ ffi::c_void,
+ sync::{Mutex, OnceLock},
+};
+
+use windows::Win32::{
+ Foundation::{HANDLE, NO_ERROR},
+ NetworkManagement::IpHelper::{
+ CancelMibChangeNotify2, MIB_IPINTERFACE_ROW, MIB_NOTIFICATION_TYPE, NotifyIpInterfaceChange,
+ },
+ Networking::WinSock::AF_UNSPEC,
+};
+
+type Callback = Box<dyn Fn() + Send + Sync>;
+
+static CALLBACK: OnceLock<Callback> = OnceLock::new();
+static HANDLE_: Mutex<Option<isize>> = Mutex::new(None);
+
+unsafe extern "system" fn on_change(
+ _: *const c_void,
+ _: *const MIB_IPINTERFACE_ROW,
+ _: MIB_NOTIFICATION_TYPE,
+) {
+ if let Some(callback) = CALLBACK.get() {
+ callback();
+ }
+}
+
+/// Calls `callback` (on a system thread) whenever a network interface
+/// changes. Bursts are expected; the callback should debounce.
+pub fn watch(callback: impl Fn() + Send + Sync + 'static) {
+ if CALLBACK.set(Box::new(callback)).is_err() {
+ return; // already watching
+ }
+ let mut handle = HANDLE::default();
+ // SAFETY: the callback is a 'static function; the handle is stored and
+ // released in `stop`.
+ let status = unsafe { NotifyIpInterfaceChange(AF_UNSPEC, Some(on_change), None, false, &mut handle) };
+ if status == NO_ERROR {
+ *HANDLE_.lock().unwrap_or_else(|e| e.into_inner()) = Some(handle.0 as isize);
+ } else {
+ tracing::warn!(?status, "can't watch for network changes");
+ }
+}
+
+/// Stops the notifications (before exit).
+pub fn stop() {
+ if let Some(raw) = HANDLE_.lock().unwrap_or_else(|e| e.into_inner()).take() {
+ // SAFETY: the handle came from NotifyIpInterfaceChange and is
+ // cancelled once.
+ unsafe {
+ let _ = CancelMibChangeNotify2(HANDLE(raw as *mut c_void));
+ }
+ }
+}
diff --git a/desktop/app/src/win/single_instance.rs b/desktop/app/src/win/single_instance.rs
new file mode 100644
index 0000000..da8cd4e
--- /dev/null
+++ b/desktop/app/src/win/single_instance.rs
@@ -0,0 +1,131 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! One Nectarlink per user session and data folder. A second launch (from
+//! the Start menu, a shortcut or a jump list) asks the running one to show
+//! its window and exits.
+
+use std::{
+ hash::{DefaultHasher, Hash, Hasher},
+ path::Path,
+};
+
+use windows::{
+ Win32::{
+ Foundation::{CloseHandle, ERROR_ALREADY_EXISTS, GetLastError, HANDLE, WAIT_OBJECT_0},
+ System::Threading::{
+ CreateEventW, CreateMutexW, EVENT_MODIFY_STATE, INFINITE, OpenEventW, SetEvent,
+ WaitForSingleObject,
+ },
+ UI::WindowsAndMessaging::{ASFW_ANY, AllowSetForegroundWindow},
+ },
+ core::HSTRING,
+};
+
+/// Held for the lifetime of the primary instance.
+#[derive(Debug)]
+pub struct PrimaryInstance {
+ mutex: HANDLE,
+ activate: HANDLE,
+}
+
+// SAFETY: kernel handles are usable from any thread.
+unsafe impl Send for PrimaryInstance {}
+// SAFETY: as above; the handles are only waited on and closed.
+unsafe impl Sync for PrimaryInstance {}
+
+#[derive(Debug)]
+pub enum Instance {
+ Primary(PrimaryInstance),
+ /// Another instance is running and was asked to show itself.
+ Secondary,
+}
+
+/// Object names are per session ("Local\") and per data folder, so dev
+/// builds with their own `--data-dir` can run side by side.
+fn names(data_dir: &Path) -> (HSTRING, HSTRING) {
+ let mut hasher = DefaultHasher::new();
+ data_dir.to_string_lossy().to_lowercase().hash(&mut hasher);
+ let tag = format!("{:016x}", hasher.finish());
+ (
+ HSTRING::from(format!(r"Local\Nectarlink.Desktop.{tag}")),
+ HSTRING::from(format!(r"Local\Nectarlink.Desktop.Activate.{tag}")),
+ )
+}
+
+pub fn acquire(data_dir: &Path) -> windows::core::Result<Instance> {
+ let (mutex_name, event_name) = names(data_dir);
+ // SAFETY: plain kernel object calls with valid names; handles are closed
+ // in Drop (or below for the secondary instance).
+ unsafe {
+ let mutex = CreateMutexW(None, true, &mutex_name)?;
+ if GetLastError() == ERROR_ALREADY_EXISTS {
+ let _ = CloseHandle(mutex);
+ // We were just launched by the user, so we may take the
+ // foreground; pass that right on so the running instance's
+ // window comes to the front instead of only flashing.
+ let _ = AllowSetForegroundWindow(ASFW_ANY);
+ if let Ok(event) = OpenEventW(EVENT_MODIFY_STATE, false, &event_name) {
+ let _ = SetEvent(event);
+ let _ = CloseHandle(event);
+ }
+ return Ok(Instance::Secondary);
+ }
+ // Auto-reset: each SetEvent wakes the waiter once.
+ let activate = CreateEventW(None, false, false, &event_name)?;
+ Ok(Instance::Primary(PrimaryInstance { mutex, activate }))
+ }
+}
+
+impl PrimaryInstance {
+ /// Calls `on_activate` (on a background thread) whenever another launch
+ /// asks this instance to show itself.
+ pub fn watch(&'static self, on_activate: impl Fn() + Send + 'static) {
+ let spawned = std::thread::Builder::new().name("single-instance".into()).spawn(move || {
+ loop {
+ // SAFETY: the event handle lives as long as `self` ('static).
+ let woke = unsafe { WaitForSingleObject(self.activate, INFINITE) };
+ if woke != WAIT_OBJECT_0 {
+ return;
+ }
+ on_activate();
+ }
+ });
+ if let Err(e) = spawned {
+ tracing::warn!(error = %e, "can't watch for other launches");
+ }
+ }
+}
+
+impl Drop for PrimaryInstance {
+ fn drop(&mut self) {
+ // SAFETY: we own both handles.
+ unsafe {
+ let _ = CloseHandle(self.activate);
+ let _ = CloseHandle(self.mutex);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn second_acquire_is_secondary_and_activates_the_first() {
+ let dir = tempfile::tempdir().unwrap();
+ let Instance::Primary(primary) = acquire(dir.path()).unwrap() else { panic!("first is primary") };
+ assert!(matches!(acquire(dir.path()).unwrap(), Instance::Secondary));
+ // The secondary set the activation event.
+ // SAFETY: the handle is owned by `primary`, alive for this call.
+ assert_eq!(unsafe { WaitForSingleObject(primary.activate, 0) }, WAIT_OBJECT_0);
+ drop(primary);
+ assert!(matches!(acquire(dir.path()).unwrap(), Instance::Primary(_)), "free again after exit");
+ }
+
+ #[test]
+ fn different_data_folders_are_independent() {
+ let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
+ let first = acquire(a.path()).unwrap();
+ assert!(matches!(first, Instance::Primary(_)));
+ assert!(matches!(acquire(b.path()).unwrap(), Instance::Primary(_)));
+ }
+}
diff --git a/desktop/app/src/win/sound.rs b/desktop/app/src/win/sound.rs
new file mode 100644
index 0000000..b03854e
--- /dev/null
+++ b/desktop/app/src/win/sound.rs
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Ringing the PC ("find my PC" from the phone): the Windows looping alarm
+//! sound, until stopped or for at most a minute.
+
+use std::{
+ sync::atomic::{AtomicU64, Ordering},
+ time::Duration,
+};
+
+use windows::{
+ Win32::Media::Audio::{PlaySoundW, SND_ALIAS, SND_ASYNC, SND_FLAGS, SND_LOOP, SND_NODEFAULT},
+ core::{HSTRING, PCWSTR},
+};
+
+/// Rings stop by themselves after this long.
+const MAX_RING: Duration = Duration::from_secs(60);
+
+/// Bumped on every start/stop, so an old timer can't stop a newer ring.
+static GENERATION: AtomicU64 = AtomicU64::new(0);
+
+pub fn start_ringing() {
+ let generation = GENERATION.fetch_add(1, Ordering::SeqCst) + 1;
+ // Fall back to a plain system sound where the alarm alias is missing.
+ let played = ["Notification.Looping.Alarm", "SystemExclamation"].iter().any(|alias| {
+ let alias = HSTRING::from(*alias);
+ // SAFETY: the alias is a valid null-terminated string for the call.
+ unsafe { PlaySoundW(&alias, None, SND_ALIAS | SND_ASYNC | SND_LOOP | SND_NODEFAULT) }.as_bool()
+ });
+ if !played {
+ tracing::warn!("no sound available to ring with");
+ }
+ let _ = std::thread::Builder::new().name("ring-timeout".into()).spawn(move || {
+ std::thread::sleep(MAX_RING);
+ if GENERATION.load(Ordering::SeqCst) == generation {
+ stop_ringing();
+ }
+ });
+}
+
+pub fn stop_ringing() {
+ GENERATION.fetch_add(1, Ordering::SeqCst);
+ // SAFETY: a null sound stops whatever this process is playing.
+ unsafe {
+ let _ = PlaySoundW(PCWSTR::null(), None, SND_FLAGS(0));
+ }
+}
diff --git a/desktop/app/src/win/tray.rs b/desktop/app/src/win/tray.rs
new file mode 100644
index 0000000..fd41079
--- /dev/null
+++ b/desktop/app/src/win/tray.rs
@@ -0,0 +1,308 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! The notification-area (tray) icon and its menu, plus the system
+//! broadcasts a hidden top-level window receives: resume from sleep and
+//! theme/animation setting changes.
+//!
+//! Everything runs on the Qt GUI thread: the hidden window is created there,
+//! and Qt's event loop dispatches its messages.
+
+use std::cell::{Cell, RefCell};
+
+use windows::{
+ Win32::{
+ Foundation::{HWND, LPARAM, LRESULT, WPARAM},
+ Graphics::Gdi::{
+ BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateBitmap, CreateDIBSection, DIB_RGB_COLORS,
+ DeleteObject, HBITMAP,
+ },
+ System::LibraryLoader::GetModuleHandleW,
+ UI::{
+ Shell::{
+ NIF_ICON, NIF_MESSAGE, NIF_SHOWTIP, NIF_TIP, NIM_ADD, NIM_DELETE, NIM_MODIFY, NIM_SETVERSION,
+ NIN_SELECT, NOTIFYICON_VERSION_4, NOTIFYICONDATAW, Shell_NotifyIconW,
+ },
+ WindowsAndMessaging::{
+ AppendMenuW, CreateIconIndirect, CreatePopupMenu, CreateWindowExW, DefWindowProcW,
+ DestroyIcon, DestroyMenu, DestroyWindow, GetSystemMetrics, HICON, HMENU, ICONINFO, MF_GRAYED,
+ MF_SEPARATOR, MF_STRING, PostMessageW, RegisterClassExW, RegisterWindowMessageW, SM_CXSMICON,
+ SetForegroundWindow, TPM_BOTTOMALIGN, TPM_RETURNCMD, TPM_RIGHTBUTTON, TrackPopupMenuEx,
+ WINDOW_EX_STYLE, WM_APP, WM_CONTEXTMENU, WM_NULL, WM_POWERBROADCAST, WM_SETTINGCHANGE,
+ WNDCLASSEXW, WS_EX_TOOLWINDOW, WS_POPUP,
+ },
+ },
+ },
+ core::{PCWSTR, w},
+};
+
+/// What the user or the system asked for.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TrayEvent {
+ Open,
+ FindPhone,
+ Quit,
+ /// The PC woke from sleep.
+ Resumed,
+ /// Dark mode or the animation setting changed.
+ AppearanceChanged,
+}
+
+/// Menu texts (translated by the caller).
+#[derive(Debug, Clone)]
+pub struct MenuLabels {
+ pub open: String,
+ pub find_phone: String,
+ pub quit: String,
+}
+
+const CALLBACK_MESSAGE: u32 = WM_APP + 1;
+const ICON_ID: u32 = 1;
+const CMD_OPEN: u32 = 1;
+const CMD_FIND_PHONE: u32 = 2;
+const CMD_QUIT: u32 = 3;
+const PBT_APMRESUMEAUTOMATIC: usize = 0x12;
+/// NIN_SELECT | NINF_KEY (shellapi.h): the icon was activated with the keyboard.
+const NIN_KEYSELECT: u32 = NIN_SELECT | 0x1;
+const SPI_SETCLIENTAREAANIMATION: usize = 0x1043;
+
+type Handler = Box<dyn Fn(TrayEvent)>;
+
+thread_local! {
+ static HANDLER: RefCell<Option<Handler>> = RefCell::new(None);
+ static LABELS: RefCell<Option<MenuLabels>> = const { RefCell::new(None) };
+ static CAN_FIND_PHONE: Cell<bool> = const { Cell::new(false) };
+ static TOOLTIP: RefCell<String> = const { RefCell::new(String::new()) };
+ static ICON: Cell<HICON> = Cell::new(HICON::default());
+ static TASKBAR_CREATED: Cell<u32> = const { Cell::new(0) };
+}
+
+/// The tray icon. Removed when dropped. Create and drop on the GUI thread.
+#[derive(Debug)]
+pub struct Tray {
+ hwnd: HWND,
+}
+
+impl Tray {
+ pub fn create(
+ tooltip: &str,
+ labels: MenuLabels,
+ handler: impl Fn(TrayEvent) + 'static,
+ ) -> windows::core::Result<Tray> {
+ HANDLER.with(|h| *h.borrow_mut() = Some(Box::new(handler)));
+ LABELS.with(|l| *l.borrow_mut() = Some(labels));
+ TOOLTIP.with(|t| *t.borrow_mut() = tooltip.to_owned());
+ // SAFETY: standard window class registration and creation; the
+ // window procedure only touches this thread's thread-locals.
+ let hwnd = unsafe {
+ let instance = GetModuleHandleW(None)?;
+ let class = WNDCLASSEXW {
+ cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
+ lpfnWndProc: Some(window_proc),
+ hInstance: instance.into(),
+ lpszClassName: w!("Nectarlink.TrayWindow"),
+ ..Default::default()
+ };
+ // Registering twice (a second Tray) fails harmlessly.
+ RegisterClassExW(&class);
+ TASKBAR_CREATED.with(|t| t.set(RegisterWindowMessageW(w!("TaskbarCreated"))));
+ // A hidden top-level window (not message-only) so it also gets
+ // power and setting broadcasts.
+ CreateWindowExW(
+ WS_EX_TOOLWINDOW | WINDOW_EX_STYLE(0),
+ w!("Nectarlink.TrayWindow"),
+ w!("Nectarlink"),
+ WS_POPUP,
+ 0,
+ 0,
+ 0,
+ 0,
+ None,
+ None,
+ Some(instance.into()),
+ None,
+ )?
+ };
+ ICON.with(|i| i.set(create_icon().unwrap_or_default()));
+ add_icon(hwnd);
+ Ok(Tray { hwnd })
+ }
+
+ pub fn set_tooltip(&self, text: &str) {
+ TOOLTIP.with(|t| *t.borrow_mut() = text.to_owned());
+ let mut data = icon_data(self.hwnd);
+ data.uFlags = NIF_TIP | NIF_SHOWTIP;
+ // SAFETY: data is fully initialized for this window's icon.
+ unsafe {
+ let _ = Shell_NotifyIconW(NIM_MODIFY, &data);
+ }
+ }
+
+ /// Whether "Find my phone" is offered (a phone is paired).
+ pub fn set_find_phone_enabled(&self, enabled: bool) {
+ CAN_FIND_PHONE.with(|c| c.set(enabled));
+ }
+}
+
+impl Drop for Tray {
+ fn drop(&mut self) {
+ let data = icon_data(self.hwnd);
+ // SAFETY: removing our own icon and destroying our own window/icon.
+ unsafe {
+ let _ = Shell_NotifyIconW(NIM_DELETE, &data);
+ let _ = DestroyWindow(self.hwnd);
+ let icon = ICON.with(|i| i.replace(HICON::default()));
+ if !icon.is_invalid() {
+ let _ = DestroyIcon(icon);
+ }
+ }
+ HANDLER.with(|h| *h.borrow_mut() = None);
+ }
+}
+
+fn icon_data(hwnd: HWND) -> NOTIFYICONDATAW {
+ let mut data = NOTIFYICONDATAW {
+ cbSize: std::mem::size_of::<NOTIFYICONDATAW>() as u32,
+ hWnd: hwnd,
+ uID: ICON_ID,
+ uFlags: NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP,
+ uCallbackMessage: CALLBACK_MESSAGE,
+ hIcon: ICON.with(Cell::get),
+ ..Default::default()
+ };
+ TOOLTIP.with(|t| {
+ let wide: Vec<u16> = t.borrow().encode_utf16().take(data.szTip.len() - 1).collect();
+ data.szTip[..wide.len()].copy_from_slice(&wide);
+ });
+ data.Anonymous.uVersion = NOTIFYICON_VERSION_4;
+ data
+}
+
+fn add_icon(hwnd: HWND) {
+ let data = icon_data(hwnd);
+ // SAFETY: data is fully initialized for this window's icon.
+ unsafe {
+ if !Shell_NotifyIconW(NIM_ADD, &data).as_bool() {
+ tracing::warn!("can't add the tray icon");
+ return;
+ }
+ let _ = Shell_NotifyIconW(NIM_SETVERSION, &data);
+ }
+}
+
+/// Builds an HICON from the mark rendered at the small-icon size.
+fn create_icon() -> windows::core::Result<HICON> {
+ // SAFETY: GetSystemMetrics has no preconditions.
+ let size = unsafe { GetSystemMetrics(SM_CXSMICON) }.clamp(16, 64) as usize;
+ let rgba = super::icon::render(size);
+ // SAFETY: a top-down 32-bit DIB of `size`×`size`; we write exactly
+ // size*size*4 bytes into its pixel buffer, then hand both bitmaps to
+ // CreateIconIndirect, which copies them, and delete ours.
+ unsafe {
+ let header = BITMAPINFOHEADER {
+ biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
+ biWidth: size as i32,
+ biHeight: -(size as i32),
+ biPlanes: 1,
+ biBitCount: 32,
+ biCompression: BI_RGB.0,
+ ..Default::default()
+ };
+ let info = BITMAPINFO { bmiHeader: header, ..Default::default() };
+ let mut bits = std::ptr::null_mut();
+ let color: HBITMAP = CreateDIBSection(None, &info, DIB_RGB_COLORS, &mut bits, None, 0)?;
+ let pixels = std::slice::from_raw_parts_mut(bits.cast::<u8>(), size * size * 4);
+ for (dst, src) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(rgba.as_chunks::<4>().0) {
+ // RGBA → BGRA, straight alpha (what icons expect).
+ *dst = [src[2], src[1], src[0], src[3]];
+ }
+ let mask = CreateBitmap(size as i32, size as i32, 1, 1, None);
+ let icon = CreateIconIndirect(&ICONINFO {
+ fIcon: true.into(),
+ hbmMask: mask,
+ hbmColor: color,
+ ..Default::default()
+ });
+ let _ = DeleteObject(color.into());
+ let _ = DeleteObject(mask.into());
+ icon
+ }
+}
+
+fn emit(event: TrayEvent) {
+ HANDLER.with(|h| {
+ if let Some(handler) = h.borrow().as_ref() {
+ handler(event);
+ }
+ });
+}
+
+fn show_menu(hwnd: HWND, x: i32, y: i32) {
+ let Some(labels) = LABELS.with(|l| l.borrow().clone()) else { return };
+ let to_wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::<Vec<u16>>();
+ let (open, find, quit) = (to_wide(&labels.open), to_wide(&labels.find_phone), to_wide(&labels.quit));
+ // SAFETY: the menu and strings outlive TrackPopupMenuEx; the menu is
+ // destroyed afterwards. SetForegroundWindow/WM_NULL are the documented
+ // way to make the menu close when clicking elsewhere.
+ let command = unsafe {
+ let Ok(menu): windows::core::Result<HMENU> = CreatePopupMenu() else { return };
+ let find_flags = if CAN_FIND_PHONE.with(Cell::get) { MF_STRING } else { MF_STRING | MF_GRAYED };
+ let _ = AppendMenuW(menu, MF_STRING, CMD_OPEN as usize, PCWSTR(open.as_ptr()));
+ let _ = AppendMenuW(menu, find_flags, CMD_FIND_PHONE as usize, PCWSTR(find.as_ptr()));
+ let _ = AppendMenuW(menu, MF_SEPARATOR, 0, PCWSTR::null());
+ let _ = AppendMenuW(menu, MF_STRING, CMD_QUIT as usize, PCWSTR(quit.as_ptr()));
+ let _ = SetForegroundWindow(hwnd);
+ let command =
+ TrackPopupMenuEx(menu, (TPM_RETURNCMD | TPM_RIGHTBUTTON | TPM_BOTTOMALIGN).0, x, y, hwnd, None);
+ let _ = PostMessageW(Some(hwnd), WM_NULL, WPARAM(0), LPARAM(0));
+ let _ = DestroyMenu(menu);
+ command.0 as u32
+ };
+ match command {
+ CMD_OPEN => emit(TrayEvent::Open),
+ CMD_FIND_PHONE => emit(TrayEvent::FindPhone),
+ CMD_QUIT => emit(TrayEvent::Quit),
+ _ => {}
+ }
+}
+
+unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
+ match msg {
+ CALLBACK_MESSAGE => {
+ // NOTIFYICON_VERSION_4: the event is in LOWORD(lParam) and the
+ // anchor point in wParam.
+ let event = (lparam.0 & 0xFFFF) as u32;
+ match event {
+ NIN_SELECT | NIN_KEYSELECT => emit(TrayEvent::Open),
+ WM_CONTEXTMENU => {
+ let x = (wparam.0 & 0xFFFF) as i16 as i32;
+ let y = ((wparam.0 >> 16) & 0xFFFF) as i16 as i32;
+ show_menu(hwnd, x, y);
+ }
+ _ => {}
+ }
+ LRESULT(0)
+ }
+ WM_POWERBROADCAST => {
+ if wparam.0 == PBT_APMRESUMEAUTOMATIC {
+ emit(TrayEvent::Resumed);
+ }
+ LRESULT(1)
+ }
+ WM_SETTINGCHANGE => {
+ // SAFETY: for WM_SETTINGCHANGE, lParam is null or a valid
+ // null-terminated string for the duration of the message.
+ let area =
+ if lparam.0 == 0 { None } else { unsafe { PCWSTR(lparam.0 as *const u16).to_string().ok() } };
+ if area.as_deref() == Some("ImmersiveColorSet") || wparam.0 == SPI_SETCLIENTAREAANIMATION {
+ emit(TrayEvent::AppearanceChanged);
+ }
+ LRESULT(0)
+ }
+ // Explorer restarted: the tray is new and our icon must be re-added.
+ m if m != 0 && m == TASKBAR_CREATED.with(Cell::get) => {
+ add_icon(hwnd);
+ LRESULT(0)
+ }
+ // SAFETY: default handling for everything else.
+ _ => unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) },
+ }
+}