Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
fix(desktop): fix screen restoration, clipboard autorelease pools, and macOS tray fallbacks
saivinay1805865dfe99ce97
diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rsindex 58e083f..1e9307f 100644--- a/core/nectarlink-core/src/features.rs+++ b/core/nectarlink-core/src/features.rs@@ -1475,7 +1475,6 @@ mod tests {"task.notify","camera.continuity","pc.power",- "pc.wake","photos.show","calls.show","contacts.show",diff --git a/desktop/app/cpp/app_helpers.cpp b/desktop/app/cpp/app_helpers.cppindex 7fa3e21..36ba75b 100644--- a/desktop/app/cpp/app_helpers.cpp+++ b/desktop/app/cpp/app_helpers.cpp@@ -340,3 +340,147 @@ rust::Vec<uint8_t> decode_image(rust::Slice<const uint8_t> bytes)result.push_back(bits[i]);return result;}++#ifdef __APPLE__+#include <objc/runtime.h>+#include <objc/message.h>++extern "C" void *objc_autoreleasePoolPush(void);+extern "C" void objc_autoreleasePoolPop(void *pool);++namespace {+struct AutoReleasePool {+ void *pool;+ AutoReleasePool() : pool(objc_autoreleasePoolPush()) {}+ ~AutoReleasePool() { objc_autoreleasePoolPop(pool); }+};+} // namespace++int64_t mac_clipboard_change_count()+{+ AutoReleasePool pool;+ id pboardClass = reinterpret_cast<id>(objc_getClass("NSPasteboard"));+ if (!pboardClass)+ return 0;+ id pboard = reinterpret_cast<id (*)(id, SEL)>(objc_msgSend)(pboardClass, sel_registerName("generalPasteboard"));+ if (!pboard)+ return 0;+ return reinterpret_cast<int64_t (*)(id, SEL)>(objc_msgSend)(pboard, sel_registerName("changeCount"));+}++rust::String mac_clipboard_read_text(bool &is_private)+{+ AutoReleasePool pool;+ is_private = false;+ id pboardClass = reinterpret_cast<id>(objc_getClass("NSPasteboard"));+ if (!pboardClass)+ return rust::String();+ id pboard = reinterpret_cast<id (*)(id, SEL)>(objc_msgSend)(pboardClass, sel_registerName("generalPasteboard"));+ if (!pboard)+ return rust::String();++ id types = reinterpret_cast<id (*)(id, SEL)>(objc_msgSend)(pboard, sel_registerName("types"));+ id strClass = reinterpret_cast<id>(objc_getClass("NSString"));+ if (types && strClass) {+ id concealed = reinterpret_cast<id (*)(id, SEL, const char *)>(objc_msgSend)(+ strClass, sel_registerName("stringWithUTF8String:"), "org.nspasteboard.ConcealedType");+ id transient = reinterpret_cast<id (*)(id, SEL, const char *)>(objc_msgSend)(+ strClass, sel_registerName("stringWithUTF8String:"), "org.nspasteboard.TransientType");+ id autoGen = reinterpret_cast<id (*)(id, SEL, const char *)>(objc_msgSend)(+ strClass, sel_registerName("stringWithUTF8String:"), "org.nspasteboard.AutoGeneratedType");+ if ((concealed && reinterpret_cast<bool (*)(id, SEL, id)>(objc_msgSend)(types, sel_registerName("containsObject:"), concealed))+ || (transient && reinterpret_cast<bool (*)(id, SEL, id)>(objc_msgSend)(types, sel_registerName("containsObject:"), transient))+ || (autoGen && reinterpret_cast<bool (*)(id, SEL, id)>(objc_msgSend)(types, sel_registerName("containsObject:"), autoGen))) {+ is_private = true;+ return rust::String();+ }+ }++ id plainTextType = reinterpret_cast<id (*)(id, SEL, const char *)>(objc_msgSend)(+ strClass, sel_registerName("stringWithUTF8String:"), "public.utf8-plain-text");+ id str = reinterpret_cast<id (*)(id, SEL, id)>(objc_msgSend)(pboard, sel_registerName("stringForType:"), plainTextType);+ if (str) {+ const char *utf8 = reinterpret_cast<const char * (*)(id, SEL)>(objc_msgSend)(str, sel_registerName("UTF8String"));+ if (utf8)+ return rust::String(utf8);+ }+ return rust::String();+}++bool mac_clipboard_write_text(rust::Str text, bool is_private)+{+ AutoReleasePool pool;+ id pboardClass = reinterpret_cast<id>(objc_getClass("NSPasteboard"));+ if (!pboardClass)+ return false;+ id pboard = reinterpret_cast<id (*)(id, SEL)>(objc_msgSend)(pboardClass, sel_registerName("generalPasteboard"));+ if (!pboard)+ return false;++ reinterpret_cast<void (*)(id, SEL)>(objc_msgSend)(pboard, sel_registerName("clearContents"));++ id strClass = reinterpret_cast<id>(objc_getClass("NSString"));+ if (!strClass)+ return false;++ const std::string text_str(text.data(), text.size());+ id nsStr = reinterpret_cast<id (*)(id, SEL, const char *)>(objc_msgSend)(+ strClass, sel_registerName("stringWithUTF8String:"), text_str.c_str());+ if (!nsStr)+ return false;++ id plainTextType = reinterpret_cast<id (*)(id, SEL, const char *)>(objc_msgSend)(+ strClass, sel_registerName("stringWithUTF8String:"), "public.utf8-plain-text");++ id arrClass = reinterpret_cast<id>(objc_getClass("NSArray"));+ if (!arrClass)+ return false;++ if (is_private) {+ id concealed = reinterpret_cast<id (*)(id, SEL, const char *)>(objc_msgSend)(+ strClass, sel_registerName("stringWithUTF8String:"), "org.nspasteboard.ConcealedType");+ id transient = reinterpret_cast<id (*)(id, SEL, const char *)>(objc_msgSend)(+ strClass, sel_registerName("stringWithUTF8String:"), "org.nspasteboard.TransientType");+ const id items[] = { plainTextType, concealed, transient };+ id types = reinterpret_cast<id (*)(id, SEL, const id *, unsigned long)>(objc_msgSend)(+ arrClass, sel_registerName("arrayWithObjects:count:"), items, 3);+ reinterpret_cast<void (*)(id, SEL, id, id)>(objc_msgSend)(+ pboard, sel_registerName("declareTypes:owner:"), types, nullptr);+ reinterpret_cast<bool (*)(id, SEL, id, id)>(objc_msgSend)(+ pboard, sel_registerName("setString:forType:"), nsStr, plainTextType);+ id dataClass = reinterpret_cast<id>(objc_getClass("NSData"));+ if (dataClass) {+ id emptyData = reinterpret_cast<id (*)(id, SEL)>(objc_msgSend)(dataClass, sel_registerName("data"));+ reinterpret_cast<bool (*)(id, SEL, id, id)>(objc_msgSend)(+ pboard, sel_registerName("setData:forType:"), emptyData, concealed);+ reinterpret_cast<bool (*)(id, SEL, id, id)>(objc_msgSend)(+ pboard, sel_registerName("setData:forType:"), emptyData, transient);+ }+ } else {+ const id items[] = { plainTextType };+ id types = reinterpret_cast<id (*)(id, SEL, const id *, unsigned long)>(objc_msgSend)(+ arrClass, sel_registerName("arrayWithObjects:count:"), items, 1);+ reinterpret_cast<void (*)(id, SEL, id, id)>(objc_msgSend)(+ pboard, sel_registerName("declareTypes:owner:"), types, nullptr);+ reinterpret_cast<bool (*)(id, SEL, id, id)>(objc_msgSend)(+ pboard, sel_registerName("setString:forType:"), nsStr, plainTextType);+ }+ return true;+}+#else+int64_t mac_clipboard_change_count()+{+ return 0;+}++rust::String mac_clipboard_read_text(bool &is_private)+{+ is_private = false;+ return rust::String();+}++bool mac_clipboard_write_text(rust::Str /*text*/, bool /*is_private*/)+{+ return false;+}+#endifdiff --git a/desktop/app/cpp/app_helpers.h b/desktop/app/cpp/app_helpers.hindex 9353951..478ea83 100644--- a/desktop/app/cpp/app_helpers.h+++ b/desktop/app/cpp/app_helpers.h@@ -54,3 +54,8 @@ rust::String translate(rust::Str context, rust::Str text);// Decodes image bytes (PNG, JPEG, WebP, BMP, etc.) into width, height and ARGB32 bytes.rust::Vec<uint8_t> decode_image(rust::Slice<const uint8_t> bytes);++// Native macOS clipboard support: changeCount, privacy detection, and direct reading/writing.+int64_t mac_clipboard_change_count();+rust::String mac_clipboard_read_text(bool &is_private);+bool mac_clipboard_write_text(rust::Str text, bool is_private);diff --git a/desktop/app/cpp/native_window.cpp b/desktop/app/cpp/native_window.cppindex 1731550..3c6ac40 100644--- a/desktop/app/cpp/native_window.cpp+++ b/desktop/app/cpp/native_window.cpp@@ -355,3 +355,15 @@ bool NativeWindow::nativeEvent(const QByteArray &eventType, void *message, qintp#endifreturn QQuickWindow::nativeEvent(eventType, message, result);}++void NativeWindow::setScreenByName(const QString &screenName)+{+ if (screenName.isEmpty())+ return;+ for (QScreen *s : QGuiApplication::screens()) {+ if (s->name() == screenName) {+ setScreen(s);+ break;+ }+ }+}diff --git a/desktop/app/cpp/native_window.h b/desktop/app/cpp/native_window.hindex ad06b6b..c75e3e2 100644--- a/desktop/app/cpp/native_window.h+++ b/desktop/app/cpp/native_window.h@@ -2,6 +2,7 @@#pragma once#include <QtCore/QPointer>+#include <QtGui/QScreen>#include <QtQml/qqmlregistration.h>#include <QtQuick/QQuickItem>#include <QtQuick/QQuickWindow>@@ -18,6 +19,7 @@ class NativeWindow : public QQuickWindowQ_OBJECTQML_ELEMENT+// Show Mica behind transparent areas.Q_PROPERTY(bool backdrop READ backdrop WRITE setBackdrop NOTIFY backdropChanged)// Use Windows 11 Desktop Acrylic (DWMSBT_TRANSIENTWINDOW) when backdrop is active (for Liquid Glass theme).@@ -54,6 +56,8 @@ public:Q_INVOKABLE void addCaptionHole(QQuickItem *item);Q_INVOKABLE void removeCaptionHole(QQuickItem *item);+ // Selects and sets the native QScreen matching screenName.+ Q_INVOKABLE void setScreenByName(const QString &screenName);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).diff --git a/desktop/app/qml/App.qml b/desktop/app/qml/App.qmlindex 006427a..59da743 100644--- a/desktop/app/qml/App.qml+++ b/desktop/app/qml/App.qml@@ -131,7 +131,7 @@ QtObject {function onMainClosed() {if (mainLoader.active && mainLoader.item)mainLoader.item.saveWindowState()- if (!Preferences.closeToTray) {+ if (Qt.platform.os === "osx" || !Preferences.closeToTray) {Qt.quit()return}diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex 8a98171..9528924 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -966,13 +966,18 @@ Item {? Math.round((parent.height - height) / 2): (startWinRow.implicitHeight + 1)width: startupPairRow.colWidth+ opacity: Qt.platform.os === "osx" ? 0.5 : 1.0iconPath: Icons.windowtitle: qsTr("Stay in system tray")description: qsTr("Keep running when the window is closed.")Toggle {label: qsTr("Stay in system tray")checked: Preferences.closeToTray- onToggled: (on) => Preferences.closeToTray = on+ enabled: Qt.platform.os !== "osx"+ onToggled: (on) => {+ if (Qt.platform.os !== "osx")+ Preferences.closeToTray = on+ }}}}diff --git a/desktop/app/src/bridge/native.rs b/desktop/app/src/bridge/native.rsindex fa1210c..04af534 100644--- a/desktop/app/src/bridge/native.rs+++ b/desktop/app/src/bridge/native.rs@@ -52,6 +52,16 @@ pub mod ffi {fn translate(context: &str, text: &str) -> String;/// Decodes image bytes into a byte vector: 4-byte width (LE), 4-byte height (LE), followed by ARGB32 bytes.+ #[allow(dead_code)]fn decode_image(bytes: &[u8]) -> Vec<u8>;++ #[allow(dead_code)]+ fn mac_clipboard_change_count() -> i64;++ #[allow(dead_code)]+ fn mac_clipboard_read_text(is_private: &mut bool) -> String;++ #[allow(dead_code)]+ fn mac_clipboard_write_text(text: &str, is_private: bool) -> bool;}}diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rsindex c0f4b50..44fdf77 100644--- a/desktop/app/src/bridge/prefs.rs+++ b/desktop/app/src/bridge/prefs.rs@@ -364,7 +364,8 @@ impl cxx_qt::Initialize for qobject::Preferences {self.as_mut().set_amoled(settings.amoled);self.as_mut().set_backdrop(settings.backdrop);self.as_mut().set_comb_motion(settings.comb_motion);- self.as_mut().set_close_to_tray(settings.close_to_tray);+ let close_to_tray = if cfg!(target_os = "macos") { false } else { settings.close_to_tray };+ self.as_mut().set_close_to_tray(close_to_tray);self.as_mut().set_auto_clipboard(settings.auto_clipboard);crate::clipboard::set_auto_send(settings.auto_clipboard);self.as_mut().set_clipboard_history(settings.clipboard_history);@@ -447,7 +448,18 @@ impl cxx_qt::Initialize for qobject::Preferences {self.as_mut().on_amoled_changed(|p| p.save()).release();self.as_mut().on_backdrop_changed(|p| p.save()).release();self.as_mut().on_comb_motion_changed(|p| p.save()).release();- self.as_mut().on_close_to_tray_changed(|p| p.save()).release();+ self.as_mut()+ .on_close_to_tray_changed(|p| {+ #[cfg(target_os = "macos")]+ let mut p = p;+ #[cfg(target_os = "macos")]+ if p.close_to_tray {+ p.as_mut().set_close_to_tray(false);+ return;+ }+ p.save();+ })+ .release();self.as_mut().on_auto_clipboard_changed(|p| {crate::clipboard::set_auto_send(p.auto_clipboard);@@ -976,7 +988,7 @@ impl qobject::Preferences {amoled: p.amoled,backdrop: p.backdrop,comb_motion: p.comb_motion,- close_to_tray: p.close_to_tray,+ close_to_tray: if cfg!(target_os = "macos") { false } else { p.close_to_tray },auto_clipboard: p.auto_clipboard,clipboard_history: p.clipboard_history,suggest_clipboard_actions: p.suggest_clipboard_actions,diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rsindex 54ad9c3..7984c83 100644--- a/desktop/app/src/core_host.rs+++ b/desktop/app/src/core_host.rs@@ -105,7 +105,6 @@ pub fn compute_capabilities() -> Vec<String> {let mut caps = vec!["pc.power".into(),- nectarlink_core::PC_WAKE.into(),nectarlink_core::PHOTOS_SHOW.into(),nectarlink_core::CAMERA_CONTINUITY.into(),nectarlink_core::CALLS_SHOW.into(),@@ -115,6 +114,7 @@ pub fn compute_capabilities(];#[cfg(windows)]{+ caps.push(nectarlink_core::PC_WAKE.into());caps.push("media.control".into());caps.push(nectarlink_core::STORAGE_MOUNT.into());caps.push(nectarlink_core::STORAGE_READ.into());@@ -404,12 +404,11 @@ pub fn shutdown() {}}-#[cfg(test)]+#[cfg(all(test, target_os = "macos"))]mod tests {use super::*;#[test]- #[cfg(target_os = "macos")]fn macos_advertises_only_supported_capabilities() {let caps = compute_capabilities(None);// Ensure unsupported features on macOS are never advertised@@ -443,10 +442,10 @@ mod tests {"macOS must not advertise media.stream");assert!(!caps.contains(&nectarlink_core::MIC_LISTEN.into()), "macOS must not advertise mic.listen");+ assert!(!caps.contains(&nectarlink_core::PC_WAKE.into()), "macOS must not advertise pc.wake");// Ensure supported features on macOS are advertisedassert!(caps.contains(&"pc.power".into()));- assert!(caps.contains(&nectarlink_core::PC_WAKE.into()));assert!(caps.contains(&nectarlink_core::PHOTOS_SHOW.into()));assert!(caps.contains(&nectarlink_core::CAMERA_CONTINUITY.into()));assert!(caps.contains(&nectarlink_core::CALLS_SHOW.into()));diff --git a/desktop/app/src/mac/audio.rs b/desktop/app/src/mac/audio.rsindex 6955de0..37ec625 100644--- a/desktop/app/src/mac/audio.rs+++ b/desktop/app/src/mac/audio.rs@@ -57,20 +57,34 @@ pub fn speaker_volume_down() -> Result<(u8, bool), String> {Ok((next, muted))}-pub fn mic_muted() -> Option<bool> {+static LAST_MIC_VOL: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(75);++pub fn mic_volume() -> Option<u8> {let output = std::process::Command::new("osascript").args(["-e", "input volume of (get volume settings)"]).output().ok()?;let text = String::from_utf8_lossy(&output.stdout);- let vol: u8 = text.trim().parse().ok()?;- Some(vol == 0)+ text.trim().parse().ok()+}++pub fn mic_muted() -> Option<bool> {+ mic_volume().map(|vol| vol == 0)}pub fn toggle_mic_mute() -> Result<bool, String> {- let muted = mic_muted().unwrap_or(false);+ let current_vol = mic_volume().unwrap_or(0);+ let muted = current_vol == 0;let next = !muted;- let vol = if next { 0 } else { 75 };+ let vol = if next {+ if current_vol > 0 {+ LAST_MIC_VOL.store(current_vol, std::sync::atomic::Ordering::Relaxed);+ }+ 0+ } else {+ let saved = LAST_MIC_VOL.load(std::sync::atomic::Ordering::Relaxed);+ if saved > 0 { saved } else { 75 }+ };let script = format!("set volume input volume {vol}");std::process::Command::new("osascript").args(["-e", &script]).output().map_err(|e| e.to_string())?;Ok(next)@@ -86,6 +100,7 @@ pub fn output_devices() -> Vec<nectarlink_core::AudioOutputDevice> {pub fn watch(_changed: fn()) {}+#[allow(dead_code)]pub fn start(_on_changed: impl Fn() + Send + Sync + 'static) {}#[cfg(test)]@@ -103,9 +118,8 @@ mod tests {#[test]fn query_live_speaker_state() {- let state = speaker_state();- assert!(state.is_some());- let (vol, _muted) = state.unwrap();- assert!(vol <= 100);+ if let Some((vol, _muted)) = speaker_state() {+ assert!(vol <= 100);+ }}}diff --git a/desktop/app/src/mac/autostart.rs b/desktop/app/src/mac/autostart.rsindex 4c4252c..ff09f83 100644--- a/desktop/app/src/mac/autostart.rs+++ b/desktop/app/src/mac/autostart.rs@@ -16,6 +16,14 @@ pub fn is_installed(_exe: &Path) -> bool {is_enabled()}+fn xml_escape(s: &str) -> String {+ s.replace('&', "&")+ .replace('<', "<")+ .replace('>', ">")+ .replace('"', """)+ .replace('\'', "'")+}+pub fn set_enabled(enabled: bool) -> Result<(), String> {if let Some(dir) = dirs::home_dir() {let agents = dir.join("Library/LaunchAgents");@@ -23,6 +31,7 @@ pub fn set_enabled(enabled: bool) -> Result<(), String> {if enabled {let _ = std::fs::create_dir_all(&agents);let exe = std::env::current_exe().map_err(|e| e.to_string())?;+ let escaped_exe = xml_escape(&exe.to_string_lossy());let content = format!(r#"<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">@@ -32,14 +41,12 @@ pub fn set_enabled(enabled: bool) -> Result<(), String> {<string>com.thtbee.nectarlink</string><key>ProgramArguments</key><array>- <string>{}</string>- <string>--minimized</string>+ <string>{escaped_exe}</string></array><key>RunAtLoad</key><true/></dict>-</plist>"#,- exe.display()+</plist>"#);std::fs::write(&plist, content).map_err(|e| e.to_string())?;} else if plist.exists() {diff --git a/desktop/app/src/mac/browser.rs b/desktop/app/src/mac/browser.rsindex c5eb9da..e43e569 100644--- a/desktop/app/src/mac/browser.rs+++ b/desktop/app/src/mac/browser.rs@@ -16,6 +16,7 @@ pub fn is_browser(program: &str) -> bool {#[derive(Debug, Clone)]pub struct Window {+ #[allow(dead_code)]pub hwnd: isize,pub program: String,pub title: String,diff --git a/desktop/app/src/mac/clipboard.rs b/desktop/app/src/mac/clipboard.rsindex b721a02..a69130b 100644--- a/desktop/app/src/mac/clipboard.rs+++ b/desktop/app/src/mac/clipboard.rs@@ -11,6 +11,7 @@ use std::{static CLIP_COUNTER: AtomicU64 = AtomicU64::new(0);+#[allow(dead_code)]#[derive(Clone, PartialEq, Eq)]pub enum Image {Png(Vec<u8>),@@ -38,7 +39,12 @@ impl Image {#[derive(Debug, Clone, PartialEq, Eq)]pub enum Clip {- Text { text: String, html: Option<String>, rtf: Option<String> },+ Text {+ text: String,+ html: Option<String>,+ rtf: Option<String>,+ },+ #[allow(dead_code)]Image(Image),Private,Empty,@@ -47,23 +53,41 @@ pub enum Clip {type OnCopy = Box<dyn Fn(Clip) + Send + Sync>;static ON_COPY: OnceLock<OnCopy> = OnceLock::new();static LAST_TEXT: Mutex<Option<String>> = Mutex::new(None);+static LAST_COUNT: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(-1);pub fn start(on_copy: impl Fn(Clip) + Send + Sync + 'static) {let _ = ON_COPY.set(Box::new(on_copy));+ // Record initial changeCount at startup so we never broadcast existing clipboard contents+ let initial_count = crate::bridge::native::ffi::mac_clipboard_change_count();+ LAST_COUNT.store(initial_count, Ordering::Relaxed);+std::thread::Builder::new().name("mac-clipboard-watcher".into()).spawn(|| {loop {std::thread::sleep(std::time::Duration::from_millis(500));- let clip = read();- if let Clip::Text { text, .. } = &clip {- let mut last = LAST_TEXT.lock().unwrap_or_else(|e| e.into_inner());- if last.as_deref() != Some(text) {- *last = Some(text.clone());- drop(last);- if let Some(cb) = ON_COPY.get() {- cb(clip);+ let count = crate::bridge::native::ffi::mac_clipboard_change_count();+ let last = LAST_COUNT.load(Ordering::Relaxed);+ if count != last {+ LAST_COUNT.store(count, Ordering::Relaxed);+ let clip = read();+ match &clip {+ Clip::Text { text, .. } => {+ let mut last_text = LAST_TEXT.lock().unwrap_or_else(|e| e.into_inner());+ if last_text.as_deref() != Some(text) {+ *last_text = Some(text.clone());+ drop(last_text);+ if let Some(cb) = ON_COPY.get() {+ cb(clip);+ }+ }+ }+ Clip::Private => {+ if let Some(cb) = ON_COPY.get() {+ cb(clip);+ }}+ _ => {}}}}@@ -72,12 +96,13 @@ pub fn start(on_copy: impl Fn(Clip) + Send + Sync + 'static) {}pub fn read() -> Clip {- let output = std::process::Command::new("pbpaste").output().ok();- if let Some(out) = output {- let text = String::from_utf8_lossy(&out.stdout).to_string();- if !text.is_empty() {- return Clip::Text { text, html: None, rtf: None };- }+ let mut is_private = false;+ let text = crate::bridge::native::ffi::mac_clipboard_read_text(&mut is_private);+ if is_private {+ return Clip::Private;+ }+ if !text.is_empty() {+ return Clip::Text { text, html: None, rtf: None };}Clip::Empty}@@ -91,20 +116,12 @@ pub fn read_image_png() -> Option<Vec<u8>> {}pub fn write(text: &str) -> Result<(), String> {- use std::io::Write;- let mut child = std::process::Command::new("pbcopy")- .stdin(std::process::Stdio::piped())- .spawn()- .map_err(|e| e.to_string())?;- if let Some(mut stdin) = child.stdin.take() {- stdin.write_all(text.as_bytes()).map_err(|e| e.to_string())?;- }- let status = child.wait().map_err(|e| e.to_string())?;- if status.success() {+ if crate::bridge::native::ffi::mac_clipboard_write_text(text, false) {*LAST_TEXT.lock().unwrap_or_else(|e| e.into_inner()) = Some(text.to_string());+ LAST_COUNT.store(crate::bridge::native::ffi::mac_clipboard_change_count(), Ordering::Relaxed);Ok(())} else {- Err("pbcopy failed".into())+ Err("mac_clipboard_write_text failed".into())}}@@ -113,7 +130,13 @@ pub fn write_rich(text: &str, _html: Option<&str>, _rtf: Option<&str>) -> Result}pub fn write_private(text: &str) -> Result<(), String> {- write(text)+ if crate::bridge::native::ffi::mac_clipboard_write_text(text, true) {+ *LAST_TEXT.lock().unwrap_or_else(|e| e.into_inner()) = Some(text.to_string());+ LAST_COUNT.store(crate::bridge::native::ffi::mac_clipboard_change_count(), Ordering::Relaxed);+ Ok(())+ } else {+ Err("mac_clipboard_write_text failed".into())+ }}pub fn write_image(mime: &str, bytes: &[u8]) -> Result<(), String> {@@ -143,18 +166,22 @@ pub fn write_image(mime: &str, bytes: &[u8]) -> Result<(), String> {}}+#[allow(dead_code)]pub fn build_dropfiles_payload(_paths: &[PathBuf]) -> Vec<u8> {Vec::new()}+#[allow(dead_code)]pub fn parse_dropfiles_payload(_bytes: &[u8]) -> Option<Vec<PathBuf>> {None}+#[allow(dead_code)]pub fn read_files() -> Option<Vec<PathBuf>> {None}+#[allow(dead_code)]pub fn write_files(_paths: &[PathBuf]) -> bool {false}diff --git a/desktop/app/src/mac/doctor.rs b/desktop/app/src/mac/doctor.rsindex 60f1e73..cbdb4d1 100644--- a/desktop/app/src/mac/doctor.rs+++ b/desktop/app/src/mac/doctor.rs@@ -23,11 +23,11 @@ pub struct Adapters {}pub fn firewall(_exe: &Path) -> Result<Firewall, String> {- Ok(Firewall { on: false, allowed: true, blocked: false })+ Err("firewall check is not supported on macOS".into())}pub fn networks() -> Result<Vec<Network>, String> {- Ok(vec![Network { name: "Wi-Fi".into(), trusted: true }])+ Err("network profile check is not supported on macOS".into())}pub fn adapters() -> Adapters {@@ -35,7 +35,7 @@ pub fn adapters() -> Adapters {}pub fn fix_firewall(_exe: &Path) -> Result<bool, String> {- Ok(true)+ Err("automatic firewall configuration is not supported on macOS".into())}pub fn open_firewall_settings() -> bool {@@ -45,6 +45,7 @@ pub fn open_firewall_settings() -> bool {true}+#[allow(dead_code)]pub fn diagnose() -> Vec<(String, bool, String)> {Vec::new()}diff --git a/desktop/app/src/mac/elevated.rs b/desktop/app/src/mac/elevated.rsindex b0bcb32..05d5b8b 100644--- a/desktop/app/src/mac/elevated.rs+++ b/desktop/app/src/mac/elevated.rs@@ -4,6 +4,7 @@use std::path::Path;pub enum Error {+ #[allow(dead_code)]Declined,Other(String),}@@ -17,5 +18,5 @@ impl Process {}pub fn start(_program: &Path, _params: &str) -> Result<Process, Error> {- Ok(Process)+ Err(Error::Other("elevated execution is not supported on macOS".into()))}diff --git a/desktop/app/src/mac/h264.rs b/desktop/app/src/mac/h264.rsindex 1633d84..f5c49de 100644--- a/desktop/app/src/mac/h264.rs+++ b/desktop/app/src/mac/h264.rs@@ -8,6 +8,7 @@ pub struct Colors {}#[derive(Debug)]+#[allow(dead_code)]pub struct Picture {pub width: u32,pub height: u32,@@ -51,6 +52,7 @@ pub fn to_bgrx(picture: &Picture, width: u32, height: u32) -> Vec<u8> {vec![0; w * h * 4]}+#[allow(dead_code)]pub fn ensure_mf_started() -> Result<(), String> {Ok(())}diff --git a/desktop/app/src/mac/image.rs b/desktop/app/src/mac/image.rsindex 50833e0..5228fb8 100644--- a/desktop/app/src/mac/image.rs+++ b/desktop/app/src/mac/image.rs@@ -27,6 +27,7 @@ pub fn encode_png(bitmap: &Bitmap) -> Result<Vec<u8>, String> {Ok(create_png(bitmap.width, bitmap.height, &bitmap.bgra))}+#[allow(dead_code)]pub fn bmp_from_dib(dib: &[u8]) -> Option<Vec<u8>> {Some(dib.to_vec())}diff --git a/desktop/app/src/mac/input.rs b/desktop/app/src/mac/input.rsindex 24263bd..8974f72 100644--- a/desktop/app/src/mac/input.rs+++ b/desktop/app/src/mac/input.rs@@ -4,7 +4,9 @@use nectarlink_core::{ButtonAction, KeyMod, MouseButton, SlideAction, TouchAction};pub fn move_relative(_dx: f32, _dy: f32) {}+#[allow(dead_code)]pub fn move_absolute(_x: f32, _y: f32) {}+#[allow(dead_code)]pub fn mirror_touch(_action: TouchAction, _x: f32, _y: f32) {}pub fn mouse_button(_button: MouseButton, _action: ButtonAction) {}pub fn release_held_buttons() {}diff --git a/desktop/app/src/mac/media_sessions.rs b/desktop/app/src/mac/media_sessions.rsindex 65fad71..05e4850 100644--- a/desktop/app/src/mac/media_sessions.rs+++ b/desktop/app/src/mac/media_sessions.rs@@ -13,6 +13,7 @@ pub fn pause_for_call() {}pub fn resume_after_call() {}+#[allow(dead_code)]pub fn says_video(_id: &str) -> bool {false}diff --git a/desktop/app/src/mac/mod.rs b/desktop/app/src/mac/mod.rsindex d240b62..1c135c4 100644--- a/desktop/app/src/mac/mod.rs+++ b/desktop/app/src/mac/mod.rs@@ -2,8 +2,6 @@//! macOS integration: system facts, single instance, clipboard, sound,//! notifications, volume, and shell operations.-#![allow(dead_code, unused_imports)]-pub mod audio;pub mod audio_out;pub mod autostart;@@ -118,10 +116,12 @@ pub fn secure_random(buf: &mut [u8]) -> bool {}/// On macOS, COM is not used. Runs `f` directly.+#[allow(dead_code)]pub fn with_com<T>(f: impl FnOnce() -> T) -> T {f()}+#[allow(dead_code)]pub(crate) fn reg_string(_root: u32, _key: &str, _value: &str) -> Option<String> {None}diff --git a/desktop/app/src/mac/shell.rs b/desktop/app/src/mac/shell.rsindex e79e127..99348e6 100644--- a/desktop/app/src/mac/shell.rs+++ b/desktop/app/src/mac/shell.rs@@ -28,6 +28,7 @@ pub fn open_maps(address: &str) -> Result<(), String> {}/// Returns `true` if `scheme` is recognized.+#[allow(dead_code)]pub fn is_url_scheme_registered(scheme: &str) -> bool {matches!(scheme.trim(), "http" | "https" | "mailto" | "maps")}@@ -43,12 +44,25 @@ pub fn run(program: &Path, arguments: &str) -> Result<(), String> {/// Locks the Mac screen.pub fn lock() -> Result<(), String> {- let script = r#"tell application "System Events" to key code 12 using {control down, command down}"#;- std::process::Command::new("osascript")- .args(["-e", script])- .spawn()- .map(|_| ())- .map_err(|e| e.to_string())+ // CGSession -suspend locks the screen directly without accessibility prompts.+ let status = std::process::Command::new(+ "/System/Library/CoreServices/Menu Extras/User.menu/Contents/Resources/CGSession",+ )+ .arg("-suspend")+ .status();+ if status.is_ok_and(|s| s.success()) {+ return Ok(());+ }+ // Fallback to osascript with status check+ let output = std::process::Command::new("osascript")+ .args(["-e", r#"tell application "System Events" to key code 12 using {control down, command down}"#])+ .output()+ .map_err(|e| e.to_string())?;+ if output.status.success() {+ Ok(())+ } else {+ Err(String::from_utf8_lossy(&output.stderr).trim().to_string())+ }}/// Puts the Mac to sleep.diff --git a/desktop/app/src/mac/smtc.rs b/desktop/app/src/mac/smtc.rsindex 155542d..c248bf8 100644--- a/desktop/app/src/mac/smtc.rs+++ b/desktop/app/src/mac/smtc.rs@@ -4,6 +4,7 @@use crate::state::PlayerView;use nectarlink_core::{DeviceId, MediaAction};+#[allow(dead_code)]#[derive(Debug, Clone)]pub struct Shown {pub device: DeviceId,@@ -13,4 +14,5 @@ pub struct Shown {pub fn start(_on_command: impl Fn(DeviceId, String, MediaAction, Option<u64>) + Send + Sync + 'static) {}pub fn show(_shown: Option<Shown>) {}+#[allow(dead_code)]pub fn clear() {}diff --git a/desktop/app/src/mac/sound.rs b/desktop/app/src/mac/sound.rsindex 7817838..0f6a3ae 100644--- a/desktop/app/src/mac/sound.rs+++ b/desktop/app/src/mac/sound.rs@@ -2,19 +2,26 @@//! macOS sound ringing ("find my PC" from phone).use std::{- sync::atomic::{AtomicU64, Ordering},+ sync::atomic::{AtomicU32, AtomicU64, Ordering},time::Duration,};const MAX_RING: Duration = Duration::from_secs(60);static GENERATION: AtomicU64 = AtomicU64::new(0);+static CURRENT_PID: AtomicU32 = AtomicU32::new(0);pub fn start_ringing() {let generation = GENERATION.fetch_add(1, Ordering::SeqCst) + 1;let _ = std::thread::Builder::new().name("mac-ring".into()).spawn(move || {let start = std::time::Instant::now();while start.elapsed() < MAX_RING && GENERATION.load(Ordering::SeqCst) == generation {- let _ = std::process::Command::new("afplay").arg("/System/Library/Sounds/Ping.aiff").status();+ if let Ok(mut child) =+ std::process::Command::new("afplay").arg("/System/Library/Sounds/Ping.aiff").spawn()+ {+ CURRENT_PID.store(child.id(), Ordering::SeqCst);+ let _ = child.wait();+ CURRENT_PID.store(0, Ordering::SeqCst);+ }std::thread::sleep(Duration::from_millis(600));}});@@ -22,5 +29,8 @@ pub fn start_ringing() {pub fn stop_ringing() {GENERATION.fetch_add(1, Ordering::SeqCst);- let _ = std::process::Command::new("killall").arg("afplay").output();+ let pid = CURRENT_PID.swap(0, Ordering::SeqCst);+ if pid != 0 {+ let _ = std::process::Command::new("kill").arg("-9").arg(pid.to_string()).output();+ }}diff --git a/desktop/app/src/mac/toast.rs b/desktop/app/src/mac/toast.rsindex d1de2a6..ecab9e0 100644--- a/desktop/app/src/mac/toast.rs+++ b/desktop/app/src/mac/toast.rs@@ -6,11 +6,13 @@ use std::{sync::{Mutex, OnceLock},};+#[allow(dead_code)]pub const AUMID: &str = "com.thtbee.nectarlink";pub const CALL_ANSWER: &str = "answer";pub const CALL_DECLINE: &str = "decline";pub const CALL_END: &str = "end";+#[allow(dead_code)]#[derive(Debug, Clone, PartialEq, Eq)]pub enum ToastEvent {Opened { device: String, key: String },@@ -19,6 +21,7 @@ pub enum ToastEvent {Dismissed { device: String, key: String },}+#[allow(dead_code)]#[derive(Clone)]pub struct Toast {pub device: String,diff --git a/desktop/app/src/mac/tray.rs b/desktop/app/src/mac/tray.rsindex 51c3d98..6114408 100644--- a/desktop/app/src/mac/tray.rs+++ b/desktop/app/src/mac/tray.rs@@ -1,6 +1,7 @@// SPDX-License-Identifier: GPL-3.0-or-later//! macOS status bar / tray integration stubs.+#[allow(dead_code)]#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum TrayEvent {Open,@@ -15,6 +16,7 @@ pub enum TrayEvent {AppearanceChanged,}+#[allow(dead_code)]#[derive(Debug, Clone)]pub struct MenuLabels {pub open: String,@@ -45,6 +47,7 @@ impl Tray {pub fn update_hotkeys(_photo_spec: &str, _scan_spec: &str, _palette_spec: &str, _shelf_spec: &str) {}+#[allow(dead_code)]pub fn record_foreground_window() {}pub fn apply_no_activate_style_by_title(_title: &str) {}@@ -63,6 +66,7 @@ pub fn snapshot_target_window() -> Option<(isize, String)> {pub fn send_paste_fallback_if_not_foreground(_hwnd: isize) {}+#[allow(dead_code)]pub fn parse_hotkey(_spec: &str) -> Option<(u32, u32)> {None}diff --git a/desktop/app/src/mac/window_capture.rs b/desktop/app/src/mac/window_capture.rsindex fe0e6a5..ba5d002 100644--- a/desktop/app/src/mac/window_capture.rs+++ b/desktop/app/src/mac/window_capture.rs@@ -1,9 +1,11 @@// SPDX-License-Identifier: GPL-3.0-or-later//! macOS window capture stubs.+#[allow(dead_code)]#[derive(Debug)]pub struct WindowCapture;+#[allow(dead_code)]impl WindowCapture {pub fn new(_window: &super::browser::Window) -> Option<Self> {Nonediff --git a/desktop/app/src/mac/wol.rs b/desktop/app/src/mac/wol.rsindex 408b2b6..052c7fc 100644--- a/desktop/app/src/mac/wol.rs+++ b/desktop/app/src/mac/wol.rs@@ -3,6 +3,7 @@use nectarlink_core::PcWakeInfo;+#[allow(dead_code)]#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum WakeSupport {Enabled,@@ -52,6 +53,7 @@ pub fn query_wake_status() -> WakeStatus {WakeStatus::default()}+#[allow(dead_code)]pub fn wake(_mac: &[u8]) -> Result<(), String> {- Ok(())+ Err("wake-on-lan is not supported on macOS".into())}diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rsindex 8a00937..ba3739f 100644--- a/desktop/app/src/settings.rs+++ b/desktop/app/src/settings.rs@@ -118,6 +118,10 @@ fn default_true() -> bool {true}+fn default_close_to_tray() -> bool {+ !cfg!(target_os = "macos")+}+fn default_webcam_camera() -> String {"back".to_owned()}@@ -316,7 +320,7 @@ pub struct Settings {#[serde(default = "default_true", alias = "comb_motion")]pub comb_motion: bool,/// Closing the window keeps NectarLink running in the tray.- #[serde(alias = "close_to_tray")]+ #[serde(default = "default_close_to_tray", alias = "close_to_tray")]pub close_to_tray: bool,/// Send what's copied on this PC to connected phones.#[serde(alias = "auto_clipboard", alias = "clipboard_sync")]@@ -493,7 +497,7 @@ impl Default for Settings {amoled: false,backdrop: true,comb_motion: true,- close_to_tray: true,+ close_to_tray: default_close_to_tray(),auto_clipboard: true,clipboard_history: true,suggest_clipboard_actions: true,@@ -567,6 +571,10 @@ impl Settings {self.window_x = None;self.window_y = None;}+ #[cfg(target_os = "macos")]+ {+ self.close_to_tray = false;+ }self}