Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
fix(linux): address PR #38 review feedback
Jochen Kirstätterceb7cb160c16
diff --git a/Cargo.lock b/Cargo.lockindex 8b3c4db..51bd3d6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -223,6 +223,40 @@ dependencies = ["winnow",]+[[package]]+name = "async-broadcast"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"+dependencies = [+ "event-listener",+ "event-listener-strategy",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-recursion"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]++[[package]]+name = "async-trait"+version = "0.1.92"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "async_io_stream"version = "0.3.3"@@ -1065,6 +1099,12 @@ version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"+[[package]]+name = "endi"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"+[[package]]name = "enum-assoc"version = "1.4.1"@@ -1076,6 +1116,27 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "enumflags2"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"+dependencies = [+ "enumflags2_derive",+ "serde",+]++[[package]]+name = "enumflags2_derive"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "equivalent"version = "1.0.2"@@ -1092,6 +1153,26 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "event-listener"+version = "5.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"+dependencies = [+ "parking",+ "pin-project-lite",+]++[[package]]+name = "event-listener-strategy"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"+dependencies = [+ "event-listener",+ "pin-project-lite",+]+[[package]]name = "fallible-iterator"version = "0.3.0"@@ -1432,6 +1513,12 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]name = "hickory-proto"version = "0.26.3"@@ -2206,6 +2293,15 @@ version = "2.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"+[[package]]+name = "memoffset"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"+dependencies = [+ "autocfg",+]+[[package]]name = "minimal-lexical"version = "0.2.1"@@ -2407,6 +2503,7 @@ dependencies = ["tracing-subscriber","windows","windows-core",+ "zbus",][[package]]@@ -2859,6 +2956,16 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]+name = "ordered-stream"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"+dependencies = [+ "futures-core",+ "pin-project-lite",+]+[[package]]name = "owned_ttf_parser"version = "0.25.1"@@ -3588,6 +3695,17 @@ dependencies = ["zmij",]+[[package]]+name = "serde_repr"+version = "0.1.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "serde_spanned"version = "1.1.1"@@ -3898,7 +4016,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand",- "getrandom 0.3.4",+ "getrandom 0.4.3","once_cell","rustix","windows-sys 0.61.2",@@ -4032,6 +4150,7 @@ dependencies = ["signal-hook-registry","socket2","tokio-macros",+ "tracing","windows-sys 0.61.2",]@@ -4282,6 +4401,17 @@ version = "1.20.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"+[[package]]+name = "uds_windows"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"+dependencies = [+ "memoffset",+ "tempfile",+ "windows-sys 0.61.2",+]+[[package]]name = "unicode-ident"version = "1.0.26"@@ -4474,6 +4604,17 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"+[[package]]+name = "uuid"+version = "1.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"+dependencies = [+ "js-sys",+ "serde_core",+ "wasm-bindgen",+]+[[package]]name = "valuable"version = "0.1.1"@@ -5088,6 +5229,71 @@ dependencies = ["synstructure",]+[[package]]+name = "zbus"+version = "5.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"+dependencies = [+ "async-broadcast",+ "async-recursion",+ "async-trait",+ "enumflags2",+ "event-listener",+ "futures-core",+ "futures-lite",+ "hex",+ "libc",+ "ordered-stream",+ "rustix",+ "serde",+ "serde_repr",+ "tokio",+ "tracing",+ "uds_windows",+ "uuid",+ "windows-sys 0.61.2",+ "winnow",+ "zbus_macros",+ "zbus_names",+ "zvariant",+]++[[package]]+name = "zbus_macros"+version = "5.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "zbus_names",+ "zvariant",+ "zvariant_utils",+]++[[package]]+name = "zbus_names"+version = "4.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd"+dependencies = [+ "serde",+ "winnow",+ "zvariant",+]++[[package]]+name = "zcheapstr"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473"+dependencies = [+ "serde",+]+[[package]]name = "zerocopy"version = "0.8.59"@@ -5187,3 +5393,44 @@ name = "zmij"version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"++[[package]]+name = "zvariant"+version = "5.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7"+dependencies = [+ "endi",+ "enumflags2",+ "serde",+ "winnow",+ "zcheapstr",+ "zvariant_derive",+ "zvariant_utils",+]++[[package]]+name = "zvariant_derive"+version = "5.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 3.0.6",+ "zvariant_utils",+]++[[package]]+name = "zvariant_utils"+version = "4.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"+dependencies = [+ "proc-macro2",+ "quote",+ "serde",+ "syn 3.0.6",+ "winnow",+]diff --git a/Cargo.toml b/Cargo.tomlindex 524ac0d..67ada86 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -69,6 +69,7 @@ url = "2.5"windows = "0.62"# The same version windows itself depends on, never newer on its own.windows-core = "0.62"+zbus = { version = "5", default-features = false, features = ["tokio", "blocking-api"] }[workspace.lints.rust]unsafe_code = "deny"diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.tomlindex 0eaaa44..015e65b 100644--- a/desktop/app/Cargo.toml+++ b/desktop/app/Cargo.toml@@ -116,6 +116,7 @@ windows = { workspace = true, features = [[target.'cfg(target_os = "linux")'.dependencies]libc = "0.2"+zbus.workspace = true[build-dependencies]cxx-qt-build = { workspace = true, features = ["link_qt_object_files"] }diff --git a/desktop/app/build.rs b/desktop/app/build.rsindex 0803f6b..b5757ca 100644--- a/desktop/app/build.rs+++ b/desktop/app/build.rs@@ -365,8 +365,11 @@ 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")+ let mut builder = CxxQtBuilder::new_qml_module(module).qt_module("Quick");+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("linux") {+ builder = builder.qt_module("Widgets");+ }+ builder.include_dir("cpp").cpp_files(["cpp/app_helpers.cpp",@@ -407,6 +410,7 @@ fn main() {println!("cargo:rustc-link-lib=user32");} else if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("linux") {println!("cargo:rustc-link-lib=Qt6Quick");+ println!("cargo:rustc-link-lib=Qt6Widgets");println!("cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN:$ORIGIN/lib:$ORIGIN/../lib:$ORIGIN/../lib/nectarlink/lib");diff --git a/desktop/app/cpp/app_helpers.cpp b/desktop/app/cpp/app_helpers.cppindex 619415c..8d35aaa 100644--- a/desktop/app/cpp/app_helpers.cpp+++ b/desktop/app/cpp/app_helpers.cpp@@ -33,6 +33,20 @@#include <malloc.h>#endif+#ifdef __linux__+#include <QtCore/QMetaObject>+#include <QtCore/QThread>+#include <QtGui/QAction>+#include <QtGui/QClipboard>+#include <QtWidgets/QApplication>+#include <QtWidgets/QMenu>+#include <QtWidgets/QSystemTrayIcon>+#include <chrono>+#include <condition_variable>+#include <deque>+#include <mutex>+#endif+namespace {QIcon &appIcon(){@@ -538,3 +552,263 @@ uint64_t mac_free_space(rust::Str path, bool &ok)ok = true;return static_cast<uint64_t>(available);}++#ifdef __linux__+namespace {+struct LinuxClipboardWatch {+ std::mutex mutex;+ std::condition_variable cv;+ std::atomic<uint64_t> seq { 1 };+};++LinuxClipboardWatch &linuxClipboardWatch()+{+ static LinuxClipboardWatch watch;+ return watch;+}++struct LinuxTrayState {+ QPointer<QSystemTrayIcon> icon;+ QPointer<QMenu> menu;+ QPointer<QAction> findPhoneAction;+ std::mutex mutex;+ std::condition_variable cv;+ std::deque<std::string> actions;+};++LinuxTrayState &linuxTray()+{+ static LinuxTrayState state;+ return state;+}++void pushTrayAction(const char *action)+{+ auto &st = linuxTray();+ {+ std::lock_guard<std::mutex> lock(st.mutex);+ st.actions.emplace_back(action);+ }+ st.cv.notify_all();+}++template <typename F>+void runOnQtMainThread(F &&fn)+{+ QCoreApplication *app = QCoreApplication::instance();+ if (!app)+ return;+ if (QThread::currentThread() == app->thread()) {+ fn();+ } else {+ QMetaObject::invokeMethod(app, std::forward<F>(fn), Qt::QueuedConnection);+ }+}+} // namespace+#endif++std::unique_ptr<QGuiApplication> create_qt_app()+{+ static int s_argc = 1;+ static char s_arg0[] = "nectarlink";+ static char *s_argv[] = { s_arg0, nullptr };+#ifdef __linux__+ auto app = std::unique_ptr<QGuiApplication>(new QApplication(s_argc, s_argv));+ if (QClipboard *cb = QGuiApplication::clipboard()) {+ QObject::connect(cb, &QClipboard::dataChanged, cb, []() {+ linux_clipboard_notify_external();+ });+ }+ return app;+#else+ return std::make_unique<QGuiApplication>(s_argc, s_argv);+#endif+}++void linux_tray_setup(+ rust::Str icon_path,+ rust::Str tooltip,+ rust::Str open_label,+ rust::Str command_palette_label,+ rust::Str shelf_label,+ rust::Str take_photo_label,+ rust::Str scan_document_label,+ rust::Str find_phone_label,+ rust::Str open_link_label,+ rust::Str quit_label)+{+#ifdef __linux__+ const QString iconPath = QString::fromUtf8(icon_path.data(), static_cast<qsizetype>(icon_path.size()));+ const QString tooltipStr = QString::fromUtf8(tooltip.data(), static_cast<qsizetype>(tooltip.size()));+ const QString openStr = QString::fromUtf8(open_label.data(), static_cast<qsizetype>(open_label.size()));+ const QString paletteStr = QString::fromUtf8(command_palette_label.data(), static_cast<qsizetype>(command_palette_label.size()));+ const QString shelfStr = QString::fromUtf8(shelf_label.data(), static_cast<qsizetype>(shelf_label.size()));+ const QString photoStr = QString::fromUtf8(take_photo_label.data(), static_cast<qsizetype>(take_photo_label.size()));+ const QString scanStr = QString::fromUtf8(scan_document_label.data(), static_cast<qsizetype>(scan_document_label.size()));+ const QString findPhoneStr = QString::fromUtf8(find_phone_label.data(), static_cast<qsizetype>(find_phone_label.size()));+ const QString openLinkStr = QString::fromUtf8(open_link_label.data(), static_cast<qsizetype>(open_link_label.size()));+ const QString quitStr = QString::fromUtf8(quit_label.data(), static_cast<qsizetype>(quit_label.size()));++ runOnQtMainThread([=]() {+ if (!qobject_cast<QApplication *>(QCoreApplication::instance()))+ return;+ auto &st = linuxTray();+ if (st.icon) {+ st.icon->hide();+ delete st.icon.data();+ }+ if (st.menu) {+ delete st.menu.data();+ }+ {+ std::lock_guard<std::mutex> lock(st.mutex);+ st.actions.clear();+ }++ auto *menu = new QMenu();+ QObject::connect(menu->addAction(openStr), &QAction::triggered, menu, []() { pushTrayAction("OPEN"); });+ QObject::connect(menu->addAction(paletteStr), &QAction::triggered, menu, []() { pushTrayAction("COMMAND_PALETTE"); });+ QObject::connect(menu->addAction(shelfStr), &QAction::triggered, menu, []() { pushTrayAction("SHELF"); });+ menu->addSeparator();+ QObject::connect(menu->addAction(photoStr), &QAction::triggered, menu, []() { pushTrayAction("TAKE_PHOTO"); });+ QObject::connect(menu->addAction(scanStr), &QAction::triggered, menu, []() { pushTrayAction("SCAN_DOCUMENT"); });+ QAction *findPhone = menu->addAction(findPhoneStr);+ findPhone->setEnabled(false);+ QObject::connect(findPhone, &QAction::triggered, menu, []() { pushTrayAction("FIND_PHONE"); });+ QObject::connect(menu->addAction(openLinkStr), &QAction::triggered, menu, []() { pushTrayAction("OPEN_LINK"); });+ menu->addSeparator();+ QObject::connect(menu->addAction(quitStr), &QAction::triggered, menu, []() { pushTrayAction("QUIT"); });++ auto *tray = new QSystemTrayIcon(QCoreApplication::instance());+ QIcon icon = appIcon();+ if (icon.isNull() && !iconPath.isEmpty())+ icon = QIcon(iconPath);+ tray->setIcon(icon);+ tray->setToolTip(tooltipStr);+ tray->setContextMenu(menu);+ QObject::connect(tray, &QSystemTrayIcon::activated, tray, [](QSystemTrayIcon::ActivationReason reason) {+ if (reason == QSystemTrayIcon::Trigger || reason == QSystemTrayIcon::DoubleClick)+ pushTrayAction("OPEN");+ });+ tray->show();++ st.icon = tray;+ st.menu = menu;+ st.findPhoneAction = findPhone;+ });+#else+ (void)icon_path;+ (void)tooltip;+ (void)open_label;+ (void)command_palette_label;+ (void)shelf_label;+ (void)take_photo_label;+ (void)scan_document_label;+ (void)find_phone_label;+ (void)open_link_label;+ (void)quit_label;+#endif+}++void linux_tray_set_tooltip(rust::Str tooltip)+{+#ifdef __linux__+ const QString tooltipStr = QString::fromUtf8(tooltip.data(), static_cast<qsizetype>(tooltip.size()));+ runOnQtMainThread([tooltipStr]() {+ if (auto *icon = linuxTray().icon.data())+ icon->setToolTip(tooltipStr);+ });+#else+ (void)tooltip;+#endif+}++void linux_tray_set_find_phone_enabled(bool enabled)+{+#ifdef __linux__+ runOnQtMainThread([enabled]() {+ if (auto *act = linuxTray().findPhoneAction.data())+ act->setEnabled(enabled);+ });+#else+ (void)enabled;+#endif+}++void linux_tray_teardown()+{+#ifdef __linux__+ auto &st = linuxTray();+ st.cv.notify_all();+ runOnQtMainThread([]() {+ auto &s = linuxTray();+ if (s.icon) {+ s.icon->hide();+ delete s.icon.data();+ }+ if (s.menu) {+ delete s.menu.data();+ }+ s.findPhoneAction = nullptr;+ });+#endif+}++rust::String linux_tray_wait_action(uint32_t timeout_ms)+{+#ifdef __linux__+ auto &st = linuxTray();+ std::unique_lock<std::mutex> lock(st.mutex);+ if (st.actions.empty() && timeout_ms > 0) {+ st.cv.wait_for(lock, std::chrono::milliseconds(timeout_ms));+ }+ if (!st.actions.empty()) {+ std::string next = std::move(st.actions.front());+ st.actions.pop_front();+ return rust::String(next);+ }+#else+ (void)timeout_ms;+#endif+ return rust::String();+}++uint64_t linux_clipboard_sequence()+{+#ifdef __linux__+ return linuxClipboardWatch().seq.load(std::memory_order_acquire);+#else+ return 0;+#endif+}++uint64_t linux_clipboard_wait_change(uint64_t last_seq, uint32_t timeout_ms)+{+#ifdef __linux__+ auto &w = linuxClipboardWatch();+ uint64_t cur = w.seq.load(std::memory_order_acquire);+ if (cur != last_seq || timeout_ms == 0)+ return cur;+ std::unique_lock<std::mutex> lock(w.mutex);+ w.cv.wait_for(lock, std::chrono::milliseconds(timeout_ms), [&w, last_seq]() {+ return w.seq.load(std::memory_order_acquire) != last_seq;+ });+ return w.seq.load(std::memory_order_acquire);+#else+ (void)last_seq;+ (void)timeout_ms;+ return 0;+#endif+}++void linux_clipboard_notify_external()+{+#ifdef __linux__+ auto &w = linuxClipboardWatch();+ {+ std::lock_guard<std::mutex> lock(w.mutex);+ w.seq.fetch_add(1, std::memory_order_release);+ }+ w.cv.notify_all();+#endif+}diff --git a/desktop/app/cpp/app_helpers.h b/desktop/app/cpp/app_helpers.hindex 27da9f6..ed649c2 100644--- a/desktop/app/cpp/app_helpers.h+++ b/desktop/app/cpp/app_helpers.h@@ -4,6 +4,13 @@#include <rust/cxx.h>#include <cstdint>+#include <memory>++class QGuiApplication;++// Creates the Qt application instance (`QApplication` on Linux so+// `QSystemTrayIcon` and `QMenu` work; `QGuiApplication` elsewhere).+std::unique_ptr<QGuiApplication> create_qt_app();// Qt setup that must happen before QGuiApplication is created.void prepare_qt();@@ -62,3 +69,24 @@ bool mac_clipboard_write_text(rust::Str text, bool is_private);int64_t mac_local_offset_ms(int64_t at_ms);uint64_t mac_free_space(rust::Str path, bool &ok);++// Linux QSystemTrayIcon + QMenu and QClipboard change notifications.+void linux_tray_setup(+ rust::Str icon_path,+ rust::Str tooltip,+ rust::Str open_label,+ rust::Str command_palette_label,+ rust::Str shelf_label,+ rust::Str take_photo_label,+ rust::Str scan_document_label,+ rust::Str find_phone_label,+ rust::Str open_link_label,+ rust::Str quit_label);+void linux_tray_set_tooltip(rust::Str tooltip);+void linux_tray_set_find_phone_enabled(bool enabled);+void linux_tray_teardown();+rust::String linux_tray_wait_action(uint32_t timeout_ms);++uint64_t linux_clipboard_sequence();+uint64_t linux_clipboard_wait_change(uint64_t last_seq, uint32_t timeout_ms);+void linux_clipboard_notify_external();diff --git a/desktop/app/src/bridge/native.rs b/desktop/app/src/bridge/native.rsindex 7903c20..6a0c85d 100644--- a/desktop/app/src/bridge/native.rs+++ b/desktop/app/src/bridge/native.rs@@ -6,9 +6,14 @@ pub mod ffi {unsafe extern "C++" {include!("app_helpers.h");include!("video_view.h");+ include!("cxx-qt-lib/qguiapplication.h");include!("cxx-qt-lib/qqmlapplicationengine.h");+ type QGuiApplication = cxx_qt_lib::QGuiApplication;type QQmlApplicationEngine = cxx_qt_lib::QQmlApplicationEngine;+ #[allow(dead_code)]+ fn create_qt_app() -> UniquePtr<QGuiApplication>;+/// The latest picture of a video stream (32-bit BGRX rows), for/// `VideoView`s showing it. Any thread.fn video_frame(stream: &str, width: u32, height: u32, bgrx: &[u8]);@@ -69,5 +74,41 @@ pub mod ffi {#[allow(dead_code)]fn mac_free_space(path: &str, ok: &mut bool) -> u64;++ #[allow(dead_code)]+ #[allow(clippy::too_many_arguments)]+ fn linux_tray_setup(+ icon_path: &str,+ tooltip: &str,+ open_label: &str,+ command_palette_label: &str,+ shelf_label: &str,+ take_photo_label: &str,+ scan_document_label: &str,+ find_phone_label: &str,+ open_link_label: &str,+ quit_label: &str,+ );++ #[allow(dead_code)]+ fn linux_tray_set_tooltip(tooltip: &str);++ #[allow(dead_code)]+ fn linux_tray_set_find_phone_enabled(enabled: bool);++ #[allow(dead_code)]+ fn linux_tray_teardown();++ #[allow(dead_code)]+ fn linux_tray_wait_action(timeout_ms: u32) -> String;++ #[allow(dead_code)]+ fn linux_clipboard_sequence() -> u64;++ #[allow(dead_code)]+ fn linux_clipboard_wait_change(last_seq: u64, timeout_ms: u32) -> u64;++ #[allow(dead_code)]+ fn linux_clipboard_notify_external();}}diff --git a/desktop/app/src/doctor.rs b/desktop/app/src/doctor.rsindex 85508aa..14fafa9 100644--- a/desktop/app/src/doctor.rs+++ b/desktop/app/src/doctor.rs@@ -55,6 +55,9 @@ pub struct Facts {pub firewall: Option<windows_checks::Firewall>,/// Paired devices: link and discovery diagnostics.pub devices: Vec<DeviceFact>,+ /// Optional helper tools missing from `PATH` on Linux.+ #[cfg(target_os = "linux")]+ pub missing_tools: Vec<&'static str>,}/// Asks Windows and the core (blocking; call on a worker thread).@@ -81,7 +84,15 @@ pub fn gather() -> Facts {}).collect()});- Facts { local_address: adapters.local_address, vpn: adapters.vpn, networks, firewall, devices }+ Facts {+ local_address: adapters.local_address,+ vpn: adapters.vpn,+ networks,+ firewall,+ devices,+ #[cfg(target_os = "linux")]+ missing_tools: windows_checks::missing_tools(),+ }}/// A network's name as people say it. While Windows is still identifying@@ -263,6 +274,20 @@ pub fn diagnose(facts: &Facts, now_secs: i64) -> Vec<Check> {));}+ #[cfg(target_os = "linux")]+ if !facts.missing_tools.is_empty() {+ let list = facts.missing_tools.join(", ");+ checks.push(check(+ "linux-tools",+ Outcome::Warn,+ format!("Optional helper tools not found: {list}"),+ format!(+ "Install {list} with your package manager for full clipboard, window focus, Wi-Fi hotspot, BLE discovery, and firewall setup support."+ ),+ None,+ ));+ }+// Each phone.for (i, d) in facts.devices.iter().enumerate() {let name = &d.name;@@ -428,6 +453,8 @@ mod tests {networks: vec![("Home".into(), true)],firewall: Some(windows_checks::Firewall { on: true, allowed: true, blocked: false }),devices: vec![device_fact("Pixel", LinkState::Online { path: ConnectionPath::Lan, rtt_ms: 4 })],+ #[cfg(target_os = "linux")]+ missing_tools: Vec::new(),}}diff --git a/desktop/app/src/linux/autostart.rs b/desktop/app/src/linux/autostart.rsindex 28a3ab0..4f8b85a 100644--- a/desktop/app/src/linux/autostart.rs+++ b/desktop/app/src/linux/autostart.rs@@ -8,9 +8,29 @@ use std::{const DESKTOP_FILE_NAME: &str = "nectarlink.desktop";+/// Escapes a single argument for placement inside double quotes (`"..."`) on a+/// FreeDesktop `.desktop` `Exec=` line (`\`, `"`, `` ` ``, `$`, and literal `%`).+pub(crate) fn escape_desktop_exec_arg(raw: &str) -> String {+ let mut out = String::with_capacity(raw.len());+ for c in raw.chars() {+ if c == '\n' || c == '\r' || c.is_control() {+ continue;+ }+ match c {+ '\\' => out.push_str("\\\\"),+ '"' => out.push_str("\\\""),+ '`' => out.push_str("\\`"),+ '$' => out.push_str("\\$"),+ '%' => out.push_str("%%"),+ _ => out.push(c),+ }+ }+ out+}+/// The command line written into the autostart entry's `Exec=` line.pub fn command(exe: &Path) -> String {- format!("\"{}\" --minimized", exe.display())+ format!("\"{}\" --minimized", escape_desktop_exec_arg(&exe.to_string_lossy()))}fn autostart_file_path_in(config_dir: &Path) -> PathBuf {@@ -132,4 +152,13 @@ mod tests {assert!(!is_installed(Path::new("/home/user/repo/target/debug/nectarlink-desktop")));assert!(!is_installed(Path::new("/home/user/repo/target/release/nectarlink-desktop")));}++ #[test]+ fn command_escapes_desktop_entry_special_characters() {+ let exe = Path::new("/opt/my \"quoted\" $dir`1`\\bin%20/nectarlink-desktop");+ assert_eq!(+ command(exe),+ r#""/opt/my \"quoted\" \$dir\`1\`\\bin%%20/nectarlink-desktop" --minimized"#+ );+ }}diff --git a/desktop/app/src/linux/ble_beacon.rs b/desktop/app/src/linux/ble_beacon.rsindex f8a39b4..8eda06f 100644--- a/desktop/app/src/linux/ble_beacon.rs+++ b/desktop/app/src/linux/ble_beacon.rs@@ -134,13 +134,18 @@ fn stop_bluetoothctl_advertisement(child: Option<Child>) {}fn is_adapter_powered() -> bool {- if let Ok(out) = Command::new("busctl")- .args(["--system", "get-property", "org.bluez", "/org/bluez/hci0", "org.bluez.Adapter1", "Powered"])- .output()- && out.status.success()+ if let Ok(conn) = zbus::blocking::Connection::system()+ && let Ok(reply) = conn.call_method(+ Some("org.bluez"),+ "/org/bluez/hci0",+ Some("org.freedesktop.DBus.Properties"),+ "Get",+ &("org.bluez.Adapter1", "Powered"),+ )+ && let Ok(val) = reply.body().deserialize::<zbus::zvariant::OwnedValue>()+ && let Ok(powered) = bool::try_from(val){- let stdout = String::from_utf8_lossy(&out.stdout);- return stdout.trim().ends_with("true");+ return powered;}if let Ok(out) = Command::new("bluetoothctl").arg("show").output()&& out.status.success()diff --git a/desktop/app/src/linux/clipboard.rs b/desktop/app/src/linux/clipboard.rsindex 1d2b4d1..a03da2a 100644--- a/desktop/app/src/linux/clipboard.rs+++ b/desktop/app/src/linux/clipboard.rs@@ -10,17 +10,14 @@//! before updating the system clipboard so the watcher thread never echoes//! phone clipboard writes back to the phone.-use std::io::Write;+use std::io::{BufRead, BufReader, Write};use std::path::{Path, PathBuf};use std::process::{Command, Stdio};use std::sync::{Mutex, OnceLock};-use std::time::Duration;+use std::time::{Duration, Instant};use super::image::{self, Bitmap};-/// Poll interval for the background Linux clipboard watcher thread.-const POLL_INTERVAL: Duration = Duration::from_millis(450);-/// Content fingerprint used to deduplicate clipboard updates and suppress/// echoing NectarLink's own writes back to connected phones.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -155,6 +152,13 @@ pub(crate) fn is_kde_secret_value(bytes: &[u8]) -> bool {std::str::from_utf8(trimmed).ok().is_some_and(|s| s.trim().eq_ignore_ascii_case("secret"))}+/// Records the fingerprint of whatever is currently on the clipboard so that+/// pre-existing clipboard contents at app startup are never sent to the phone.+pub(crate) fn seed_initial_clipboard() {+ let initial = fingerprint(&read());+ *LAST_REPORTED.lock().unwrap_or_else(|e| e.into_inner()) = initial;+}+/// Starts watching the Linux clipboard on a background thread (`"clipboard"`)./// Newly copied text or images that are not marked private and were not/// written by NectarLink are passed to `on_copy`.@@ -168,15 +172,55 @@ whereif !has_display_server() {return;}+ seed_initial_clipboard();+ if is_wayland() {+ let _ = std::thread::Builder::new().name("clipboard-wl-watch".into()).spawn(wayland_watch_loop);+ }let spawned = std::thread::Builder::new().name("clipboard".into()).spawn(watcher_loop);if let Err(e) = spawned {tracing::warn!(error = %e, "can't start Linux clipboard watcher");}}+/// Runs `wl-paste --watch` on Wayland so clipboard changes while NectarLink is+/// unfocused are detected on compositors that implement `wlr-data-control` or+/// `ext-data-control`. If the compositor does not support data-control (for+/// example GNOME Wayland), `wl-paste --watch` exits immediately and we do not+/// respawn it, relying on `QClipboard::dataChanged` instead.+fn wayland_watch_loop() {+ let started = Instant::now();+ let Ok(mut child) = Command::new("wl-paste")+ .args(["--watch", "printf", "\\n"])+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ else {+ return;+ };+ if let Some(stdout) = child.stdout.take() {+ let reader = BufReader::new(stdout);+ for line in reader.lines() {+ if line.is_err() {+ break;+ }+ crate::bridge::native::ffi::linux_clipboard_notify_external();+ }+ }+ let _ = child.wait();+ if started.elapsed() < Duration::from_secs(2) {+ tracing::debug!("wl-paste --watch exited early; relying on QClipboard::dataChanged");+ }+}+fn watcher_loop() {+ let mut last_seq = crate::bridge::native::ffi::linux_clipboard_sequence();loop {- std::thread::sleep(POLL_INTERVAL);+ let next_seq = crate::bridge::native::ffi::linux_clipboard_wait_change(last_seq, 2000);+ if next_seq == last_seq {+ continue;+ }+ last_seq = next_seq;let clip = read();if let Some(on_copy) = ON_COPY.get() {let _ = report_if_changed(clip, on_copy);@@ -928,6 +972,15 @@ mod tests {assert!(report_if_changed(user_clip.clone(), |c| reported.push(c)));assert!(!report_if_changed(user_clip, |c| reported.push(c)));assert_eq!(reported.len(), 1);++ // Pre-existing clipboard contents when start() runs must be seeded into+ // LAST_REPORTED so the first clipboard event does not send stale content.+ *LAST_CLIP.lock().unwrap_or_else(|e| e.into_inner()) =+ Clip::Text { text: "already on clipboard before launch".into(), html: None, rtf: None };+ *LAST_REPORTED.lock().unwrap_or_else(|e| e.into_inner()) = None;+ seed_initial_clipboard();+ assert!(!report_if_changed(read(), |c| reported.push(c)));+ assert_eq!(reported.len(), 1);}#[test]diff --git a/desktop/app/src/linux/doctor.rs b/desktop/app/src/linux/doctor.rsindex b5bcb54..0748703 100644--- a/desktop/app/src/linux/doctor.rs+++ b/desktop/app/src/linux/doctor.rs@@ -235,35 +235,59 @@ pub fn adapters() -> Adapters {Adapters { local_address, vpn }}+/// Returns the names of optional session-relevant helper commands that are not+/// currently installed on `PATH` (`wl-copy`/`wl-paste` on Wayland,+/// `xclip`/`xdotool` on X11, and `xdg-open`, `nmcli`, `bluetoothctl`, `pkexec`).+pub fn missing_tools() -> Vec<&'static str> {+ let mut missing = Vec::new();+ if std::env::var_os("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty()) {+ for tool in ["wl-copy", "wl-paste"] {+ if !has_command(tool) {+ missing.push(tool);+ }+ }+ }+ if std::env::var_os("DISPLAY").is_some_and(|v| !v.is_empty()) {+ for tool in ["xclip", "xdotool"] {+ if !has_command(tool) {+ missing.push(tool);+ }+ }+ }+ for tool in ["xdg-open", "nmcli", "bluetoothctl", "pkexec"] {+ if !has_command(tool) {+ missing.push(tool);+ }+ }+ missing+}+pub fn fix_firewall(_exe: &Path) -> Result<bool> {if is_service_active("ufw") || has_command("ufw") {- let status = super::elevated::run_elevated(- Path::new("sh"),- &["-c", "ufw allow 7718/tcp && ufw allow 7718/udp && ufw allow 5353/udp"],- );- return Ok(matches!(status, Ok(0)));- }- if is_service_active("firewalld") || has_command("firewall-cmd") {let status = super::elevated::run_elevated(Path::new("sh"),&["-c",- "firewall-cmd --permanent --add-port=7718/tcp --add-port=7718/udp --add-port=5353/udp && firewall-cmd --reload",+ "for cidr in 192.168.0.0/16 10.0.0.0/8 172.16.0.0/12 fe80::/10; do \+ ufw allow from \"$cidr\" to any port 7718 proto tcp && \+ ufw allow from \"$cidr\" to any port 7718 proto udp && \+ ufw allow from \"$cidr\" to any port 5353 proto udp || exit 1; \+ done",],);return Ok(matches!(status, Ok(0)));}- if is_service_active("nftables") {+ if is_service_active("firewalld") || has_command("firewall-cmd") {let status = super::elevated::run_elevated(Path::new("sh"),&["-c",- "nft add rule inet filter input tcp dport 7718 accept; nft add rule inet filter input udp dport { 5353, 7718 } accept",+ "firewall-cmd --permanent --add-port=7718/tcp --add-port=7718/udp --add-port=5353/udp && firewall-cmd --reload",],);return Ok(matches!(status, Ok(0)));}- Ok(true)+ Ok(false)}pub fn open_firewall_settings() -> bool {@@ -312,6 +336,20 @@ To Action FromSome(Firewall { on: true, allowed: true, blocked: false }));+ let subnet_scoped_allowed_output = "\+Status: active++To Action From+-- ------ ----+7718/tcp ALLOW 192.168.0.0/16+7718/udp ALLOW 192.168.0.0/16+5353/udp ALLOW 192.168.0.0/16+";+ assert_eq!(+ parse_ufw_status(subnet_scoped_allowed_output),+ Some(Firewall { on: true, allowed: true, blocked: false })+ );+let blocked_output = "\Status: activediff --git a/desktop/app/src/linux/jumplist.rs b/desktop/app/src/linux/jumplist.rsindex 4a02a2d..734ad80 100644--- a/desktop/app/src/linux/jumplist.rs+++ b/desktop/app/src/linux/jumplist.rs@@ -67,11 +67,7 @@ pub fn write_desktop_file_to() -> std::io::Result<PathBuf> {std::fs::create_dir_all(dir)?;let desktop_path = dir.join("nectarlink.desktop");- let exe_str: String = exe- .to_string_lossy()- .chars()- .filter(|&c| c != '\n' && c != '\r' && c != '"' && !c.is_control())- .collect();+ let exe_str = super::autostart::escape_desktop_exec_arg(&exe.to_string_lossy());let icon_str: String =icon_path.to_string_lossy().chars().filter(|&c| c != '\n' && c != '\r' && !c.is_control()).collect();@@ -138,11 +134,7 @@ pub fn unregister() {pub fn build_task_arguments(action: &str, custom_data_dir: Option<&Path>) -> String {match custom_data_dir {Some(dir) => {- let clean: String = dir- .to_string_lossy()- .chars()- .filter(|&c| c != '\n' && c != '\r' && c != '"' && !c.is_control())- .collect();+ let clean = super::autostart::escape_desktop_exec_arg(&dir.to_string_lossy());format!("--data-dir \"{clean}\" {ARG} {action}")}None => format!("{ARG} {action}"),diff --git a/desktop/app/src/linux/shell.rs b/desktop/app/src/linux/shell.rsindex 1234ff8..7f52a63 100644--- a/desktop/app/src/linux/shell.rs+++ b/desktop/app/src/linux/shell.rs@@ -1,6 +1,6 @@// SPDX-License-Identifier: GPL-3.0-or-later//! Opening URLs, files, folders, and power actions (lock, sleep) on Linux via-//! `xdg-open`, `dbus-send`, `loginctl`, and `systemctl`.+//! `xdg-open`, D-Bus (`org.freedesktop.FileManager1`), `loginctl`, and `systemctl`.use std::{fs,@@ -87,23 +87,17 @@ pub fn open_folder(path: &Path) -> Result<(), String> {pub fn select_in_explorer(path: &Path) -> Result<(), String> {let abs = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());let file_uri = format!("file://{}", abs.to_string_lossy());- let array_arg = format!("array:string:{file_uri}");- let dbus_ok = Command::new("dbus-send")- .args([- "--session",- "--dest=org.freedesktop.FileManager1",- "--type=method_call",- "/org/freedesktop/FileManager1",- "org.freedesktop.FileManager1.ShowItems",- &array_arg,- "string:",- ])- .stdin(Stdio::null())- .stdout(Stdio::null())- .stderr(Stdio::null())- .status()- .is_ok_and(|s| s.success());- if dbus_ok {+ if let Ok(conn) = zbus::blocking::Connection::session()+ && conn+ .call_method(+ Some("org.freedesktop.FileManager1"),+ "/org/freedesktop/FileManager1",+ Some("org.freedesktop.FileManager1"),+ "ShowItems",+ &(vec![file_uri.as_str()], ""),+ )+ .is_ok()+ {return Ok(());}let folder = abs.parent().unwrap_or(&abs);diff --git a/desktop/app/src/linux/shortcut.rs b/desktop/app/src/linux/shortcut.rsindex 2cefc4c..9031ded 100644--- a/desktop/app/src/linux/shortcut.rs+++ b/desktop/app/src/linux/shortcut.rs@@ -86,7 +86,8 @@ pub fn write(path: &Path, shortcut: &Shortcut) -> Result<()> {if let Some(parent) = path.parent() {std::fs::create_dir_all(parent)?;}- let target = sanitize_single_line(&shortcut.target.to_string_lossy());+ let raw_target = sanitize_single_line(&shortcut.target.to_string_lossy());+ let exec_target = super::autostart::escape_desktop_exec_arg(&shortcut.target.to_string_lossy());let args = sanitize_single_line(&shortcut.arguments);let desc = sanitize_single_line(&shortcut.description);@@ -95,10 +96,10 @@ pub fn write(path: &Path, shortcut: &Shortcut) -> Result<()> {Type=Application\n\Name=NectarLink\n\Comment={desc}\n\- Exec=\"{target}\" {args}\n\+ Exec=\"{exec_target}\" {args}\n\Icon=nectarlink\n\Terminal=false\n\- X-NectarLink-Target={target}\n\+ X-NectarLink-Target={raw_target}\n\X-NectarLink-Args={args}\n\X-NectarLink-Comment={desc}\n",);@@ -263,7 +264,8 @@ pub fn write_file_manager_integrations(desired_nautilus.insert(label.clone());desired_desktop.insert(desktop_filename.clone());- let target = sanitize_shell_path(&sc.target.to_string_lossy());+ let shell_target = sanitize_shell_path(&sc.target.to_string_lossy());+ let exec_target = super::autostart::escape_desktop_exec_arg(&sc.target.to_string_lossy());let args = sanitize_exec_args(&sc.arguments);let comment = sanitize_single_line(&sc.description);@@ -275,9 +277,9 @@ pub fn write_file_manager_integrations(if [ -n \"${{NAUTILUS_SCRIPT_SELECTED_FILE_PATHS:-}}\" ]; then\n\IFS='\n'\n\set -f\n\- exec \"{target}\" {args} $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS\n\+ exec \"{shell_target}\" {args} $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS\n\else\n\- exec \"{target}\" {args} \"$@\"\n\+ exec \"{shell_target}\" {args} \"$@\"\n\fi\n",);write_file_nofollow(&nautilus_path, &script, 0o755)?;@@ -294,7 +296,7 @@ pub fn write_file_manager_integrations([Desktop Action NectarLinkSend_{dev_id}]\n\Name={label}\n\Icon=nectarlink\n\- Exec=\"{target}\" {args} %F\n"+ Exec=\"{exec_target}\" {args} %F\n");write_file_nofollow(&kio_path, &kio_content, 0o644)?;@@ -310,7 +312,7 @@ pub fn write_file_manager_integrations(\n\[X-Action-Profile profile-zero]\n\MimeTypes=all/allfiles;\n\- Exec=\"{target}\" {args} %F\n\+ Exec=\"{exec_target}\" {args} %F\n\Name=Default profile\n",);write_file_nofollow(&action_path, &action_content, 0o644)?;diff --git a/desktop/app/src/linux/toast.rs b/desktop/app/src/linux/toast.rsindex 5eb00e8..b1b7b02 100644--- a/desktop/app/src/linux/toast.rs+++ b/desktop/app/src/linux/toast.rs@@ -4,10 +4,9 @@use std::collections::HashMap;use std::fmt;-use std::io::{BufRead, BufReader};use std::path::PathBuf;-use std::process::{Command, Stdio};use std::sync::{Mutex, OnceLock};+use std::time::Duration;pub const AUMID: &str = "Nectarlink.Desktop";pub const CALL_ANSWER: &str = "answer";@@ -448,47 +447,71 @@ fn compute_progress_percent(progress: &Progress) -> i32 {progress.value.map(|v| (v.clamp(0.0, 1.0) * 100.0).round() as i32).unwrap_or(0)}-fn build_actions_gvariant(actions: &[(String, String)], reply: Option<&(String, String)>) -> String {- let mut items: Vec<String> = Vec::new();- items.push("'default'".to_string());- items.push("'Open'".to_string());+fn build_actions_list(actions: &[(String, String)], reply: Option<&(String, String)>) -> Vec<String> {+ let mut items = Vec::with_capacity(2 + actions.len() * 2 + 2);+ items.push("default".to_string());+ items.push("Open".to_string());for (id, label) in actions {if !id.trim().is_empty() {- items.push(escape_gvariant_string(id));- items.push(escape_gvariant_string(label));+ items.push(id.clone());+ items.push(label.clone());}}if let Some((_action_id, placeholder)) = reply {let label = if placeholder.trim().is_empty() { "Reply" } else { placeholder.trim() };- items.push("'inline-reply'".to_string());- items.push(escape_gvariant_string(label));+ items.push("inline-reply".to_string());+ items.push(label.to_string());}- format!("[{}]", items.join(", "))+ items}-fn build_hints_gvariant(progress: Option<&Progress>, silent: bool, call: bool) -> String {- let mut entries = Vec::new();- let urgency = if call {+fn build_hints_map(+ progress: Option<&Progress>,+ silent: bool,+ call: bool,+) -> HashMap<&'static str, zbus::zvariant::Value<'static>> {+ let mut hints = HashMap::new();+ let urgency: u8 = if call {2} else if silent {0} else {1};- entries.push(format!("'urgency': <byte {urgency}>"));+ hints.insert("urgency", zbus::zvariant::Value::U8(urgency));if silent && !call {- entries.push("'suppress-sound': <true>".to_string());+ hints.insert("suppress-sound", zbus::zvariant::Value::Bool(true));}if let Some(prog) = progress {let pct = compute_progress_percent(prog);- entries.push(format!("'value': <int32 {pct}>"));+ hints.insert("value", zbus::zvariant::Value::I32(pct));}- format!("{{{}}}", entries.join(", "))+ hints}-fn escape_gvariant_string(s: &str) -> String {- let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");- format!("'{escaped}'")+static DBUS_SESSION: OnceLock<Mutex<Option<zbus::blocking::Connection>>> = OnceLock::new();++fn with_session_connection<T, F>(mut op: F) -> Option<T>+where+ F: FnMut(&zbus::blocking::Connection) -> zbus::Result<T>,+{+ let mutex = DBUS_SESSION.get_or_init(|| Mutex::new(None));+ let mut guard = mutex.lock().ok()?;+ if guard.is_none() {+ *guard = zbus::blocking::Connection::session().ok();+ }+ if let Some(conn) = guard.as_ref() {+ match op(conn) {+ Ok(val) => return Some(val),+ Err(_) => {+ *guard = zbus::blocking::Connection::session().ok();+ if let Some(retry_conn) = guard.as_ref() {+ return op(retry_conn).ok();+ }+ }+ }+ }+ None}#[allow(clippy::too_many_arguments)]@@ -507,224 +530,105 @@ fn send_notification(return None;}- let actions_arg = build_actions_gvariant(actions, reply);- let hints_arg = build_hints_gvariant(progress, silent, call);- let expire_timeout = if call { "int32 0" } else { "int32 -1" };+ let actions_list = build_actions_list(actions, reply);+ let hints_map = build_hints_map(progress, silent, call);+ let expire_timeout: i32 = if call { 0 } else { -1 };- if let Ok(output) = Command::new("gdbus")- .args([- "call",- "--session",- "--dest",- "org.freedesktop.Notifications",- "--object-path",+ with_session_connection(|conn| {+ let reply_msg = conn.call_method(+ Some("org.freedesktop.Notifications"),"/org/freedesktop/Notifications",- "--method",- "org.freedesktop.Notifications.Notify",- "NectarLink",- &replaces_id.to_string(),- icon_path,- summary,- body,- &actions_arg,- &hints_arg,- expire_timeout,- ])- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::null())- .output()- && output.status.success()- {- let stdout = String::from_utf8_lossy(&output.stdout);- if let Some(id) = parse_notify_id(&stdout) {- return Some(id);- }- }-- // Fallback to notify-send- let mut cmd = Command::new("notify-send");- cmd.arg("--app-name=NectarLink").arg("--print-id");- if replaces_id != 0 {- cmd.arg(format!("--replace-id={replaces_id}"));- }- if !icon_path.is_empty() {- cmd.arg(format!("--icon={icon_path}"));- }- if call {- cmd.arg("--urgency=critical");- } else if silent {- cmd.arg("--urgency=low");- }- if let Some(prog) = progress {- let pct = compute_progress_percent(prog);- cmd.arg(format!("--hint=int:value:{pct}"));- }- cmd.arg(summary);- if !body.is_empty() {- cmd.arg(body);- }- if let Ok(output) = cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).output()- && output.status.success()- {- let stdout = String::from_utf8_lossy(&output.stdout);- if let Some(id) = parse_notify_id(&stdout) {- return Some(id);- }- }-- None+ Some("org.freedesktop.Notifications"),+ "Notify",+ &("NectarLink", replaces_id, icon_path, summary, body, &actions_list, &hints_map, expire_timeout),+ )?;+ let msg_body = reply_msg.body();+ msg_body.deserialize::<u32>().or_else(|_| msg_body.deserialize::<(u32,)>().map(|(id,)| id))+ })}fn close_notification(id: u32) {if cfg!(test) || id == 0 {return;}- let _ = Command::new("gdbus")- .args([- "call",- "--session",- "--dest",- "org.freedesktop.Notifications",- "--object-path",+ let _ = with_session_connection(|conn| {+ conn.call_method(+ Some("org.freedesktop.Notifications"),"/org/freedesktop/Notifications",- "--method",- "org.freedesktop.Notifications.CloseNotification",- &id.to_string(),- ])- .stdin(Stdio::null())- .stdout(Stdio::null())- .stderr(Stdio::null())- .status();+ Some("org.freedesktop.Notifications"),+ "CloseNotification",+ &(id,),+ )+ .map(|_| ())+ });}fn monitor_loop() {- let Ok(mut child) = Command::new("gdbus")- .args([- "monitor",- "--session",- "--dest",- "org.freedesktop.Notifications",- "--object-path",- "/org/freedesktop/Notifications",- ])- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::null())- .spawn()- else {- return;- };+ loop {+ let Ok(conn) = zbus::blocking::Connection::session() else {+ std::thread::sleep(Duration::from_secs(5));+ continue;+ };+ let Ok(rule) = zbus::MatchRule::builder()+ .msg_type(zbus::message::Type::Signal)+ .interface("org.freedesktop.Notifications")+ .and_then(|b| b.path("/org/freedesktop/Notifications"))+ .map(|b| b.build())+ else {+ return;+ };+ let Ok(iter) = zbus::blocking::MessageIterator::for_match_rule(rule, &conn, None) else {+ std::thread::sleep(Duration::from_secs(5));+ continue;+ };- let Some(stdout) = child.stdout.take() else {- return;- };- let reader = BufReader::new(stdout);- for line in reader.lines().map_while(Result::ok) {- if let Some(signal) = parse_monitor_line(&line) {- let event_and_cb = TOASTER.get().and_then(|mutex| {- let mut guard = mutex.lock().ok()?;- let ev = guard.handle_signal(signal)?;- Some(ev)- });- if let Some(event) = event_and_cb- && let Some(mutex) = TOASTER.get()- && let Ok(guard) = mutex.lock()- && let Some(cb) = &guard.on_event- {- cb(event);+ for msg in iter {+ let Ok(msg) = msg else {+ break;+ };+ if let Some(signal) = parse_dbus_signal(&msg) {+ let event = TOASTER.get().and_then(|mutex| {+ let mut guard = mutex.lock().ok()?;+ guard.handle_signal(signal)+ });+ if let Some(event) = event+ && let Some(mutex) = TOASTER.get()+ && let Ok(guard) = mutex.lock()+ && let Some(cb) = &guard.on_event+ {+ cb(event);+ }}}+ std::thread::sleep(Duration::from_secs(2));}}-/// Parses the notification ID returned by `gdbus call ... Notify` (e.g. `(uint32 42,)`)-/// or `notify-send --print-id` (e.g. `42`).-pub fn parse_notify_id(output: &str) -> Option<u32> {- let trimmed = output.trim();- if trimmed.is_empty() {+/// Deserializes a D-Bus signal from `org.freedesktop.Notifications` into a [`MonitorSignal`].+pub fn parse_dbus_signal(msg: &zbus::message::Message) -> Option<MonitorSignal> {+ let header = msg.header();+ if header.message_type() != zbus::message::Type::Signal {return None;}- if let Ok(id) = trimmed.parse::<u32>() {- return Some(id);- }- if let Some(idx) = trimmed.find("uint32 ") {- let rest = &trimmed[idx + "uint32 ".len()..];- let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();- if let Ok(id) = digits.parse::<u32>() {- return Some(id);- }- }- None-}--/// Parses a single line from `gdbus monitor --session --dest org.freedesktop.Notifications`.-///-/// Expected signal formats:-/// - `/org/freedesktop/Notifications: org.freedesktop.Notifications.ActionInvoked (uint32 12, 'reply')`-/// - `/org/freedesktop/Notifications: org.freedesktop.Notifications.NotificationReplied (uint32 12, 'Hello!')`-/// - `/org/freedesktop/Notifications: org.freedesktop.Notifications.NotificationClosed (uint32 12, uint32 2)`-pub fn parse_monitor_line(line: &str) -> Option<MonitorSignal> {- let trimmed = line.trim();- if let Some(idx) = trimmed.find("ActionInvoked") {- let args = &trimmed[idx + "ActionInvoked".len()..];- let (id, rest) = parse_first_uint32(args)?;- let action_key = parse_quoted_arg(rest)?;- return Some(MonitorSignal::ActionInvoked { id, action_key });- }- if let Some(idx) = trimmed.find("NotificationReplied") {- let args = &trimmed[idx + "NotificationReplied".len()..];- let (id, rest) = parse_first_uint32(args)?;- let text = parse_quoted_arg(rest)?;- return Some(MonitorSignal::NotificationReplied { id, text });- }- if let Some(idx) = trimmed.find("NotificationClosed") {- let args = &trimmed[idx + "NotificationClosed".len()..];- let (id, rest) = parse_first_uint32(args)?;- let (reason, _) = parse_first_uint32(rest).unwrap_or((0, ""));- return Some(MonitorSignal::NotificationClosed { id, reason });- }- None-}--fn parse_first_uint32(s: &str) -> Option<(u32, &str)> {- let start = s.find(|c: char| c.is_ascii_digit())?;- let after_prefix = &s[start..];- // Skip the `32` in `uint32 ` if `start` landed on `32`- let after_uint = if start >= 4 && &s[start - 4..start + 2] == "uint32" {- let rest_after_type = &s[start + 2..];- let num_start = rest_after_type.find(|c: char| c.is_ascii_digit())?;- &rest_after_type[num_start..]- } else {- after_prefix- };- let end = after_uint.find(|c: char| !c.is_ascii_digit()).unwrap_or(after_uint.len());- let val = after_uint[..end].parse::<u32>().ok()?;- Some((val, &after_uint[end..]))-}--fn parse_quoted_arg(s: &str) -> Option<String> {- let comma = s.find(',')?;- let after_comma = s[comma + 1..].trim();- let quote_char = after_comma.chars().next()?;- if quote_char != '\'' && quote_char != '"' {+ if header.interface().map(|i| i.as_str()) != Some("org.freedesktop.Notifications") {return None;}- let content = &after_comma[quote_char.len_utf8()..];- let mut out = String::new();- let mut chars = content.chars();- while let Some(ch) = chars.next() {- if ch == '\\' {- if let Some(next) = chars.next() {- out.push(next);- }- } else if ch == quote_char {- return Some(out);- } else {- out.push(ch);+ let member = header.member()?.as_str();+ match member {+ "ActionInvoked" => {+ let (id, action_key) = msg.body().deserialize::<(u32, String)>().ok()?;+ Some(MonitorSignal::ActionInvoked { id, action_key })+ }+ "NotificationReplied" => {+ let (id, text) = msg.body().deserialize::<(u32, String)>().ok()?;+ Some(MonitorSignal::NotificationReplied { id, text })}+ "NotificationClosed" => {+ let (id, reason) = msg.body().deserialize::<(u32, u32)>().ok()?;+ Some(MonitorSignal::NotificationClosed { id, reason })+ }+ _ => None,}- None}#[cfg(test)]@@ -732,30 +636,63 @@ mod tests {use super::*;#[test]- fn parses_notify_ids_from_gdbus_and_notify_send() {- assert_eq!(parse_notify_id("(uint32 42,)\n"), Some(42));- assert_eq!(parse_notify_id("(uint32 108,)"), Some(108));- assert_eq!(parse_notify_id("73\n"), Some(73));- assert_eq!(parse_notify_id(""), None);+ fn builds_actions_and_hints_without_gvariant_text_mangling() {+ let actions = vec![("mark_read".to_string(), "Mark 'read' [1]".to_string())];+ let reply = ("direct_reply".to_string(), "Reply \"now\"".to_string());+ let list = build_actions_list(&actions, Some(&reply));+ assert_eq!(+ list,+ vec!["default", "Open", "mark_read", "Mark 'read' [1]", "inline-reply", "Reply \"now\""]+ );++ let prog = Progress { status: "Transferring".to_string(), value: Some(0.42), label: String::new() };+ let hints = build_hints_map(Some(&prog), true, false);+ assert_eq!(hints.get("urgency"), Some(&zbus::zvariant::Value::U8(0)));+ assert_eq!(hints.get("suppress-sound"), Some(&zbus::zvariant::Value::Bool(true)));+ assert_eq!(hints.get("value"), Some(&zbus::zvariant::Value::I32(42)));}#[test]- fn parses_gdbus_monitor_signals() {- let action_line = "/org/freedesktop/Notifications: org.freedesktop.Notifications.ActionInvoked (uint32 15, 'mark_read')";+ fn parses_zbus_notification_signals() {+ let action_msg = zbus::message::Message::signal(+ "/org/freedesktop/Notifications",+ "org.freedesktop.Notifications",+ "ActionInvoked",+ )+ .unwrap()+ .build(&(15u32, "mark_read"))+ .unwrap();assert_eq!(- parse_monitor_line(action_line),+ parse_dbus_signal(&action_msg),Some(MonitorSignal::ActionInvoked { id: 15, action_key: "mark_read".to_string() }));- let reply_line = "/org/freedesktop/Notifications: org.freedesktop.Notifications.NotificationReplied (uint32 15, 'Sounds good\\'s!')";+ let reply_msg = zbus::message::Message::signal(+ "/org/freedesktop/Notifications",+ "org.freedesktop.Notifications",+ "NotificationReplied",+ )+ .unwrap()+ .build(&(15u32, "Sounds good's!\nLine 2 [true]"))+ .unwrap();assert_eq!(- parse_monitor_line(reply_line),- Some(MonitorSignal::NotificationReplied { id: 15, text: "Sounds good's!".to_string() })+ parse_dbus_signal(&reply_msg),+ Some(MonitorSignal::NotificationReplied {+ id: 15,+ text: "Sounds good's!\nLine 2 [true]".to_string(),+ }));- let closed_line = "/org/freedesktop/Notifications: org.freedesktop.Notifications.NotificationClosed (uint32 15, uint32 2)";+ let closed_msg = zbus::message::Message::signal(+ "/org/freedesktop/Notifications",+ "org.freedesktop.Notifications",+ "NotificationClosed",+ )+ .unwrap()+ .build(&(15u32, 2u32))+ .unwrap();assert_eq!(- parse_monitor_line(closed_line),+ parse_dbus_signal(&closed_msg),Some(MonitorSignal::NotificationClosed { id: 15, reason: 2 }));}diff --git a/desktop/app/src/linux/tray.rs b/desktop/app/src/linux/tray.rsindex 0e536e3..d84203f 100644--- a/desktop/app/src/linux/tray.rs+++ b/desktop/app/src/linux/tray.rs@@ -6,9 +6,9 @@use std::{collections::HashMap,env,- io::{BufRead, BufReader, Result, Write},+ io::Result,path::PathBuf,- process::{Child, ChildStdin, Command, Stdio},+ process::{Command, Stdio},sync::{Arc, Mutex, OnceLock,atomic::{AtomicBool, AtomicU64, Ordering},@@ -638,6 +638,14 @@ fn spawn_x11_hotkey_thread(stop: Arc<AtomicBool>, handler: Arc<SharedHandler>) -.ok()}+/// Returns true when an `org.freedesktop.portal.Settings.SettingChanged`+/// signal (`namespace`, `key`) affects desktop appearance (`"color-scheme"`,+/// `"contrast"`, or `"accent-color"`).+pub fn is_portal_appearance_setting(namespace: &str, key: &str) -> bool {+ namespace.trim() == "org.freedesktop.appearance"+ && matches!(key.trim(), "color-scheme" | "contrast" | "accent-color")+}+/// Returns true when a line from `gdbus monitor` or `dbus-monitor` indicates/// `org.freedesktop.login1.Manager.PrepareForSleep(false)` (system waking up).pub fn is_prepare_for_sleep_resume_line(line: &str) -> bool {@@ -700,145 +708,70 @@ fn tray_icon_cache_path() -> PathBuf {}}-fn spawn_dbus_monitor_reader(- mut child: Child,- stop: Arc<AtomicBool>,- handler: Arc<SharedHandler>,- is_login1: bool,-) -> Option<JoinHandle<()>> {- let stdout = child.stdout.take()?;- std::thread::Builder::new()- .name(if is_login1 { "tray-login1-monitor".into() } else { "tray-portal-monitor".into() })- .spawn(move || {- let reader = BufReader::new(stdout);- let mut awaiting_sleep_bool = false;- for line in reader.lines() {- if stop.load(Ordering::Acquire) {- break;- }- let Ok(line) = line else { break };- if is_login1 {- if is_prepare_for_sleep_resume_line(&line) {- awaiting_sleep_bool = false;- handler.emit(TrayEvent::Resumed);- } else if line.contains("PrepareForSleep") {- awaiting_sleep_bool = !line.contains("true");- } else if awaiting_sleep_bool {- let trimmed = line.trim();- if trimmed.contains("boolean false") {- awaiting_sleep_bool = false;- handler.emit(TrayEvent::Resumed);- } else if trimmed.contains("boolean true") {- awaiting_sleep_bool = false;- }- }- } else if is_portal_appearance_changed_line(&line) {- handler.emit(TrayEvent::AppearanceChanged);- }+fn spawn_login1_sleep_listener(stop: Arc<AtomicBool>, handler: Arc<SharedHandler>) {+ let _ = std::thread::Builder::new().name("tray-login1-monitor".into()).spawn(move || {+ let Ok(conn) = zbus::blocking::Connection::system() else { return };+ let Ok(rule) = zbus::MatchRule::builder()+ .msg_type(zbus::message::Type::Signal)+ .interface("org.freedesktop.login1.Manager")+ .and_then(|b| b.member("PrepareForSleep"))+ .map(|b| b.build())+ else {+ return;+ };+ let Ok(dbus) = zbus::blocking::fdo::DBusProxy::new(&conn) else { return };+ if dbus.add_match_rule(rule).is_err() {+ return;+ }+ for msg in zbus::blocking::MessageIterator::from(&conn) {+ if stop.load(Ordering::Acquire) {+ break;}- })- .ok()+ let Ok(msg) = msg else { break };+ let hdr = msg.header();+ if hdr.interface().map(|i| i.as_str()) == Some("org.freedesktop.login1.Manager")+ && hdr.member().map(|m| m.as_str()) == Some("PrepareForSleep")+ && let Ok(going_to_sleep) = msg.body().deserialize::<bool>()+ && !going_to_sleep+ {+ handler.emit(TrayEvent::Resumed);+ }+ }+ });}-const TRAY_HELPER_SCRIPT: &str = r#"-import os, sys, threading-import gi-gi.require_version('Gtk', '3.0')-from gi.repository import Gtk, GLib--icon_path = sys.argv[1]-tooltip = sys.argv[2]-labels = sys.argv[3:11]-icon_dir = os.path.dirname(icon_path)-icon_name = os.path.splitext(os.path.basename(icon_path))[0]--def emit(action):- try:- sys.stdout.write(action + "\n")- sys.stdout.flush()- except Exception:- pass--menu = Gtk.Menu()-def add_item(label, action):- item = Gtk.MenuItem(label=label)- item.connect('activate', lambda _: emit(action))- menu.append(item)- return item--open_item = add_item(labels[0], 'OPEN')-add_item(labels[1], 'COMMAND_PALETTE')-add_item(labels[2], 'SHELF')-menu.append(Gtk.SeparatorMenuItem())-add_item(labels[3], 'TAKE_PHOTO')-add_item(labels[4], 'SCAN_DOCUMENT')-find_phone_item = add_item(labels[5], 'FIND_PHONE')-find_phone_item.set_sensitive(False)-add_item(labels[6], 'OPEN_LINK')-menu.append(Gtk.SeparatorMenuItem())-add_item(labels[7], 'QUIT')-menu.show_all()--ind = None-status_icon = None-try:- try:- gi.require_version('AyatanaAppIndicator3', '0.1')- from gi.repository import AyatanaAppIndicator3 as AppIndicator- except Exception:- gi.require_version('AppIndicator3', '0.1')- from gi.repository import AppIndicator3 as AppIndicator- ind = AppIndicator.Indicator.new_with_path(- 'nectarlink',- icon_name,- AppIndicator.IndicatorCategory.APPLICATION_STATUS,- icon_dir,- )- ind.set_status(AppIndicator.IndicatorStatus.ACTIVE)- ind.set_title(tooltip)- ind.set_icon_full(icon_path, tooltip)- ind.set_menu(menu)- try:- ind.set_secondary_activate_target(open_item)- except Exception:- pass-except Exception:- status_icon = Gtk.StatusIcon.new_from_file(icon_path)- status_icon.set_tooltip_text(tooltip)- status_icon.set_visible(True)- status_icon.connect('activate', lambda _: emit('OPEN'))- status_icon.connect(- 'popup-menu',- lambda icon, button, time: menu.popup(None, None, Gtk.StatusIcon.position_menu, icon, button, time),- )--def apply_cmd(line):- parts = line.rstrip('\r\n').split('\t', 1)- if len(parts) != 2:- return False- cmd, val = parts- if cmd == 'TOOLTIP':- if ind is not None:- ind.set_title(val)- ind.set_icon_full(icon_path, val)- if status_icon is not None:- status_icon.set_tooltip_text(val)- elif cmd == 'FIND_PHONE':- find_phone_item.set_sensitive(val == '1')- return False--def stdin_reader():- try:- for line in sys.stdin:- GLib.idle_add(apply_cmd, line)- except Exception:- pass- GLib.idle_add(Gtk.main_quit)--t = threading.Thread(target=stdin_reader, daemon=True)-t.start()-Gtk.main()-"#;+fn spawn_portal_appearance_listener(stop: Arc<AtomicBool>, handler: Arc<SharedHandler>) {+ let _ = std::thread::Builder::new().name("tray-portal-monitor".into()).spawn(move || {+ let Ok(conn) = zbus::blocking::Connection::session() else { return };+ let Ok(rule) = zbus::MatchRule::builder()+ .msg_type(zbus::message::Type::Signal)+ .interface("org.freedesktop.portal.Settings")+ .and_then(|b| b.member("SettingChanged"))+ .map(|b| b.build())+ else {+ return;+ };+ let Ok(dbus) = zbus::blocking::fdo::DBusProxy::new(&conn) else { return };+ if dbus.add_match_rule(rule).is_err() {+ return;+ }+ for msg in zbus::blocking::MessageIterator::from(&conn) {+ if stop.load(Ordering::Acquire) {+ break;+ }+ let Ok(msg) = msg else { break };+ let hdr = msg.header();+ if hdr.interface().map(|i| i.as_str()) == Some("org.freedesktop.portal.Settings")+ && hdr.member().map(|m| m.as_str()) == Some("SettingChanged")+ && let Ok((namespace, key, _val)) =+ msg.body().deserialize::<(String, String, zbus::zvariant::OwnedValue)>()+ && is_portal_appearance_setting(&namespace, &key)+ {+ handler.emit(TrayEvent::AppearanceChanged);+ }+ }+ });+}pub(crate) fn parse_tray_helper_action(line: &str) -> Option<TrayEvent> {match line.trim() {@@ -856,13 +789,12 @@ pub(crate) fn parse_tray_helper_action(line: &str) -> Option<TrayEvent> {pub struct Tray {tooltip: Mutex<String>,+ #[allow(dead_code)]labels: Mutex<MenuLabels>,find_phone_enabled: Mutex<bool>,icon_path: PathBuf,stop: Arc<AtomicBool>,handler: Arc<SharedHandler>,- helper_stdin: Mutex<Option<ChildStdin>>,- children: Mutex<Vec<Child>>,threads: Mutex<Vec<JoinHandle<()>>>,}@@ -885,175 +817,59 @@ impl Tray {let stop = Arc::new(AtomicBool::new(false));let shared_handler = SharedHandler::new(handler);- let mut helper_stdin = None;- let mut children = Vec::new();let mut threads = Vec::new();if !cfg!(test) && has_desktop_session() {record_foreground_window();- // 0. StatusNotifierItem / Gtk.StatusIcon system tray indicator helper.- let tray_child = Command::new("python3")- .args([- "-u",- "-c",- TRAY_HELPER_SCRIPT,- &icon_path.to_string_lossy(),- tooltip,- &labels.open,- &labels.command_palette,- &labels.shelf,- &labels.take_photo,- &labels.scan_document,- &labels.find_phone,- &labels.open_link,- &labels.quit,- ])- .stdin(Stdio::piped())- .stdout(Stdio::piped())- .stderr(Stdio::null())- .spawn();-- if let Ok(mut child) = tray_child {- helper_stdin = child.stdin.take();- let stdout = child.stdout.take();- children.push(child);- if let Some(stdout) = stdout {- let reader = BufReader::new(stdout);- let stop_clone = Arc::clone(&stop);- let handler_clone = Arc::clone(&shared_handler);- if let Ok(handle) =- std::thread::Builder::new().name("tray-sni-helper".into()).spawn(move || {- for line in reader.lines() {- if stop_clone.load(Ordering::Acquire) {- break;- }- let Ok(line) = line else { break };- if let Some(ev) = parse_tray_helper_action(&line) {- if matches!(- ev,- TrayEvent::CommandPalette- | TrayEvent::TakePhoto- | TrayEvent::ScanDocument- ) {- record_foreground_window();- }- handler_clone.emit(ev);- }- }- })- {- threads.push(handle);+ // 0. Qt QSystemTrayIcon + QMenu on the main GUI thread.+ crate::bridge::native::ffi::linux_tray_setup(+ &icon_path.to_string_lossy(),+ tooltip,+ &labels.open,+ &labels.command_palette,+ &labels.shelf,+ &labels.take_photo,+ &labels.scan_document,+ &labels.find_phone,+ &labels.open_link,+ &labels.quit,+ );+ let stop_clone = Arc::clone(&stop);+ let handler_clone = Arc::clone(&shared_handler);+ if let Ok(handle) = std::thread::Builder::new().name("tray-qt-actions".into()).spawn(move || {+ while !stop_clone.load(Ordering::Acquire) {+ let action = crate::bridge::native::ffi::linux_tray_wait_action(200);+ if stop_clone.load(Ordering::Acquire) {+ break;}- }- }-- // 1. System bus org.freedesktop.login1.Manager PrepareForSleep monitor.- let login1_child = Command::new("gdbus")- .args([- "monitor",- "--system",- "--dest",- "org.freedesktop.login1",- ])- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::null())- .spawn()- .or_else(|_| {- Command::new("dbus-monitor")- .args([- "--system",- "type='signal',interface='org.freedesktop.login1.Manager',member='PrepareForSleep'",- ])- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::null())- .spawn()- });- if let Ok(mut child) = login1_child {- let stdout = child.stdout.take();- children.push(child);- if let Some(stdout) = stdout {- let fake_child_reader = BufReader::new(stdout);- let stop_clone = Arc::clone(&stop);- let handler_clone = Arc::clone(&shared_handler);- if let Ok(handle) =- std::thread::Builder::new().name("tray-login1-monitor".into()).spawn(move || {- let mut awaiting_sleep_bool = false;- for line in fake_child_reader.lines() {- if stop_clone.load(Ordering::Acquire) {- break;- }- let Ok(line) = line else { break };- if is_prepare_for_sleep_resume_line(&line) {- awaiting_sleep_bool = false;- handler_clone.emit(TrayEvent::Resumed);- } else if line.contains("PrepareForSleep") {- awaiting_sleep_bool = !line.contains("true");- } else if awaiting_sleep_bool {- let trimmed = line.trim();- if trimmed.contains("boolean false") {- awaiting_sleep_bool = false;- handler_clone.emit(TrayEvent::Resumed);- } else if trimmed.contains("boolean true") {- awaiting_sleep_bool = false;- }- }- }- })+ if !action.is_empty()+ && let Some(ev) = parse_tray_helper_action(&action){- threads.push(handle);+ if matches!(+ ev,+ TrayEvent::CommandPalette | TrayEvent::TakePhoto | TrayEvent::ScanDocument+ ) {+ record_foreground_window();+ }+ handler_clone.emit(ev);}}+ }) {+ threads.push(handle);}- // 2. Session bus org.freedesktop.portal.Settings SettingChanged monitor.- let portal_child = Command::new("gdbus")- .args([- "monitor",- "--session",- "--dest",- "org.freedesktop.portal.Desktop",- "--object-path",- "/org/freedesktop/portal/desktop",- ])- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::null())- .spawn();- if let Ok(mut child) = portal_child {- let stdout = child.stdout.take();- children.push(child);- if let Some(stdout) = stdout {- let reader = BufReader::new(stdout);- let stop_clone = Arc::clone(&stop);- let handler_clone = Arc::clone(&shared_handler);- if let Ok(handle) =- std::thread::Builder::new().name("tray-portal-monitor".into()).spawn(move || {- for line in reader.lines() {- if stop_clone.load(Ordering::Acquire) {- break;- }- let Ok(line) = line else { break };- if is_portal_appearance_changed_line(&line) {- handler_clone.emit(TrayEvent::AppearanceChanged);- }- }- })- {- threads.push(handle);- }- }- }+ // 1. System bus org.freedesktop.login1.Manager PrepareForSleep listener via zbus.+ spawn_login1_sleep_listener(Arc::clone(&stop), Arc::clone(&shared_handler));++ // 2. Session bus org.freedesktop.portal.Settings SettingChanged listener via zbus.+ spawn_portal_appearance_listener(Arc::clone(&stop), Arc::clone(&shared_handler));}if let Some(handle) = spawn_x11_hotkey_thread(Arc::clone(&stop), Arc::clone(&shared_handler)) {threads.push(handle);}- let _ = spawn_dbus_monitor_reader;-Ok(Tray {tooltip: Mutex::new(tooltip.to_string()),labels: Mutex::new(labels),@@ -1061,8 +877,6 @@ impl Tray {icon_path,stop,handler: shared_handler,- helper_stdin: Mutex::new(helper_stdin),- children: Mutex::new(children),threads: Mutex::new(threads),})}@@ -1071,12 +885,8 @@ impl Tray {if let Ok(mut guard) = self.tooltip.lock() {*guard = text.to_string();}- if let Ok(mut guard) = self.helper_stdin.lock()- && let Some(stdin) = guard.as_mut()- {- let sanitized = text.replace(['\r', '\n', '\t'], " ");- let _ = writeln!(stdin, "TOOLTIP\t{sanitized}");- let _ = stdin.flush();+ if !cfg!(test) {+ crate::bridge::native::ffi::linux_tray_set_tooltip(text);}}@@ -1085,12 +895,8 @@ impl Tray {if let Ok(mut guard) = self.find_phone_enabled.lock() {*guard = enabled;}- if let Ok(mut guard) = self.helper_stdin.lock()- && let Some(stdin) = guard.as_mut()- {- let flag = if enabled { "1" } else { "0" };- let _ = writeln!(stdin, "FIND_PHONE\t{flag}");- let _ = stdin.flush();+ if !cfg!(test) {+ crate::bridge::native::ffi::linux_tray_set_find_phone_enabled(enabled);}}}@@ -1099,15 +905,8 @@ impl Drop for Tray {fn drop(&mut self) {self.stop.store(true, Ordering::Release);self.handler.clear();- if let Ok(mut stdin_guard) = self.helper_stdin.lock() {- let _ = stdin_guard.take();- }- if let Ok(mut children) = self.children.lock() {- for child in children.iter_mut() {- let _ = child.kill();- let _ = child.wait();- }- children.clear();+ if !cfg!(test) {+ crate::bridge::native::ffi::linux_tray_teardown();}if let Ok(mut threads) = self.threads.lock() {for handle in threads.drain(..) {diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex 24e20ea..5f846d6 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -430,6 +430,9 @@ fn run_setup_window(mode: setup::Mode) -> ExitCode {}bridge::setup::set_mode(mode);bridge::native::ffi::prepare_qt_without_log();+ #[cfg(target_os = "linux")]+ let mut app = bridge::native::ffi::create_qt_app();+ #[cfg(not(target_os = "linux"))]let mut app = QGuiApplication::new();if let Some(mut app) = app.as_mut() {app.as_mut().set_application_name(&QString::from("NectarLink Setup"));@@ -627,6 +630,9 @@ fn main() -> ExitCode {} else {bridge::native::ffi::prepare_qt();}+ #[cfg(target_os = "linux")]+ let mut app = bridge::native::ffi::create_qt_app();+ #[cfg(not(target_os = "linux"))]let mut app = QGuiApplication::new();if let Some(mut app) = app.as_mut() {app.as_mut().set_application_name(&QString::from("Nectarlink"));diff --git a/desktop/app/src/pc_notifications.rs b/desktop/app/src/pc_notifications.rsindex b76731f..c548e67 100644--- a/desktop/app/src/pc_notifications.rs+++ b/desktop/app/src/pc_notifications.rs@@ -4,11 +4,7 @@//! Settings (default `false`, privacy-first).#[cfg(target_os = "linux")]-use std::{- io::{BufRead, BufReader},- process::{Command, Stdio},- sync::OnceLock,-};+use std::sync::OnceLock;use std::{sync::atomic::{AtomicU64, Ordering},time::{SystemTime, UNIX_EPOCH},@@ -165,7 +161,42 @@ pub fn forward_to_phones(app_name: &str, title: &str, text: &str) -> bool {true}-/// Starts a background listener for desktop notifications on Linux via `dbus-monitor`.+/// Deserializes a Freedesktop `org.freedesktop.Notifications.Notify` D-Bus method call+/// message into `(app_name, summary, body)`, preserving multi-line notification bodies.+#[cfg(any(target_os = "linux", test))]+pub fn extract_notify_call(msg: &zbus::message::Message) -> Option<(String, String, String)> {+ let header = msg.header();+ if header.message_type() != zbus::message::Type::MethodCall {+ return None;+ }+ if header.interface().map(|i| i.as_str()) != Some("org.freedesktop.Notifications") {+ return None;+ }+ if header.member().map(|m| m.as_str()) != Some("Notify") {+ return None;+ }+ type NotifyBody = (+ String,+ u32,+ String,+ String,+ String,+ Vec<String>,+ std::collections::HashMap<String, zbus::zvariant::OwnedValue>,+ i32,+ );+ let (app_name, _replaces_id, _app_icon, summary, body, _actions, _hints, _timeout) =+ msg.body().deserialize::<NotifyBody>().ok()?;+ let app_name = app_name.trim().to_string();+ let summary = summary.trim().to_string();+ let body = body.trim().to_string();+ if summary.is_empty() && body.is_empty() {+ return None;+ }+ Some((app_name, summary, body))+}++/// Starts a background listener for desktop notifications on Linux via `zbus`.#[cfg(target_os = "linux")]pub fn start_listener() {LISTENER_STARTED.get_or_init(|| {@@ -177,61 +208,49 @@ pub fn start_listener() {#[cfg(target_os = "linux")]fn dbus_monitor_loop() {- let Ok(mut child) = Command::new("dbus-monitor")- .args(["--session", "type='method_call',interface='org.freedesktop.Notifications',member='Notify'"])- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::null())- .spawn()- else {- return;- };+ use std::time::Duration;- let Some(stdout) = child.stdout.take() else {- return;- };+ loop {+ if !settings::forward_pc_notifications_to_phone() {+ std::thread::sleep(Duration::from_secs(1));+ continue;+ }- let reader = BufReader::new(stdout);- let mut current_block = String::new();- let mut in_notify = false;- let mut string_count = 0usize;+ let Ok(conn) = zbus::blocking::Connection::session() else {+ std::thread::sleep(Duration::from_secs(5));+ continue;+ };- for line in reader.lines().map_while(Result::ok) {- let trimmed = line.trim();- if trimmed.contains("member=Notify") {- if in_notify && let Some((app, title, body)) = parse_dbus_notify_line(¤t_block) {- let _ = forward_pc_toast(&app, &title, &body);- }- current_block.clear();- in_notify = true;- string_count = 0;- current_block.push_str(trimmed);- current_block.push(' ');+ let rules = vec!["type='method_call',interface='org.freedesktop.Notifications',member='Notify'"];+ if conn+ .call_method(+ Some("org.freedesktop.DBus"),+ "/org/freedesktop/DBus",+ Some("org.freedesktop.DBus.Monitoring"),+ "BecomeMonitor",+ &(rules, 0u32),+ )+ .is_err()+ {+ std::thread::sleep(Duration::from_secs(5));continue;}- if in_notify {- if trimmed.starts_with("string \"") {- current_block.push_str(trimmed);- current_block.push(' ');- string_count += 1;- if string_count >= 4 {- if let Some((app, title, body)) = parse_dbus_notify_line(¤t_block) {+ for msg in zbus::blocking::MessageIterator::from(conn) {+ if !settings::forward_pc_notifications_to_phone() {+ break;+ }+ match msg {+ Ok(msg) => {+ if let Some((app, title, body)) = extract_notify_call(&msg) {let _ = forward_pc_toast(&app, &title, &body);}- current_block.clear();- in_notify = false;- string_count = 0;- }- } else if trimmed.starts_with("method call") || trimmed.starts_with("signal ") {- if let Some((app, title, body)) = parse_dbus_notify_line(¤t_block) {- let _ = forward_pc_toast(&app, &title, &body);}- current_block.clear();- in_notify = false;- string_count = 0;+ Err(_) => break,}}++ std::thread::sleep(Duration::from_secs(2));}}@@ -285,4 +304,38 @@ mod tests {assert!(!forward_pc_toast("NectarLink", "Connected", "Pixel 9"));assert!(!forward_pc_toast("Firefox", " ", ""));}++ #[test]+ fn extract_notify_call_preserves_multiline_body() {+ let hints: std::collections::HashMap<&str, zbus::zvariant::Value<'_>> =+ std::collections::HashMap::new();+ let actions: Vec<&str> = vec!["default", "Open"];+ let msg = zbus::message::Message::method_call("/org/freedesktop/Notifications", "Notify")+ .unwrap()+ .interface("org.freedesktop.Notifications")+ .unwrap()+ .destination("org.freedesktop.Notifications")+ .unwrap()+ .build(&(+ "Signal Desktop",+ 0u32,+ "signal-desktop",+ "Alice",+ "Hey there!\nAre we still on for 7pm?\nLet me know.",+ actions,+ hints,+ -1i32,+ ))+ .unwrap();++ let extracted = extract_notify_call(&msg);+ assert_eq!(+ extracted,+ Some((+ "Signal Desktop".to_string(),+ "Alice".to_string(),+ "Hey there!\nAre we still on for 7pm?\nLet me know.".to_string(),+ ))+ );+ }}