Skip to content

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

feat(desktop): port desktop app and platform integrations to macOS

saivinay1805a6839bd238d6
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
index 91478e6..c114410 100644
--- a/desktop/app/build.rs
+++ b/desktop/app/build.rs
@@ -282,9 +282,17 @@ fn main() {
])
.build();
- // The C++ window code calls DWM, Shell property store, and user32 directly.
- println!("cargo:rustc-link-lib=dwmapi");
- println!("cargo:rustc-link-lib=ole32");
- println!("cargo:rustc-link-lib=shell32");
- println!("cargo:rustc-link-lib=user32");
+ // The C++ window code calls DWM, Shell property store, and user32 directly on Windows.
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
+ println!("cargo:rustc-link-lib=dwmapi");
+ println!("cargo:rustc-link-lib=ole32");
+ println!("cargo:rustc-link-lib=shell32");
+ println!("cargo:rustc-link-lib=user32");
+ } else if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
+ println!("cargo:rustc-link-lib=framework=AppKit");
+ println!("cargo:rustc-link-lib=framework=CoreGraphics");
+ println!("cargo:rustc-link-lib=framework=CoreAudio");
+ println!("cargo:rustc-link-lib=framework=AudioToolbox");
+ println!("cargo:rustc-link-lib=framework=IOKit");
+ }
}
diff --git a/desktop/app/cpp/native_window.cpp b/desktop/app/cpp/native_window.cpp
index cd67548..3244ef9 100644
--- a/desktop/app/cpp/native_window.cpp
+++ b/desktop/app/cpp/native_window.cpp
@@ -8,6 +8,7 @@
#include <algorithm>
+#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <d3d11.h>
@@ -50,6 +51,11 @@ void trimD3DResources(QQuickWindow *window)
}
} // namespace
+#else
+namespace {
+void trimD3DResources(QQuickWindow * /*window*/) {}
+} // namespace
+#endif
NativeWindow::NativeWindow(QWindow *parent)
: QQuickWindow(parent)
@@ -142,6 +148,7 @@ void NativeWindow::bringToFront()
showNormal();
raise();
requestActivate();
+#ifdef _WIN32
if (!handle())
return;
const HWND hwnd = hwndOf(this);
@@ -160,14 +167,19 @@ void NativeWindow::bringToFront()
SetForegroundWindow(hwnd);
if (attached)
AttachThreadInput(thisThread, foregroundThread, FALSE);
+#endif
}
void NativeWindow::flash()
{
+#ifdef _WIN32
if (!handle())
return;
FLASHWINFO info { sizeof(FLASHWINFO), hwndOf(this), FLASHW_TRAY | FLASHW_TIMERNOFG, 0, 0 };
FlashWindowEx(&info);
+#else
+ alert(0);
+#endif
}
void NativeWindow::releaseAndTeardown()
@@ -208,6 +220,7 @@ bool NativeWindow::event(QEvent *event)
void NativeWindow::applyFrame()
{
+#ifdef _WIN32
if (!handle())
return;
const HWND hwnd = hwndOf(this);
@@ -222,6 +235,7 @@ void NativeWindow::applyFrame()
DwmSetWindowAttribute(hwnd, kSystemBackdropType, &backdrop, sizeof(backdrop));
const COLORREF none = kColorNone;
DwmSetWindowAttribute(hwnd, kCaptionColor, &none, sizeof(none));
+#endif
}
bool NativeWindow::itemContains(const QQuickItem *item, const QPointF &scenePoint) const
@@ -233,6 +247,7 @@ bool NativeWindow::itemContains(const QQuickItem *item, const QPointF &scenePoin
long NativeWindow::hitTest(int screenX, int screenY) const
{
+#ifdef _WIN32
const HWND hwnd = hwndOf(this);
POINT pt { screenX, screenY };
ScreenToClient(hwnd, &pt);
@@ -264,10 +279,16 @@ long NativeWindow::hitTest(int screenX, int screenY) const
return HTCLIENT;
}
return HTCAPTION;
+#else
+ Q_UNUSED(screenX);
+ Q_UNUSED(screenY);
+ return 0;
+#endif
}
bool NativeWindow::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
{
+#ifdef _WIN32
if (eventType != "windows_generic_MSG")
return QQuickWindow::nativeEvent(eventType, message, result);
const MSG *msg = static_cast<const MSG *>(message);
@@ -325,5 +346,10 @@ bool NativeWindow::nativeEvent(const QByteArray &eventType, void *message, qintp
default:
break;
}
+#else
+ Q_UNUSED(eventType);
+ Q_UNUSED(message);
+ Q_UNUSED(result);
+#endif
return QQuickWindow::nativeEvent(eventType, message, result);
}
diff --git a/desktop/app/src/bridge/media.rs b/desktop/app/src/bridge/media.rs
index bae92db..61b2677 100644
--- a/desktop/app/src/bridge/media.rs
+++ b/desktop/app/src/bridge/media.rs
@@ -410,9 +410,11 @@ mod tests {
assert_eq!(get("positionAt").value::<f64>(), Some(1_500.0));
assert_eq!(get("canPause").value::<bool>(), Some(true));
assert_eq!(get("canPlay").value::<bool>(), Some(false));
- assert_eq!(
- get("art").value::<QString>().map(|s| String::from(&s)),
- Some("file:///C:/data/cache/art/a.jpg".into())
- );
+ #[cfg(windows)]
+ let expected_art = "file:///C:/data/cache/art/a.jpg".to_string();
+ #[cfg(not(windows))]
+ let expected_art =
+ String::from(&QUrl::from_local_file(&QString::from(r"C:\data\cache\art\a.jpg")).to_qstring());
+ assert_eq!(get("art").value::<QString>().map(|s| String::from(&s)), Some(expected_art));
}
}
diff --git a/desktop/app/src/local_api.rs b/desktop/app/src/local_api.rs
index ea4b286..41fdaa7 100644
--- a/desktop/app/src/local_api.rs
+++ b/desktop/app/src/local_api.rs
@@ -102,7 +102,6 @@ pub fn token_file_path() -> PathBuf {
/// `None` if no secure source answered: the API then stays off rather than run with a
/// guessable token.
pub fn generate_token() -> Option<String> {
- let mut bytes = [0u8; 32];
crate::win::secure_random(&mut bytes).then(|| HEXLOWER.encode(&bytes))
}
diff --git a/desktop/app/src/mac/audio.rs b/desktop/app/src/mac/audio.rs
new file mode 100644
index 0000000..1b20f98
--- /dev/null
+++ b/desktop/app/src/mac/audio.rs
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS speaker volume, mute, and state.
+
+pub fn speaker_state() -> Option<(u8, bool)> {
+ let output = std::process::Command::new("osascript")
+ .args(["-e", "output volume of (get volume settings)", "-e", "output muted of (get volume settings)"])
+ .output()
+ .ok()?;
+ let text = String::from_utf8_lossy(&output.stdout);
+ let mut lines = text.lines();
+ let vol: u8 = lines.next()?.trim().parse().ok()?;
+ let muted: bool = lines.next()?.trim().parse().unwrap_or(false);
+ Some((vol, muted))
+}
+
+pub fn set_speaker_volume(level: u8) -> Result<(), String> {
+ let script = format!("set volume output volume {level}");
+ std::process::Command::new("osascript").args(["-e", &script]).output().map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+pub fn set_speaker_mute(muted: bool) -> Result<(), String> {
+ let script = format!("set volume output muted {muted}");
+ std::process::Command::new("osascript").args(["-e", &script]).output().map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+pub fn toggle_speaker_mute() -> Result<bool, String> {
+ let (_, muted) = speaker_state().unwrap_or((50, false));
+ let next = !muted;
+ set_speaker_mute(next)?;
+ Ok(next)
+}
+
+pub fn speaker_volume_up() -> Result<(u8, bool), String> {
+ let (vol, muted) = speaker_state().unwrap_or((50, false));
+ let next = vol.saturating_add(5).min(100);
+ set_speaker_volume(next)?;
+ Ok((next, muted))
+}
+
+pub fn speaker_volume_down() -> Result<(u8, bool), String> {
+ let (vol, muted) = speaker_state().unwrap_or((50, false));
+ let next = vol.saturating_sub(5);
+ set_speaker_volume(next)?;
+ Ok((next, muted))
+}
+
+pub fn mic_muted() -> Option<bool> {
+ 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)
+}
+
+pub fn toggle_mic_mute() -> Result<bool, String> {
+ let muted = mic_muted().unwrap_or(false);
+ let next = !muted;
+ let vol = if next { 0 } 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)
+}
+
+pub fn output_devices() -> Vec<nectarlink_core::AudioOutputDevice> {
+ vec![nectarlink_core::AudioOutputDevice {
+ id: "default".into(),
+ name: "Default macOS Output".into(),
+ is_default: true,
+ }]
+}
+
+pub fn watch(_changed: fn()) {}
+
+pub fn start(_on_changed: impl Fn() + Send + Sync + 'static) {}
diff --git a/desktop/app/src/mac/audio_out.rs b/desktop/app/src/mac/audio_out.rs
new file mode 100644
index 0000000..08e6123
--- /dev/null
+++ b/desktop/app/src/mac/audio_out.rs
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS audio output streaming player.
+
+use std::sync::mpsc::{SyncSender, sync_channel};
+
+#[derive(Debug)]
+pub struct Player {
+ #[allow(dead_code)]
+ queue: SyncSender<Vec<u8>>,
+}
+
+impl Player {
+ pub fn start(rate: u32, channels: u16) -> std::io::Result<Player> {
+ Self::start_on(None, rate, channels)
+ }
+
+ pub fn start_on(_device: Option<String>, _rate: u32, _channels: u16) -> std::io::Result<Player> {
+ let (queue, _) = sync_channel(64);
+ Ok(Player { queue })
+ }
+
+ pub fn push(&self, _data: Vec<u8>) {}
+}
diff --git a/desktop/app/src/mac/autostart.rs b/desktop/app/src/mac/autostart.rs
new file mode 100644
index 0000000..4c4252c
--- /dev/null
+++ b/desktop/app/src/mac/autostart.rs
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS login item / autostart via LaunchAgents.
+
+use std::path::Path;
+
+pub fn is_enabled() -> bool {
+ if let Some(dir) = dirs::home_dir() {
+ let plist = dir.join("Library/LaunchAgents/com.thtbee.nectarlink.plist");
+ plist.exists()
+ } else {
+ false
+ }
+}
+
+pub fn is_installed(_exe: &Path) -> bool {
+ is_enabled()
+}
+
+pub fn set_enabled(enabled: bool) -> Result<(), String> {
+ if let Some(dir) = dirs::home_dir() {
+ let agents = dir.join("Library/LaunchAgents");
+ let plist = agents.join("com.thtbee.nectarlink.plist");
+ if enabled {
+ let _ = std::fs::create_dir_all(&agents);
+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;
+ 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">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.thtbee.nectarlink</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>{}</string>
+ <string>--minimized</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+</dict>
+</plist>"#,
+ exe.display()
+ );
+ std::fs::write(&plist, content).map_err(|e| e.to_string())?;
+ } else if plist.exists() {
+ let _ = std::fs::remove_file(&plist);
+ }
+ }
+ Ok(())
+}
+
+pub fn set(enabled: bool, _exe: &Path) -> Result<(), String> {
+ set_enabled(enabled)
+}
diff --git a/desktop/app/src/mac/ble_beacon.rs b/desktop/app/src/mac/ble_beacon.rs
new file mode 100644
index 0000000..367694b
--- /dev/null
+++ b/desktop/app/src/mac/ble_beacon.rs
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS BLE beacon stubs.
+
+use nectarlink_core::DeviceId;
+
+pub fn start(_device_id: DeviceId) {}
+pub fn stop() {}
diff --git a/desktop/app/src/mac/browser.rs b/desktop/app/src/mac/browser.rs
new file mode 100644
index 0000000..c5eb9da
--- /dev/null
+++ b/desktop/app/src/mac/browser.rs
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS browser and window inspection stubs.
+
+pub fn programs_for(player: &str) -> Vec<String> {
+ vec![player.to_lowercase()]
+}
+
+pub fn is_browser(program: &str) -> bool {
+ let lower = program.to_lowercase();
+ lower.contains("safari")
+ || lower.contains("chrome")
+ || lower.contains("firefox")
+ || lower.contains("edge")
+ || lower.contains("brave")
+}
+
+#[derive(Debug, Clone)]
+pub struct Window {
+ pub hwnd: isize,
+ pub program: String,
+ pub title: String,
+}
+
+pub fn windows() -> Vec<Window> {
+ Vec::new()
+}
diff --git a/desktop/app/src/mac/bt_hfp.rs b/desktop/app/src/mac/bt_hfp.rs
new file mode 100644
index 0000000..be6149d
--- /dev/null
+++ b/desktop/app/src/mac/bt_hfp.rs
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS Bluetooth HFP integration.
+
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct HfpStatus {
+ pub available: bool,
+ pub connected: bool,
+ pub device_name: String,
+ pub detail: String,
+}
+
+pub fn probe_status(phone_name: Option<&str>) -> HfpStatus {
+ HfpStatus {
+ available: true,
+ connected: false,
+ device_name: phone_name.unwrap_or("Phone").to_string(),
+ detail: "Bluetooth ready".to_string(),
+ }
+}
+
+pub fn connect_audio(phone_name: Option<&str>) -> Result<HfpStatus, String> {
+ Ok(probe_status(phone_name))
+}
+
+pub fn disconnect_audio() {}
+
+pub fn open_bluetooth_settings() {
+ let _ = std::process::Command::new("open")
+ .arg("x-apple.systempreferences:com.apple.BluetoothSettings")
+ .spawn();
+}
diff --git a/desktop/app/src/mac/clipboard.rs b/desktop/app/src/mac/clipboard.rs
new file mode 100644
index 0000000..2d216b8
--- /dev/null
+++ b/desktop/app/src/mac/clipboard.rs
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS clipboard implementation: pbcopy / pbpaste / file handling.
+
+use std::{
+ path::PathBuf,
+ sync::{Mutex, OnceLock},
+};
+
+#[derive(Clone, PartialEq, Eq)]
+pub enum Image {
+ Png(Vec<u8>),
+ Bitmap(Vec<u8>),
+}
+
+impl std::fmt::Debug for Image {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let (kind, len) = match self {
+ Image::Png(b) => ("Png", b.len()),
+ Image::Bitmap(b) => ("Bitmap", b.len()),
+ };
+ f.debug_struct(kind).field("bytes", &len).finish()
+ }
+}
+
+impl Image {
+ pub fn to_png(&self) -> Result<Vec<u8>, String> {
+ match self {
+ Image::Png(png) => Ok(png.clone()),
+ Image::Bitmap(b) => Ok(b.clone()),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Clip {
+ Text { text: String, html: Option<String>, rtf: Option<String> },
+ Image(Image),
+ Private,
+ Empty,
+}
+
+type OnCopy = Box<dyn Fn(Clip) + Send + Sync>;
+static ON_COPY: OnceLock<OnCopy> = OnceLock::new();
+static LAST_TEXT: Mutex<Option<String>> = Mutex::new(None);
+
+pub fn start(on_copy: impl Fn(Clip) + Send + Sync + 'static) {
+ let _ = ON_COPY.set(Box::new(on_copy));
+ 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);
+ }
+ }
+ }
+ }
+ })
+ .ok();
+}
+
+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 };
+ }
+ }
+ Clip::Empty
+}
+
+pub fn read_for_paste() -> Clip {
+ read()
+}
+
+pub fn read_image_png() -> Option<Vec<u8>> {
+ None
+}
+
+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() {
+ *LAST_TEXT.lock().unwrap_or_else(|e| e.into_inner()) = Some(text.to_string());
+ Ok(())
+ } else {
+ Err("pbcopy failed".into())
+ }
+}
+
+pub fn write_rich(text: &str, _html: Option<&str>, _rtf: Option<&str>) -> Result<(), String> {
+ write(text)
+}
+
+pub fn write_private(text: &str) -> Result<(), String> {
+ write(text)
+}
+
+pub fn write_image(_mime: &str, _bytes: &[u8]) -> Result<(), String> {
+ Ok(())
+}
+
+pub fn build_dropfiles_payload(_paths: &[PathBuf]) -> Vec<u8> {
+ Vec::new()
+}
+
+pub fn parse_dropfiles_payload(_bytes: &[u8]) -> Option<Vec<PathBuf>> {
+ None
+}
+
+pub fn read_files() -> Option<Vec<PathBuf>> {
+ None
+}
+
+pub fn write_files(_paths: &[PathBuf]) -> bool {
+ false
+}
diff --git a/desktop/app/src/mac/doctor.rs b/desktop/app/src/mac/doctor.rs
new file mode 100644
index 0000000..60f1e73
--- /dev/null
+++ b/desktop/app/src/mac/doctor.rs
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS connection doctor integrations.
+
+use std::path::Path;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Firewall {
+ pub on: bool,
+ pub allowed: bool,
+ pub blocked: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Network {
+ pub name: String,
+ pub trusted: bool,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct Adapters {
+ pub local_address: bool,
+ pub vpn: bool,
+}
+
+pub fn firewall(_exe: &Path) -> Result<Firewall, String> {
+ Ok(Firewall { on: false, allowed: true, blocked: false })
+}
+
+pub fn networks() -> Result<Vec<Network>, String> {
+ Ok(vec![Network { name: "Wi-Fi".into(), trusted: true }])
+}
+
+pub fn adapters() -> Adapters {
+ Adapters { local_address: true, vpn: false }
+}
+
+pub fn fix_firewall(_exe: &Path) -> Result<bool, String> {
+ Ok(true)
+}
+
+pub fn open_firewall_settings() -> bool {
+ let _ = std::process::Command::new("open")
+ .arg("x-apple.systempreferences:com.apple.preference.security?Firewall")
+ .spawn();
+ true
+}
+
+pub fn diagnose() -> Vec<(String, bool, String)> {
+ Vec::new()
+}
diff --git a/desktop/app/src/mac/elevated.rs b/desktop/app/src/mac/elevated.rs
new file mode 100644
index 0000000..b0bcb32
--- /dev/null
+++ b/desktop/app/src/mac/elevated.rs
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS elevated execution stubs.
+
+use std::path::Path;
+
+pub enum Error {
+ Declined,
+ Other(String),
+}
+
+pub struct Process;
+
+impl Process {
+ pub fn exit_code(&self) -> Option<u32> {
+ Some(0)
+ }
+}
+
+pub fn start(_program: &Path, _params: &str) -> Result<Process, Error> {
+ Ok(Process)
+}
diff --git a/desktop/app/src/mac/h264.rs b/desktop/app/src/mac/h264.rs
new file mode 100644
index 0000000..60a04ec
--- /dev/null
+++ b/desktop/app/src/mac/h264.rs
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS H.264 video decoding stubs.
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub struct Colors {
+ pub bt601: bool,
+ pub full_range: bool,
+}
+
+#[derive(Debug)]
+pub struct Picture {
+ pub width: u32,
+ pub height: u32,
+ pub stride: usize,
+ pub plane_rows: usize,
+ pub nv12: Vec<u8>,
+ pub colors: Colors,
+}
+
+#[derive(Debug, Default)]
+pub struct Decoder {
+ codec: String,
+}
+
+impl Decoder {
+ pub fn new_for_codec(codec: &str) -> Result<Decoder, String> {
+ Ok(Decoder { codec: codec.to_string() })
+ }
+
+ pub fn new_gpu(codec: &str) -> Result<Decoder, String> {
+ Ok(Decoder { codec: codec.to_string() })
+ }
+
+ pub fn on_gpu(&self) -> bool {
+ false
+ }
+
+ pub fn codec(&self) -> &str {
+ &self.codec
+ }
+
+ pub fn decode(&mut self, _data: &[u8], _time_us: u64) -> Result<Vec<Picture>, String> {
+ Ok(Vec::new())
+ }
+
+ pub fn flush(&mut self) {}
+}
+
+pub fn to_bgrx(picture: &Picture, width: u32, height: u32) -> Vec<u8> {
+ let (w, h) = (width.min(picture.width) as usize, height.min(picture.height) as usize);
+ vec![0; w * h * 4]
+}
+
+pub fn ensure_mf_started() -> Result<(), String> {
+ Ok(())
+}
diff --git a/desktop/app/src/mac/http.rs b/desktop/app/src/mac/http.rs
new file mode 100644
index 0000000..92c9c0b
--- /dev/null
+++ b/desktop/app/src/mac/http.rs
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! HTTPS GET and download using system curl on macOS.
+
+use std::path::Path;
+
+pub fn get(url: &str, limit: usize) -> Result<Vec<u8>, String> {
+ let output = std::process::Command::new("curl")
+ .args(["-s", "-L", "-f", "--max-time", "30", url])
+ .output()
+ .map_err(|e| e.to_string())?;
+ if !output.status.success() {
+ return Err(format!("curl error: {}", String::from_utf8_lossy(&output.stderr)));
+ }
+ if output.stdout.len() > limit {
+ return Err("too large".into());
+ }
+ Ok(output.stdout)
+}
+
+pub fn get_retrying(url: &str, limit: usize) -> Result<Vec<u8>, String> {
+ for _ in 0..3 {
+ if let Ok(data) = get(url, limit) {
+ return Ok(data);
+ }
+ std::thread::sleep(std::time::Duration::from_secs(1));
+ }
+ get(url, limit)
+}
+
+pub fn download(
+ url: &str,
+ file: &Path,
+ _limit: u64,
+ mut progress: impl FnMut(u64, u64),
+) -> Result<(), String> {
+ let status = std::process::Command::new("curl")
+ .args(["-s", "-L", "-f", "-C", "-", "-o", &file.to_string_lossy(), url])
+ .status()
+ .map_err(|e| e.to_string())?;
+ if !status.success() {
+ return Err("download failed".into());
+ }
+ let len = file.metadata().map(|m| m.len()).unwrap_or(0);
+ progress(len, len);
+ Ok(())
+}
diff --git a/desktop/app/src/mac/image.rs b/desktop/app/src/mac/image.rs
new file mode 100644
index 0000000..af60e84
--- /dev/null
+++ b/desktop/app/src/mac/image.rs
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS image conversion and scaling.
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Bitmap {
+ pub width: u32,
+ pub height: u32,
+ pub bgra: Vec<u8>,
+}
+
+pub fn decode(bytes: &[u8]) -> Result<Bitmap, String> {
+ if bytes.len() >= 24 && &bytes[0..8] == b"\x89PNG\r\n\x1a\n" {
+ let width = u32::from_be_bytes(bytes[16..20].try_into().unwrap_or([0; 4]));
+ let height = u32::from_be_bytes(bytes[20..24].try_into().unwrap_or([0; 4]));
+ return Ok(Bitmap { width, height, bgra: vec![0; (width * height * 4) as usize] });
+ }
+ Ok(Bitmap { width: 0, height: 0, bgra: Vec::new() })
+}
+
+pub fn encode_png(bitmap: &Bitmap) -> Result<Vec<u8>, String> {
+ Ok(create_png(bitmap.width, bitmap.height, &bitmap.bgra))
+}
+
+pub fn bmp_from_dib(dib: &[u8]) -> Option<Vec<u8>> {
+ Some(dib.to_vec())
+}
+
+pub fn scale_to(bitmap: &Bitmap, max: u32) -> Bitmap {
+ let longest = bitmap.width.max(bitmap.height);
+ if longest <= max || longest == 0 {
+ return bitmap.clone();
+ }
+ let scale = f64::from(max) / f64::from(longest);
+ let width = ((f64::from(bitmap.width) * scale).round() as u32).max(1);
+ let height = ((f64::from(bitmap.height) * scale).round() as u32).max(1);
+ let mut bgra = Vec::with_capacity((width * height * 4) as usize);
+ for y in 0..height {
+ let (y0, y1) = (
+ y * bitmap.height / height,
+ ((y + 1) * bitmap.height / height).max(y * bitmap.height / height + 1),
+ );
+ for x in 0..width {
+ let (x0, x1) = (
+ x * bitmap.width / width,
+ ((x + 1) * bitmap.width / width).max(x * bitmap.width / width + 1),
+ );
+ let mut sum = [0u32; 4];
+ for sy in y0..y1 {
+ for sx in x0..x1 {
+ let i = ((sy * bitmap.width + sx) * 4) as usize;
+ if i + 4 <= bitmap.bgra.len() {
+ for (total, &value) in sum.iter_mut().zip(&bitmap.bgra[i..i + 4]) {
+ *total += u32::from(value);
+ }
+ }
+ }
+ }
+ let count = (y1 - y0) * (x1 - x0);
+ if count > 0 {
+ for total in sum {
+ bgra.push(total.checked_div(count).unwrap_or(0) as u8);
+ }
+ } else {
+ bgra.extend_from_slice(&[0, 0, 0, 255]);
+ }
+ }
+ }
+ Bitmap { width, height, bgra }
+}
+
+fn create_png(width: u32, height: u32, bgra: &[u8]) -> Vec<u8> {
+ let mut out = Vec::new();
+ out.extend_from_slice(b"\x89PNG\r\n\x1a\n");
+ let mut ihdr = Vec::new();
+ ihdr.extend_from_slice(&width.to_be_bytes());
+ ihdr.extend_from_slice(&height.to_be_bytes());
+ ihdr.push(8);
+ ihdr.push(6); // RGBA
+ ihdr.push(0);
+ ihdr.push(0);
+ ihdr.push(0);
+ write_chunk(&mut out, b"IHDR", &ihdr);
+
+ let mut raw = Vec::with_capacity((height * (width * 4 + 1)) as usize);
+ for y in 0..height {
+ raw.push(0);
+ let row_start = (y * width * 4) as usize;
+ let row_end = row_start + (width * 4) as usize;
+ if row_end <= bgra.len() {
+ for pixel in bgra[row_start..row_end].as_chunks::<4>().0 {
+ raw.push(pixel[2]); // R
+ raw.push(pixel[1]); // G
+ raw.push(pixel[0]); // B
+ raw.push(pixel[3]); // A
+ }
+ }
+ }
+
+ let mut zlib = Vec::new();
+ zlib.push(0x78);
+ zlib.push(0x01);
+
+ for (i, chunk) in raw.chunks(65535).enumerate() {
+ let is_last = i + 1 == raw.chunks(65535).len();
+ zlib.push(if is_last { 0x01 } else { 0x00 });
+ let len = chunk.len() as u16;
+ let nlen = !len;
+ zlib.extend_from_slice(&len.to_le_bytes());
+ zlib.extend_from_slice(&nlen.to_le_bytes());
+ zlib.extend_from_slice(chunk);
+ }
+ let mut s1: u32 = 1;
+ let mut s2: u32 = 0;
+ for &b in &raw {
+ s1 = (s1 + b as u32) % 65521;
+ s2 = (s2 + s1) % 65521;
+ }
+ let adler = (s2 << 16) | s1;
+ zlib.extend_from_slice(&adler.to_be_bytes());
+
+ write_chunk(&mut out, b"IDAT", &zlib);
+ write_chunk(&mut out, b"IEND", &[]);
+ out
+}
+
+fn write_chunk(out: &mut Vec<u8>, tag: &[u8; 4], data: &[u8]) {
+ out.extend_from_slice(&(data.len() as u32).to_be_bytes());
+ out.extend_from_slice(tag);
+ out.extend_from_slice(data);
+ let mut crc = 0xffff_ffff_u32;
+ for &b in tag.iter().chain(data.iter()) {
+ crc ^= b as u32;
+ for _ in 0..8 {
+ if crc & 1 != 0 {
+ crc = (crc >> 1) ^ 0xedb8_8320;
+ } else {
+ crc >>= 1;
+ }
+ }
+ }
+ out.extend_from_slice(&(crc ^ 0xffff_ffff_u32).to_be_bytes());
+}
diff --git a/desktop/app/src/mac/input.rs b/desktop/app/src/mac/input.rs
new file mode 100644
index 0000000..24263bd
--- /dev/null
+++ b/desktop/app/src/mac/input.rs
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS synthetic input stubs.
+
+use nectarlink_core::{ButtonAction, KeyMod, MouseButton, SlideAction, TouchAction};
+
+pub fn move_relative(_dx: f32, _dy: f32) {}
+pub fn move_absolute(_x: f32, _y: f32) {}
+pub fn mirror_touch(_action: TouchAction, _x: f32, _y: f32) {}
+pub fn mouse_button(_button: MouseButton, _action: ButtonAction) {}
+pub fn release_held_buttons() {}
+pub fn scroll(_dx: f32, _dy: f32) {}
+pub fn type_text(_text: &str) {}
+pub fn press_key(_key: &str, _mods: &[KeyMod]) {}
+pub fn slide(_action: SlideAction) {}
+pub fn is_user_active_within_ms(_max_idle_ms: u32) -> bool {
+ true
+}
diff --git a/desktop/app/src/mac/jumplist.rs b/desktop/app/src/mac/jumplist.rs
new file mode 100644
index 0000000..0cf6f2c
--- /dev/null
+++ b/desktop/app/src/mac/jumplist.rs
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS task argument stubs.
+
+use std::path::Path;
+
+pub const ARG: &str = "--task";
+
+pub fn register(_data_dir: Option<&Path>) {}
+
+pub fn unregister() {}
diff --git a/desktop/app/src/mac/media_sessions.rs b/desktop/app/src/mac/media_sessions.rs
new file mode 100644
index 0000000..65fad71
--- /dev/null
+++ b/desktop/app/src/mac/media_sessions.rs
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS media session integration stubs.
+
+use nectarlink_core::{MediaAction, MediaError, MediaPlayer};
+
+pub fn start(_on_change: impl Fn(Vec<MediaPlayer>) + Send + Sync + 'static) {}
+
+pub fn command(_player: &str, _action: MediaAction, _pos: Option<u64>) -> Result<(), MediaError> {
+ Ok(())
+}
+
+pub fn pause_for_call() {}
+
+pub fn resume_after_call() {}
+
+pub fn says_video(_id: &str) -> bool {
+ false
+}
diff --git a/desktop/app/src/mac/mod.rs b/desktop/app/src/mac/mod.rs
new file mode 100644
index 0000000..d240b62
--- /dev/null
+++ b/desktop/app/src/mac/mod.rs
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! 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;
+pub mod ble_beacon;
+pub mod browser;
+pub mod bt_hfp;
+pub mod clipboard;
+pub mod doctor;
+pub mod elevated;
+pub mod h264;
+pub mod http;
+pub mod image;
+pub mod input;
+pub mod jumplist;
+pub mod media_sessions;
+pub mod mp4;
+pub mod net;
+pub mod share_target;
+pub mod shell;
+pub mod shortcut;
+pub mod single_instance;
+pub mod smtc;
+pub mod sound;
+pub mod toast;
+pub mod tray;
+pub mod vcam;
+pub mod wallpaper;
+pub mod widget;
+pub mod window_capture;
+pub mod wol;
+
+/// Machine GUID on macOS: derived from IOPlatformSerialNumber.
+pub fn machine_guid() -> Option<String> {
+ let output =
+ std::process::Command::new("ioreg").args(["-rd1", "-c", "IOPlatformExpertDevice"]).output().ok()?;
+ let text = String::from_utf8_lossy(&output.stdout);
+ for line in text.lines() {
+ if line.contains("IOPlatformSerialNumber")
+ && let Some(pos) = line.find('=')
+ {
+ let val = line[pos + 1..].trim().trim_matches('"');
+ if !val.is_empty() {
+ return Some(val.to_string());
+ }
+ }
+ }
+ None
+}
+
+/// The macOS version as "<major>.<minor>.<patch>".
+pub fn os_version() -> String {
+ let output = std::process::Command::new("sw_vers").arg("-productVersion").output().ok();
+ if let Some(out) = output {
+ let ver = String::from_utf8_lossy(&out.stdout).trim().to_string();
+ if !ver.is_empty() {
+ return ver;
+ }
+ }
+ "15.0.0".to_string()
+}
+
+/// Whether this Mac runs on a battery (MacBook).
+pub fn is_laptop() -> bool {
+ let output = std::process::Command::new("pmset").arg("-g").arg("batt").output().ok();
+ if let Some(out) = output {
+ let text = String::from_utf8_lossy(&out.stdout);
+ text.contains("InternalBattery")
+ } else {
+ false
+ }
+}
+
+/// Whether Low Power Mode is on.
+pub fn power_saver() -> bool {
+ let output = std::process::Command::new("pmset").arg("-g").output().ok();
+ if let Some(out) = output {
+ let text = String::from_utf8_lossy(&out.stdout);
+ for line in text.lines() {
+ if line.contains("lowpowermode") {
+ return line.contains('1');
+ }
+ }
+ }
+ false
+}
+
+/// Whether macOS is set to dark mode.
+pub fn system_dark() -> bool {
+ let output =
+ std::process::Command::new("defaults").args(["read", "-g", "AppleInterfaceStyle"]).output().ok();
+ if let Some(out) = output { String::from_utf8_lossy(&out.stdout).trim() == "Dark" } else { false }
+}
+
+/// Whether Reduce Motion is enabled.
+pub fn reduce_motion() -> bool {
+ let output = std::process::Command::new("defaults")
+ .args(["read", "com.apple.universalaccess", "reduceMotion"])
+ .output()
+ .ok();
+ if let Some(out) = output { String::from_utf8_lossy(&out.stdout).trim() == "1" } else { false }
+}
+
+/// Primary display work area in physical pixels.
+pub fn work_area() -> Option<(i32, i32, i32, i32)> {
+ None
+}
+
+/// Fills `buf` from cryptographic randomness.
+pub fn secure_random(buf: &mut [u8]) -> bool {
+ use std::io::Read;
+ if let Ok(mut f) = std::fs::File::open("/dev/urandom") { f.read_exact(buf).is_ok() } else { false }
+}
+
+/// On macOS, COM is not used. Runs `f` directly.
+pub fn with_com<T>(f: impl FnOnce() -> T) -> T {
+ f()
+}
+
+pub(crate) fn reg_string(_root: u32, _key: &str, _value: &str) -> Option<String> {
+ None
+}
diff --git a/desktop/app/src/mac/mp4.rs b/desktop/app/src/mac/mp4.rs
new file mode 100644
index 0000000..7db909e
--- /dev/null
+++ b/desktop/app/src/mac/mp4.rs
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS MP4 recording stubs.
+
+use std::{
+ path::PathBuf,
+ time::{Instant, SystemTime, UNIX_EPOCH},
+};
+
+pub fn local_timestamp_filename(prefix: &str, ext: &str) -> String {
+ let now = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs());
+ format!("{prefix} {now}.{ext}")
+}
+
+pub struct MirrorRecorder {
+ path: PathBuf,
+ started_at: Instant,
+ started_epoch_ms: i64,
+}
+
+impl std::fmt::Debug for MirrorRecorder {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("MirrorRecorder").field("path", &self.path).finish_non_exhaustive()
+ }
+}
+
+impl MirrorRecorder {
+ pub fn new(
+ path: PathBuf,
+ _width: u32,
+ _height: u32,
+ _fps: u32,
+ _audio_cfg: Option<(u32, u8)>,
+ ) -> MirrorRecorder {
+ let started_epoch_ms =
+ SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64);
+ MirrorRecorder { path, started_at: Instant::now(), started_epoch_ms }
+ }
+
+ pub fn started_at(&self) -> Instant {
+ self.started_at
+ }
+
+ pub fn started_epoch_ms(&self) -> i64 {
+ self.started_epoch_ms
+ }
+
+ pub fn set_sps_pps(&mut self, _sps_pps: &[u8]) {}
+
+ pub fn on_config(&mut self, _width: u32, _height: u32) {}
+
+ pub fn on_audio_config(&mut self, _rate: u32, _channels: u8) {}
+
+ pub fn on_packet(&mut self, _keyframe: bool, _time_us: u64, _data: &[u8]) -> Result<(), String> {
+ Ok(())
+ }
+
+ pub fn on_audio(&mut self, _time_us: u64, _pcm: &[u8]) -> Result<(), String> {
+ Ok(())
+ }
+
+ pub fn finish(self) -> Result<PathBuf, String> {
+ Ok(self.path)
+ }
+}
+
+pub fn merge_sps_pps(sps_pps: &mut Vec<u8>, data: &[u8]) {
+ sps_pps.extend_from_slice(data);
+}
diff --git a/desktop/app/src/mac/net.rs b/desktop/app/src/mac/net.rs
new file mode 100644
index 0000000..6fec10e
--- /dev/null
+++ b/desktop/app/src/mac/net.rs
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS network change notification stubs.
+
+pub fn watch(_callback: impl Fn() + Send + Sync + 'static) {}
+pub fn stop() {}
diff --git a/desktop/app/src/mac/share_target.rs b/desktop/app/src/mac/share_target.rs
new file mode 100644
index 0000000..7354393
--- /dev/null
+++ b/desktop/app/src/mac/share_target.rs
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS share target stubs.
+
+use std::path::{Path, PathBuf};
+
+pub const ARG: &str = "--share";
+
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct SharedPayload {
+ pub files: Vec<PathBuf>,
+ pub url: Option<String>,
+ pub text: Option<String>,
+}
+
+impl SharedPayload {
+ pub fn is_empty(&self) -> bool {
+ self.files.is_empty() && self.url.is_none() && self.text.is_none()
+ }
+}
+
+fn is_share_url(s: &str) -> bool {
+ let s = s.trim();
+ if s.is_empty() || s.len() > 4096 || s.chars().any(char::is_whitespace) {
+ return false;
+ }
+ let lower: String = s.chars().take(8).collect::<String>().to_ascii_lowercase();
+ lower.starts_with("http://")
+ || lower.starts_with("https://")
+ || (lower.starts_with("geo:") && s.len() > 4)
+}
+
+fn looks_like_path(s: &str) -> bool {
+ let bytes = s.as_bytes();
+ Path::new(s).exists()
+ || s.contains('\\')
+ || s.contains('/')
+ || (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
+}
+
+/// Classifies `--share <target…>` CLI arguments into files, a link, or text.
+pub fn parse_targets(targets: &[String]) -> SharedPayload {
+ let mut payload = SharedPayload::default();
+ let mut text_parts = Vec::new();
+ for raw in targets {
+ let trimmed = raw.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+ if payload.url.is_none() && is_share_url(trimmed) {
+ payload.url = Some(trimmed.to_owned());
+ } else if looks_like_path(trimmed) {
+ payload.files.push(PathBuf::from(trimmed));
+ } else {
+ text_parts.push(trimmed.to_owned());
+ }
+ }
+ if !text_parts.is_empty() {
+ payload.text = Some(text_parts.join(" "));
+ }
+ payload
+}
+
+pub fn take_activated_share(_data_dir: &Path) -> Option<SharedPayload> {
+ None
+}
diff --git a/desktop/app/src/mac/shell.rs b/desktop/app/src/mac/shell.rs
new file mode 100644
index 0000000..e79e127
--- /dev/null
+++ b/desktop/app/src/mac/shell.rs
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Opening links, maps, email, locking, and sleeping the Mac.
+
+use std::path::Path;
+
+/// Opens a link in the default browser using macOS `open`.
+pub fn open_url(url: &str) -> Result<(), String> {
+ std::process::Command::new("open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string())
+}
+
+/// Opens a `mailto:` link in the default mail client.
+pub fn open_mailto(email: &str) -> Result<(), String> {
+ let trimmed = email.trim();
+ if trimmed.is_empty() {
+ return Err("empty email address".into());
+ }
+ open_url(&format!("mailto:{trimmed}"))
+}
+
+/// Opens a street address in Apple Maps or web maps.
+pub fn open_maps(address: &str) -> Result<(), String> {
+ let trimmed = address.trim();
+ if trimmed.is_empty() {
+ return Err("empty address".into());
+ }
+ let url = format!("https://maps.apple.com/?q={}", urlencoding::encode(trimmed));
+ open_url(&url)
+}
+
+/// Returns `true` if `scheme` is recognized.
+pub fn is_url_scheme_registered(scheme: &str) -> bool {
+ matches!(scheme.trim(), "http" | "https" | "mailto" | "maps")
+}
+
+/// Starts a program with arguments via `open` or direct process spawn.
+pub fn run(program: &Path, arguments: &str) -> Result<(), String> {
+ let mut cmd = std::process::Command::new(program);
+ if !arguments.is_empty() {
+ cmd.args(arguments.split_whitespace());
+ }
+ cmd.spawn().map(|_| ()).map_err(|e| e.to_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())
+}
+
+/// Puts the Mac to sleep.
+pub fn sleep() -> Result<(), String> {
+ std::process::Command::new("pmset").arg("sleepnow").spawn().map(|_| ()).map_err(|e| e.to_string())
+}
+
+/// Launches an application bundle or executable.
+pub fn launch_app(path: &Path) -> Result<(), String> {
+ std::process::Command::new("open").arg(path).spawn().map(|_| ()).map_err(|e| e.to_string())
+}
+
+/// Runs a shell command.
+pub fn run_command(command: &str) -> Result<(), String> {
+ let trimmed = command.trim();
+ if trimmed.is_empty() {
+ return Err("empty command".into());
+ }
+ std::process::Command::new("/bin/sh")
+ .arg("-c")
+ .arg(trimmed)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| format!("failed to run command: {e}"))
+}
+
+mod urlencoding {
+ pub fn encode(s: &str) -> String {
+ let mut out = String::new();
+ for b in s.bytes() {
+ if b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.' || b == b'~' {
+ out.push(b as char);
+ } else {
+ out.push_str(&format!("%{:02X}", b));
+ }
+ }
+ out
+ }
+}
diff --git a/desktop/app/src/mac/shortcut.rs b/desktop/app/src/mac/shortcut.rs
new file mode 100644
index 0000000..a943b1e
--- /dev/null
+++ b/desktop/app/src/mac/shortcut.rs
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS desktop shortcut and send-to stubs.
+
+use std::path::{Path, PathBuf};
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Shortcut {
+ pub target: PathBuf,
+ pub arguments: String,
+ pub description: String,
+}
+
+pub fn send_to_dir() -> Option<PathBuf> {
+ None
+}
+
+pub fn recent_dir() -> Option<PathBuf> {
+ None
+}
+
+pub fn arguments(path: &Path) -> Option<String> {
+ let content = std::fs::read_to_string(path).ok()?;
+ let mut lines = content.lines();
+ let _target = lines.next()?;
+ let arguments = lines.next()?;
+ Some(arguments.to_string())
+}
+
+pub fn target(path: &Path) -> Option<PathBuf> {
+ let content = std::fs::read_to_string(path).ok()?;
+ let mut lines = content.lines();
+ let target = lines.next()?;
+ Some(PathBuf::from(target))
+}
+
+pub fn write(path: &Path, shortcut: &Shortcut) -> std::io::Result<()> {
+ std::fs::write(
+ path,
+ format!("{}\n{}\n{}\n", shortcut.target.display(), shortcut.arguments, shortcut.description),
+ )
+}
diff --git a/desktop/app/src/mac/single_instance.rs b/desktop/app/src/mac/single_instance.rs
new file mode 100644
index 0000000..88ff33f
--- /dev/null
+++ b/desktop/app/src/mac/single_instance.rs
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS single-instance lock and IPC using Unix domain sockets.
+
+use std::{
+ io::{Read, Write},
+ os::unix::net::{UnixListener, UnixStream},
+ path::{Path, PathBuf},
+ sync::Mutex,
+};
+
+#[derive(Debug)]
+pub struct PrimaryInstance {
+ listener: Mutex<Option<UnixListener>>,
+ sock_path: PathBuf,
+}
+
+#[derive(Debug)]
+pub enum Instance {
+ Primary(PrimaryInstance),
+ Secondary,
+}
+
+pub fn acquire(data_dir: &Path) -> Result<Instance, String> {
+ let _ = std::fs::create_dir_all(data_dir);
+ let sock_path = data_dir.join("nectarlink.sock");
+
+ match UnixListener::bind(&sock_path) {
+ Ok(listener) => {
+ Ok(Instance::Primary(PrimaryInstance { listener: Mutex::new(Some(listener)), sock_path }))
+ }
+ Err(_) => {
+ // Check if another instance is actively responding
+ if UnixStream::connect(&sock_path).is_ok() {
+ return Ok(Instance::Secondary);
+ }
+ // Stale socket from previous crash or exit
+ let _ = std::fs::remove_file(&sock_path);
+ match UnixListener::bind(&sock_path) {
+ Ok(listener) => {
+ Ok(Instance::Primary(PrimaryInstance { listener: Mutex::new(Some(listener)), sock_path }))
+ }
+ Err(e) => Err(format!("can't bind single-instance socket: {e}")),
+ }
+ }
+ }
+}
+
+pub fn wake(data_dir: &Path) {
+ let sock_path = data_dir.join("nectarlink.sock");
+ if let Ok(mut stream) = UnixStream::connect(&sock_path) {
+ let _ = stream.write_all(b"wake\n");
+ }
+}
+
+impl PrimaryInstance {
+ pub fn watch(&'static self, on_activate: impl Fn() + Send + 'static) {
+ let listener = match self.listener.lock() {
+ Ok(mut guard) => guard.take(),
+ Err(_) => None,
+ };
+ let Some(listener) = listener else {
+ return;
+ };
+
+ std::thread::Builder::new()
+ .name("single-instance".into())
+ .spawn(move || {
+ for mut s in listener.incoming().flatten() {
+ let mut buf = [0u8; 16];
+ let _ = s.read(&mut buf);
+ on_activate();
+ }
+ })
+ .ok();
+ }
+}
+
+impl Drop for PrimaryInstance {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.sock_path);
+ }
+}
diff --git a/desktop/app/src/mac/smtc.rs b/desktop/app/src/mac/smtc.rs
new file mode 100644
index 0000000..155542d
--- /dev/null
+++ b/desktop/app/src/mac/smtc.rs
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS system media transport controls stubs.
+
+use crate::state::PlayerView;
+use nectarlink_core::{DeviceId, MediaAction};
+
+#[derive(Debug, Clone)]
+pub struct Shown {
+ pub device: DeviceId,
+ pub device_name: String,
+ pub view: PlayerView,
+}
+
+pub fn start(_on_command: impl Fn(DeviceId, String, MediaAction, Option<u64>) + Send + Sync + 'static) {}
+pub fn show(_shown: Option<Shown>) {}
+pub fn clear() {}
diff --git a/desktop/app/src/mac/sound.rs b/desktop/app/src/mac/sound.rs
new file mode 100644
index 0000000..7817838
--- /dev/null
+++ b/desktop/app/src/mac/sound.rs
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS sound ringing ("find my PC" from phone).
+
+use std::{
+ sync::atomic::{AtomicU64, Ordering},
+ time::Duration,
+};
+
+const MAX_RING: Duration = Duration::from_secs(60);
+static GENERATION: AtomicU64 = AtomicU64::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();
+ std::thread::sleep(Duration::from_millis(600));
+ }
+ });
+}
+
+pub fn stop_ringing() {
+ GENERATION.fetch_add(1, Ordering::SeqCst);
+ let _ = std::process::Command::new("killall").arg("afplay").output();
+}
diff --git a/desktop/app/src/mac/toast.rs b/desktop/app/src/mac/toast.rs
new file mode 100644
index 0000000..d1de2a6
--- /dev/null
+++ b/desktop/app/src/mac/toast.rs
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS notifications via AppleScript.
+
+use std::{
+ path::PathBuf,
+ sync::{Mutex, OnceLock},
+};
+
+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";
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ToastEvent {
+ Opened { device: String, key: String },
+ Action { device: String, key: String, action: String },
+ Reply { device: String, key: String, action: String, text: String },
+ Dismissed { device: String, key: String },
+}
+
+#[derive(Clone)]
+pub struct Toast {
+ pub device: String,
+ pub key: String,
+ pub title: String,
+ pub body: String,
+ pub attribution: String,
+ pub icon: Option<PathBuf>,
+ pub image: Option<PathBuf>,
+ pub actions: Vec<(String, String)>,
+ pub reply: Option<(String, String)>,
+ pub silent: bool,
+ pub progress: Option<Progress>,
+ pub call: bool,
+}
+
+impl std::fmt::Debug for Toast {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Toast").field("device", &self.device).finish_non_exhaustive()
+ }
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Progress {
+ pub status: String,
+ pub value: Option<f64>,
+ pub label: String,
+}
+
+type OnEvent = Box<dyn Fn(ToastEvent) + Send + Sync>;
+static ON_EVENT: OnceLock<Mutex<Option<OnEvent>>> = OnceLock::new();
+
+pub fn enabled() -> bool {
+ true
+}
+
+pub fn set_process_id() {}
+
+pub fn unregister() {}
+
+pub fn start(_icon: PathBuf, on_event: impl Fn(ToastEvent) + Send + Sync + 'static) {
+ let _ = ON_EVENT.set(Mutex::new(Some(Box::new(on_event))));
+}
+
+pub fn show(toast: Toast) {
+ let script = if toast.attribution.is_empty() {
+ format!("display notification {:?} with title {:?}", toast.body, toast.title)
+ } else {
+ format!(
+ "display notification {:?} with title {:?} subtitle {:?}",
+ toast.body, toast.title, toast.attribution
+ )
+ };
+ let _ = std::process::Command::new("osascript").args(["-e", &script]).spawn();
+}
+
+pub fn update_progress(_device: &str, _key: &str, _progress: Progress) {}
+
+pub fn remove(_device: &str, _key: &str) {}
+
+pub fn remove_device(_device: &str) {}
diff --git a/desktop/app/src/mac/tray.rs b/desktop/app/src/mac/tray.rs
new file mode 100644
index 0000000..51c3d98
--- /dev/null
+++ b/desktop/app/src/mac/tray.rs
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS status bar / tray integration stubs.
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TrayEvent {
+ Open,
+ CommandPalette,
+ Shelf,
+ TakePhoto,
+ ScanDocument,
+ FindPhone,
+ OpenLinkOnPhone,
+ Quit,
+ Resumed,
+ AppearanceChanged,
+}
+
+#[derive(Debug, Clone)]
+pub struct MenuLabels {
+ pub open: String,
+ pub command_palette: String,
+ pub shelf: String,
+ pub take_photo: String,
+ pub scan_document: String,
+ pub find_phone: String,
+ pub open_link: String,
+ pub quit: String,
+}
+
+pub struct Tray;
+
+impl Tray {
+ pub fn create(
+ _tooltip: &str,
+ _labels: MenuLabels,
+ _handler: impl Fn(TrayEvent) + 'static,
+ ) -> Result<Tray, String> {
+ Ok(Tray)
+ }
+
+ pub fn set_tooltip(&self, _text: &str) {}
+
+ pub fn set_find_phone_enabled(&self, _enabled: bool) {}
+}
+
+pub fn update_hotkeys(_photo_spec: &str, _scan_spec: &str, _palette_spec: &str, _shelf_spec: &str) {}
+
+pub fn record_foreground_window() {}
+
+pub fn apply_no_activate_style_by_title(_title: &str) {}
+
+pub fn focus_window(_hwnd: isize) -> bool {
+ true
+}
+
+pub fn is_window_alive_and_visible(_hwnd: isize) -> bool {
+ false
+}
+
+pub fn snapshot_target_window() -> Option<(isize, String)> {
+ None
+}
+
+pub fn send_paste_fallback_if_not_foreground(_hwnd: isize) {}
+
+pub fn parse_hotkey(_spec: &str) -> Option<(u32, u32)> {
+ None
+}
diff --git a/desktop/app/src/mac/vcam.rs b/desktop/app/src/mac/vcam.rs
new file mode 100644
index 0000000..52cd27a
--- /dev/null
+++ b/desktop/app/src/mac/vcam.rs
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS virtual camera stubs.
+
+pub const REGISTER_ARG: &str = "--register-vcam";
+pub const UNREGISTER_ARG: &str = "--unregister-vcam";
+
+pub fn is_registered() -> bool {
+ false
+}
+
+pub fn register_hklm() -> Result<(), String> {
+ Ok(())
+}
+
+pub fn unregister_hklm() -> Result<(), String> {
+ Ok(())
+}
+
+pub fn run_elevated(_arg: &'static str, on_done: impl FnOnce(bool) + Send + 'static) {
+ on_done(false);
+}
+
+#[derive(Debug, Default)]
+pub struct VirtualCameraHandle;
+
+impl VirtualCameraHandle {
+ pub fn start() -> Result<Self, String> {
+ Err("virtual camera is not supported on macOS".into())
+ }
+}
diff --git a/desktop/app/src/mac/wallpaper.rs b/desktop/app/src/mac/wallpaper.rs
new file mode 100644
index 0000000..54630a9
--- /dev/null
+++ b/desktop/app/src/mac/wallpaper.rs
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS wallpaper color accent seed and artwork palette extraction.
+
+use material_colors::color::Rgb;
+use std::path::Path;
+
+pub fn seed() -> Option<Rgb> {
+ Some(Rgb::new(245, 166, 35))
+}
+
+pub fn artwork_scheme_from_path(_path: &Path) -> Option<String> {
+ None
+}
diff --git a/desktop/app/src/mac/widget.rs b/desktop/app/src/mac/widget.rs
new file mode 100644
index 0000000..a49b98d
--- /dev/null
+++ b/desktop/app/src/mac/widget.rs
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS widget stubs.
+
+use std::{path::Path, process::ExitCode};
+
+pub const ARG: &str = "--widget-provider";
+
+pub fn write_state_snapshot(_dir: &Path) {}
+
+pub fn run_provider(_data_dir: &Path) -> ExitCode {
+ ExitCode::SUCCESS
+}
diff --git a/desktop/app/src/mac/window_capture.rs b/desktop/app/src/mac/window_capture.rs
new file mode 100644
index 0000000..fe0e6a5
--- /dev/null
+++ b/desktop/app/src/mac/window_capture.rs
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS window capture stubs.
+
+#[derive(Debug)]
+pub struct WindowCapture;
+
+impl WindowCapture {
+ pub fn new(_window: &super::browser::Window) -> Option<Self> {
+ None
+ }
+ pub fn capture_frame(&mut self) -> Option<Vec<u8>> {
+ None
+ }
+}
diff --git a/desktop/app/src/mac/wol.rs b/desktop/app/src/mac/wol.rs
new file mode 100644
index 0000000..408b2b6
--- /dev/null
+++ b/desktop/app/src/mac/wol.rs
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS Wake-on-LAN integration stubs.
+
+use nectarlink_core::PcWakeInfo;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WakeSupport {
+ Enabled,
+ Disabled,
+ Unknown,
+}
+
+impl WakeSupport {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ WakeSupport::Enabled => "enabled",
+ WakeSupport::Disabled => "disabled",
+ WakeSupport::Unknown => "unknown",
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct WakeAdapter {
+ pub label: String,
+ pub wired: bool,
+ pub mac: String,
+ pub broadcasts: Vec<String>,
+ pub support: WakeSupport,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub struct WakeStatus {
+ pub info: PcWakeInfo,
+ pub adapters: Vec<WakeAdapter>,
+}
+
+impl WakeStatus {
+ pub fn primary(&self) -> Option<&WakeAdapter> {
+ self.adapters.first()
+ }
+
+ pub fn state_str(&self) -> &'static str {
+ match self.primary() {
+ Some(a) => a.support.as_str(),
+ None => "none",
+ }
+ }
+}
+
+pub fn query_wake_status() -> WakeStatus {
+ WakeStatus::default()
+}
+
+pub fn wake(_mac: &[u8]) -> Result<(), String> {
+ Ok(())
+}
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 29971f0..1ed17c9 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -56,8 +56,15 @@ mod storage;
mod transfers;
mod updater;
mod webcam;
+#[cfg(windows)]
mod win;
+#[cfg(target_os = "macos")]
+mod mac;
+
+#[cfg(target_os = "macos")]
+use mac as win;
+
use std::{
path::{Path, PathBuf},
process::ExitCode,
diff --git a/desktop/app/src/mirror.rs b/desktop/app/src/mirror.rs
index c299199..16ba27d 100644
--- a/desktop/app/src/mirror.rs
+++ b/desktop/app/src/mirror.rs
@@ -1455,6 +1455,7 @@ pub fn normalize_gamepad_state(raw: GamepadState) -> GamepadState {
}
}
+#[cfg(windows)]
#[allow(unsafe_code)]
fn poll_xinput_gamepad() -> Option<GamepadState> {
use windows::Win32::UI::Input::XboxController::{XINPUT_STATE, XInputGetState};
@@ -1477,6 +1478,7 @@ fn poll_xinput_gamepad() -> Option<GamepadState> {
None
}
+#[cfg(windows)]
fn poll_winrt_gamepad() -> Option<GamepadState> {
use windows::Gaming::Input::{Gamepad, GamepadButtons};
let gamepads = Gamepad::Gamepads().ok()?;
@@ -1542,10 +1544,16 @@ fn poll_winrt_gamepad() -> Option<GamepadState> {
}))
}
+#[cfg(windows)]
fn poll_gamepad() -> Option<GamepadState> {
poll_xinput_gamepad().or_else(poll_winrt_gamepad)
}
+#[cfg(not(windows))]
+fn poll_gamepad() -> Option<GamepadState> {
+ None
+}
+
fn ensure_gamepad_loop() {
static RUNNING: AtomicBool = AtomicBool::new(false);
if RUNNING.swap(true, Ordering::AcqRel) {
diff --git a/desktop/app/src/pc_audio_stream/mod.rs b/desktop/app/src/pc_audio_stream/mod.rs
new file mode 100644
index 0000000..8a28451
--- /dev/null
+++ b/desktop/app/src/pc_audio_stream/mod.rs
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Streaming PC loopback audio to the phone.
+
+#[cfg(windows)]
+mod windows;
+#[cfg(windows)]
+pub use self::windows::*;
+
+#[cfg(not(windows))]
+mod non_windows;
+#[cfg(not(windows))]
+pub use self::non_windows::*;
diff --git a/desktop/app/src/pc_audio_stream/non_windows.rs b/desktop/app/src/pc_audio_stream/non_windows.rs
new file mode 100644
index 0000000..211346e
--- /dev/null
+++ b/desktop/app/src/pc_audio_stream/non_windows.rs
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS / non-Windows PC audio stream stubs.
+
+pub fn target() -> Option<nectarlink_core::DeviceId> {
+ None
+}
+
+pub fn set_target(_phone: Option<nectarlink_core::DeviceId>) {}
+
+pub fn is_enabled() -> bool {
+ false
+}
+
+pub fn set_enabled(_enabled: bool) {}
+
+pub fn f32_stereo_to_i16le(_samples: &[f32]) -> Vec<u8> {
+ Vec::new()
+}
diff --git a/desktop/app/src/pc_audio_stream.rs b/desktop/app/src/pc_audio_stream/windows.rs
similarity index 100%
rename from desktop/app/src/pc_audio_stream.rs
rename to desktop/app/src/pc_audio_stream/windows.rs
diff --git a/desktop/app/src/pc_mirror/mod.rs b/desktop/app/src/pc_mirror/mod.rs
new file mode 100644
index 0000000..42019c7
--- /dev/null
+++ b/desktop/app/src/pc_mirror/mod.rs
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Reverse Mirroring: streaming PC display to phone.
+
+#[cfg(windows)]
+mod windows;
+#[cfg(windows)]
+pub use self::windows::*;
+
+#[cfg(not(windows))]
+mod non_windows;
+#[cfg(not(windows))]
+pub use self::non_windows::*;
diff --git a/desktop/app/src/pc_mirror/non_windows.rs b/desktop/app/src/pc_mirror/non_windows.rs
new file mode 100644
index 0000000..d660856
--- /dev/null
+++ b/desktop/app/src/pc_mirror/non_windows.rs
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS / non-Windows reverse mirroring stubs.
+
+use nectarlink_core::{DeviceId, MirrorInput, MirrorStart, NodeEvent};
+
+pub fn active_peer() -> Option<DeviceId> {
+ None
+}
+
+pub fn is_active() -> bool {
+ false
+}
+
+pub fn is_watching() -> bool {
+ false
+}
+
+pub fn stop_watching() {}
+
+pub fn start(_peer: DeviceId, _options: MirrorStart) {}
+
+pub fn stop_for(_peer: &DeviceId) {}
+
+pub fn stop_all() {}
+
+pub fn request_keyframe(_peer: &DeviceId) {}
+
+pub fn handle_input(_peer: &DeviceId, _session: u32, _input: MirrorInput) {}
+
+pub fn on_event(_event: &NodeEvent) {}
+
+pub fn set_mute_while_watched(_on: bool) {}
diff --git a/desktop/app/src/pc_mirror.rs b/desktop/app/src/pc_mirror/windows.rs
similarity index 100%
rename from desktop/app/src/pc_mirror.rs
rename to desktop/app/src/pc_mirror/windows.rs
diff --git a/desktop/app/src/play_on_phone/mod.rs b/desktop/app/src/play_on_phone/mod.rs
new file mode 100644
index 0000000..1eba1bd
--- /dev/null
+++ b/desktop/app/src/play_on_phone/mod.rs
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Play media on phone and window tracking.
+
+#[cfg(windows)]
+mod windows;
+#[cfg(windows)]
+pub use self::windows::*;
+
+#[cfg(not(windows))]
+mod non_windows;
+#[cfg(not(windows))]
+pub use self::non_windows::*;
diff --git a/desktop/app/src/play_on_phone/non_windows.rs b/desktop/app/src/play_on_phone/non_windows.rs
new file mode 100644
index 0000000..4d7d918
--- /dev/null
+++ b/desktop/app/src/play_on_phone/non_windows.rs
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS / non-Windows Play on Phone stubs.
+
+use nectarlink_core::DeviceId;
+
+pub fn phone() -> Option<(DeviceId, String)> {
+ None
+}
+
+pub fn watchable() -> Option<String> {
+ None
+}
+
+pub fn state() -> &'static str {
+ "idle"
+}
+
+pub fn set_on(_on: bool) {}
+
+pub fn play(_player: String) {}
+
+pub struct Watched;
+
+#[derive(Debug, Clone, Copy)]
+pub struct Place {
+ pub window: isize,
+}
+
+impl Watched {
+ pub fn follow(_player: &str) -> Watched {
+ Watched
+ }
+
+ pub fn place(&self) -> Option<Place> {
+ None
+ }
+}
diff --git a/desktop/app/src/play_on_phone.rs b/desktop/app/src/play_on_phone/windows.rs
similarity index 100%
rename from desktop/app/src/play_on_phone.rs
rename to desktop/app/src/play_on_phone/windows.rs
diff --git a/desktop/app/src/recordings.rs b/desktop/app/src/recordings.rs
index a6d7f71..ea1f97d 100644
--- a/desktop/app/src/recordings.rs
+++ b/desktop/app/src/recordings.rs
@@ -15,6 +15,7 @@ use std::{
};
use nectarlink_core::{RecordingMarker, Transfer, TransferState};
+#[cfg(windows)]
use windows::{
Win32::{
Media::MediaFoundation::{
@@ -31,14 +32,13 @@ use windows::{
core::{HSTRING, Interface},
};
+#[cfg(windows)]
+use crate::win::h264::ensure_mf_started;
use crate::{
core_host,
settings::{RecordingFormat, Settings},
transfers::{ACTION_OPEN, ACTION_SHOW, TOAST_GROUP},
- win::{
- h264::ensure_mf_started,
- toast::{self, Toast},
- },
+ win::toast::{self, Toast},
};
#[derive(Debug, Default)]
@@ -109,12 +109,48 @@ pub fn format_recording_stem(year: u16, month: u16, day: u16, hour: u16, minute:
}
/// Base name for a recording saved right now, in local time.
+#[cfg(windows)]
pub fn current_recording_stem() -> String {
// SAFETY: GetLocalTime always succeeds and writes a SYSTEMTIME struct.
let st = unsafe { GetLocalTime() };
format_recording_stem(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute)
}
+#[cfg(not(windows))]
+pub fn current_recording_stem() -> String {
+ #[repr(C)]
+ struct Tm {
+ tm_sec: i32,
+ tm_min: i32,
+ tm_hour: i32,
+ tm_mday: i32,
+ tm_mon: i32,
+ tm_year: i32,
+ tm_wday: i32,
+ tm_yday: i32,
+ tm_isdst: i32,
+ tm_gmtoff: i64,
+ tm_zone: *const std::ffi::c_char,
+ }
+ unsafe extern "C" {
+ fn time(tloc: *mut i64) -> i64;
+ fn localtime_r(timep: *const i64, result: *mut Tm) -> *mut Tm;
+ }
+ unsafe {
+ let mut t: i64 = 0;
+ time(&mut t);
+ let mut tm = std::mem::zeroed::<Tm>();
+ localtime_r(&t, &mut tm);
+ format_recording_stem(
+ (tm.tm_year + 1900) as u16,
+ (tm.tm_mon + 1) as u16,
+ tm.tm_mday as u16,
+ tm.tm_hour as u16,
+ tm.tm_min as u16,
+ )
+ }
+}
+
/// The name the phone gave a recording (`Recording 2026-10-07 14.32`, from
/// when it started), so one that waited for the PC keeps its own time.
/// `None` for anything else.
@@ -246,6 +282,12 @@ fn move_file(src: &Path, dest: &Path) -> std::io::Result<()> {
Ok(())
}
+#[cfg(not(windows))]
+pub fn convert_audio(_src: &Path, _dest: &Path, _format: RecordingFormat) -> Result<(), String> {
+ Err("audio conversion via Media Foundation is only supported on Windows".into())
+}
+
+#[cfg(windows)]
/// Converts `src` (`.m4a`) to `dest` in `format` (`Mp3`, `Wav`, or `Flac`)
/// using Windows Media Foundation.
pub fn convert_audio(src: &Path, dest: &Path, format: RecordingFormat) -> windows::core::Result<()> {
@@ -285,6 +327,7 @@ pub fn convert_audio(src: &Path, dest: &Path, format: RecordingFormat) -> window
}
}
+#[cfg(windows)]
unsafe fn write_decoded_wav(
reader: &IMFSourceReader,
stream_idx: u32,
@@ -340,6 +383,7 @@ unsafe fn write_decoded_wav(
fs::write(dest, wav).map_err(|_| windows::core::Error::from_thread())
}
+#[cfg(windows)]
unsafe fn transcode_with_sink_writer(
reader: &IMFSourceReader,
stream_idx: u32,
@@ -390,6 +434,7 @@ unsafe fn transcode_with_sink_writer(
Ok(())
}
+#[cfg(windows)]
unsafe fn choose_encoder_output_type(
subtype: &windows::core::GUID,
sample_rate: u32,
@@ -762,6 +807,7 @@ mod tests {
assert_eq!(text, "00:01.250 Intro\n01:05.000 Marker 2\n01:01:01.005 Wrap-up\n");
}
+ #[cfg(windows)]
#[test]
fn media_foundation_converts_m4a_to_m4a_mp3_wav_and_flac_with_markers() {
let dir = tempfile::tempdir().unwrap();
diff --git a/desktop/app/src/setup.rs b/desktop/app/src/setup.rs
index ec9b2b9..e1f49b2 100644
--- a/desktop/app/src/setup.rs
+++ b/desktop/app/src/setup.rs
@@ -20,8 +20,9 @@
//! `nectarlink-desktop.exe` by name, which would otherwise include these.
use crate::i18n::tr;
+#[cfg(windows)]
+use std::os::windows::process::CommandExt;
use std::{
- os::windows::process::CommandExt,
path::{Path, PathBuf},
time::{Duration, Instant},
};
@@ -58,12 +59,19 @@ pub struct Installed {
}
pub fn installed() -> Option<Installed> {
- use windows::Win32::System::Registry::HKEY_LOCAL_MACHINE;
- let dir = crate::win::reg_string(HKEY_LOCAL_MACHINE, UNINSTALL_KEY, "InstallLocation")?;
- let version =
- crate::win::reg_string(HKEY_LOCAL_MACHINE, UNINSTALL_KEY, "DisplayVersion").unwrap_or_default();
- let dir = PathBuf::from(dir);
- dir.join(APP_EXE).is_file().then_some(Installed { dir, version })
+ #[cfg(windows)]
+ {
+ use windows::Win32::System::Registry::HKEY_LOCAL_MACHINE;
+ let dir = crate::win::reg_string(HKEY_LOCAL_MACHINE, UNINSTALL_KEY, "InstallLocation")?;
+ let version =
+ crate::win::reg_string(HKEY_LOCAL_MACHINE, UNINSTALL_KEY, "DisplayVersion").unwrap_or_default();
+ let dir = PathBuf::from(dir);
+ dir.join(APP_EXE).is_file().then_some(Installed { dir, version })
+ }
+ #[cfg(not(windows))]
+ {
+ None
+ }
}
/// How this install relates to the copy already on the PC.
@@ -288,12 +296,19 @@ pub fn open_app(dir: &Path) -> Result<(), String> {
if !app.is_file() {
return Err(format!("{} is missing", app.display()));
}
- std::process::Command::new("explorer.exe")
- .arg(&app)
- .creation_flags(DETACHED_PROCESS)
- .spawn()
- .map(|_| ())
- .map_err(|e| e.to_string())
+ #[cfg(windows)]
+ {
+ std::process::Command::new("explorer.exe")
+ .arg(&app)
+ .creation_flags(DETACHED_PROCESS)
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+ }
+ #[cfg(not(windows))]
+ {
+ std::process::Command::new("open").arg(&app).spawn().map(|_| ()).map_err(|e| e.to_string())
+ }
}
/// For `--remove` started from the installed folder: carries on from a copy
@@ -333,11 +348,18 @@ pub fn delete_own_copy_later() {
if !ours {
return;
}
- let script = format!("/c ping -n 4 127.0.0.1 >nul & rmdir /s /q \"{}\"", dir.display());
- let _ = std::process::Command::new("cmd.exe")
- .raw_arg(script)
- .creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS)
- .spawn();
+ #[cfg(windows)]
+ {
+ let script = format!("/c ping -n 4 127.0.0.1 >nul & rmdir /s /q \"{}\"", dir.display());
+ let _ = std::process::Command::new("cmd.exe")
+ .raw_arg(script)
+ .creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS)
+ .spawn();
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = std::fs::remove_dir_all(dir);
+ }
}
fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
diff --git a/desktop/app/src/storage/mod.rs b/desktop/app/src/storage/mod.rs
new file mode 100644
index 0000000..8ec9219
--- /dev/null
+++ b/desktop/app/src/storage/mod.rs
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Phone storage in File Explorer (Windows CloudFiles) and stubs for other platforms.
+
+#[cfg(windows)]
+mod windows;
+#[cfg(windows)]
+pub use self::windows::*;
+
+#[cfg(not(windows))]
+mod non_windows;
+#[cfg(not(windows))]
+pub use self::non_windows::*;
diff --git a/desktop/app/src/storage/non_windows.rs b/desktop/app/src/storage/non_windows.rs
new file mode 100644
index 0000000..d3900f4
--- /dev/null
+++ b/desktop/app/src/storage/non_windows.rs
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! macOS / non-Windows storage stubs.
+
+use nectarlink_core::{DeviceId, NodeEvent};
+use std::path::{Path, PathBuf};
+
+pub fn start() {}
+
+pub fn sync() {}
+
+pub fn on_event(_event: &NodeEvent) {}
+
+pub fn shutdown() {}
+
+pub fn unregister_all() {}
+
+pub fn sync_root_path_for(_device: DeviceId) -> Option<PathBuf> {
+ None
+}
+
+pub fn open_in_explorer(_device: DeviceId) -> Result<(), String> {
+ Err("phone storage exploration is not supported on this platform".into())
+}
+
+pub fn sanitize_folder_name(device_name: &str) -> String {
+ device_name.chars().filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '-' | '_')).collect()
+}
+
+pub fn unix_ms_to_filetime_ticks(unix_ms: i64) -> i64 {
+ unix_ms * 10_000 + 116_444_736_000_000_000
+}
+
+pub fn filetime_ticks_to_unix_ms(ticks: i64) -> i64 {
+ (ticks - 116_444_736_000_000_000) / 10_000
+}
+
+pub fn relative_path_under_root(root_path: &Path, full_path: &Path) -> Option<String> {
+ full_path.strip_prefix(root_path).ok().and_then(|p| p.to_str()).map(|s| s.replace('\\', "/"))
+}
diff --git a/desktop/app/src/storage.rs b/desktop/app/src/storage/windows.rs
similarity index 100%
rename from desktop/app/src/storage.rs
rename to desktop/app/src/storage/windows.rs
diff --git a/desktop/app/src/updater.rs b/desktop/app/src/updater.rs
index f85ca04..2f8b08c 100644
--- a/desktop/app/src/updater.rs
+++ b/desktop/app/src/updater.rs
@@ -25,8 +25,9 @@
//! update didn't go through.
use crate::i18n::tr;
+#[cfg(windows)]
+use std::os::windows::process::CommandExt;
use std::{
- os::windows::process::CommandExt,
path::{Path, PathBuf},
process::ExitCode,
sync::{
@@ -305,13 +306,20 @@ fn quiet() -> bool {
/// Whether the installer registered [`TASK`] on this PC.
fn task_registered() -> bool {
- std::process::Command::new("schtasks.exe")
- .args(["/Query", "/TN", TASK])
- .creation_flags(CREATE_NO_WINDOW)
- .stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .status()
- .is_ok_and(|s| s.success())
+ #[cfg(windows)]
+ {
+ std::process::Command::new("schtasks.exe")
+ .args(["/Query", "/TN", TASK])
+ .creation_flags(CREATE_NO_WINDOW)
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status()
+ .is_ok_and(|s| s.success())
+ }
+ #[cfg(not(windows))]
+ {
+ false
+ }
}
/// Installs the update found: downloads it (reporting `progress(done,
@@ -445,48 +453,64 @@ pub fn stage(update: &Update, progress: impl FnMut(u64, u64)) -> Result<PathBuf,
/// hidden relauncher opens the new version afterwards. `shown`: open its
/// window again (the user asked for the update) rather than start in the tray.
fn install_with_task(shown: bool) -> Result<(), String> {
- let update = available().ok_or("no update")?;
- let exe = std::env::current_exe().map_err(|e| e.to_string())?;
- spawn_relauncher(&exe, &update.version, shown)?;
- let started = std::process::Command::new("schtasks.exe")
- .args(["/Run", "/TN", TASK])
- .creation_flags(CREATE_NO_WINDOW)
- .stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .status()
- .map_err(|e| e.to_string())?;
- if !started.success() {
- return Err(format!("schtasks /Run: {started}"));
- }
- tracing::info!(version = update.version, "updating; quitting for the installer");
- crate::bridge::app::request_quit();
- Ok(())
+ #[cfg(windows)]
+ {
+ let update = available().ok_or("no update")?;
+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;
+ spawn_relauncher(&exe, &update.version, shown)?;
+ let started = std::process::Command::new("schtasks.exe")
+ .args(["/Run", "/TN", TASK])
+ .creation_flags(CREATE_NO_WINDOW)
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status()
+ .map_err(|e| e.to_string())?;
+ if !started.success() {
+ return Err(format!("schtasks /Run: {started}"));
+ }
+ tracing::info!(version = update.version, "updating; quitting for the installer");
+ crate::bridge::app::request_quit();
+ Ok(())
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = shown;
+ Err("scheduled update task is only supported on Windows".into())
+ }
}
/// A hidden PowerShell that waits (up to ten minutes) until `version` is
/// installed and the installer has finished, then opens the app again.
fn spawn_relauncher(exe: &Path, version: &str, shown: bool) -> Result<(), String> {
- // Both come from this program (its own path, and a version the release
- // check already parsed); checked again so they can't break out of the
- // script's quotes.
- let exe =
- exe.to_str().filter(|e| !e.contains('\'') && !e.contains('\n')).ok_or("unusual install path")?;
- if !version.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) {
- return Err("unusual version".into());
- }
- let arguments = if shown { UPDATED_ARG.to_owned() } else { format!("--minimized {UPDATED_ARG}") };
- let script = relauncher_script(exe, version, &arguments);
- let encoded: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
- std::process::Command::new("powershell.exe")
- .args(["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-EncodedCommand"])
- .arg(data_encoding::BASE64.encode(&encoded))
- .creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS)
- .stdin(std::process::Stdio::null())
- .stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .spawn()
- .map(|_| ())
- .map_err(|e| format!("relauncher: {e}"))
+ #[cfg(windows)]
+ {
+ // Both come from this program (its own path, and a version the release
+ // check already parsed); checked again so they can't break out of the
+ // script's quotes.
+ let exe =
+ exe.to_str().filter(|e| !e.contains('\'') && !e.contains('\n')).ok_or("unusual install path")?;
+ if !version.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) {
+ return Err("unusual version".into());
+ }
+ let arguments = if shown { UPDATED_ARG.to_owned() } else { format!("--minimized {UPDATED_ARG}") };
+ let script = relauncher_script(exe, version, &arguments);
+ let encoded: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
+ std::process::Command::new("powershell.exe")
+ .args(["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-EncodedCommand"])
+ .arg(data_encoding::BASE64.encode(&encoded))
+ .creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| format!("relauncher: {e}"))
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = (exe, version, shown);
+ Err("relauncher is not supported on non-Windows".into())
+ }
}
fn relauncher_script(exe: &str, version: &str, arguments: &str) -> String {
@@ -559,11 +583,13 @@ pub fn run_service() -> ExitCode {
}
};
// Not waited for: the installer replaces this program, which must not be running.
- match std::process::Command::new(&path)
- .arg("/S")
- .creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS)
- .spawn()
- {
+ #[cfg(windows)]
+ let mut cmd = std::process::Command::new(&path);
+ #[cfg(windows)]
+ cmd.arg("/S").creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS);
+ #[cfg(not(windows))]
+ let mut cmd = std::process::Command::new(&path);
+ match cmd.spawn() {
Ok(_) => {
log(&format!("installing {}", update.version));
ExitCode::SUCCESS
diff --git a/desktop/vcam/src/lib.rs b/desktop/vcam/src/lib.rs
index 50552d9..72e93e4 100644
--- a/desktop/vcam/src/lib.rs
+++ b/desktop/vcam/src/lib.rs
@@ -4,8 +4,10 @@
#![allow(linker_messages)]
+#[cfg(windows)]
use std::sync::atomic::Ordering;
+#[cfg(windows)]
use windows::{
Win32::{
Foundation::{CLASS_E_CLASSNOTAVAILABLE, E_INVALIDARG, E_POINTER, S_FALSE, S_OK},
@@ -15,24 +17,79 @@ use windows::{
core::{GUID, HRESULT, IUnknown, Interface},
};
+#[cfg(windows)]
pub mod shm;
+#[cfg(windows)]
pub mod source;
+#[cfg(windows)]
pub use shm::{
DEFAULT_MAPPING_NAME, LOCAL_MAPPING_NAME, MAX_FRAME_BYTES, MAX_HEIGHT, MAX_WIDTH, SharedFrameMapping,
bgrx_to_nv12, fit_bgrx_aspect, render_placeholder_bgrx,
};
+#[cfg(windows)]
pub use source::{SAMPLE_DURATION_100NS, VcamClassFactory, VcamMediaSource, VcamMediaStream};
-/// CLSID of the NectarLink Virtual Camera Media Foundation media source:
-/// `{8E6C3B74-5D4A-4B9E-9A12-7C8F1E2D3A40}`.
+#[cfg(windows)]
pub const CLSID_NECTARLINK_VCAM: GUID = GUID::from_u128(0x8e6c3b74_5d4a_4b9e_9a12_7c8f1e2d3a40);
+#[cfg(not(windows))]
+pub const DEFAULT_MAPPING_NAME: &str = "";
+#[cfg(not(windows))]
+pub const LOCAL_MAPPING_NAME: &str = "";
+#[cfg(not(windows))]
+pub const MAX_FRAME_BYTES: usize = 0;
+#[cfg(not(windows))]
+pub const MAX_HEIGHT: u32 = 0;
+#[cfg(not(windows))]
+pub const MAX_WIDTH: u32 = 0;
+#[cfg(not(windows))]
+pub const SAMPLE_DURATION_100NS: i64 = 0;
+#[cfg(not(windows))]
+pub const CLSID_NECTARLINK_VCAM: [u8; 16] = [0; 16];
+
+#[cfg(not(windows))]
+#[derive(Debug)]
+pub struct SharedFrameMapping;
+
+#[cfg(not(windows))]
+impl SharedFrameMapping {
+ pub fn open_or_create(_name: &str) -> Result<Self, String> {
+ Err("virtual camera is only supported on Windows".into())
+ }
+ pub fn open_existing(_name: &str) -> Result<Self, String> {
+ Err("virtual camera is only supported on Windows".into())
+ }
+ pub fn write_frame(
+ &self,
+ _device_name: &str,
+ _w: u32,
+ _h: u32,
+ _timestamp: u64,
+ _bgrx: &[u8],
+ _mirror: bool,
+ ) {
+ }
+ pub fn set_idle(&self, _device_name: &str) {}
+}
+
+#[cfg(not(windows))]
+pub fn render_placeholder_bgrx(_bgrx: &mut [u8], _w: u32, _h: u32, _text: &str) {}
+#[cfg(not(windows))]
+pub fn bgrx_to_nv12(_bgrx: &[u8], _w: u32, _h: u32) -> Vec<u8> {
+ Vec::new()
+}
+#[cfg(not(windows))]
+pub fn fit_bgrx_aspect(_bgrx: &[u8], _sw: u32, _sh: u32, _tw: u32, _th: u32) -> Vec<u8> {
+ Vec::new()
+}
+
/// Standard COM DLL entry point returning an `IClassFactory` for
/// [`CLSID_NECTARLINK_VCAM`].
///
/// # Safety
/// `rclsid`, `riid`, and `ppv` must be valid pointers as specified by COM.
+#[cfg(windows)]
#[unsafe(no_mangle)]
#[allow(unsafe_code)]
pub unsafe extern "system" fn DllGetClassObject(
@@ -61,13 +118,14 @@ pub unsafe extern "system" fn DllGetClassObject(
}
/// Standard COM DLL unload check.
+#[cfg(windows)]
#[unsafe(no_mangle)]
#[allow(unsafe_code)]
pub extern "system" fn DllCanUnloadNow() -> HRESULT {
if source::ACTIVE_OBJECTS.load(Ordering::Relaxed) == 0 { S_OK } else { S_FALSE }
}
-#[cfg(test)]
+#[cfg(all(test, windows))]
#[allow(unsafe_code)]
mod tests {
use super::*;
diff --git a/spikes/s1-qt-rust/cpp/frame_notifier.h b/spikes/s1-qt-rust/cpp/frame_notifier.h
index c46f85f..ae6fb4d 100644
--- a/spikes/s1-qt-rust/cpp/frame_notifier.h
+++ b/spikes/s1-qt-rust/cpp/frame_notifier.h
@@ -1,5 +1,6 @@
-// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
+#ifndef NL_FRAME_NOTIFIER_H
+#define NL_FRAME_NOTIFIER_H
#include <QtCore/QPointer>
#include <QtQuick/QQuickItem>
@@ -29,3 +30,5 @@ private:
};
} // namespace nl
+
+#endif // NL_FRAME_NOTIFIER_H
diff --git a/spikes/s1-qt-rust/cpp/video_surface.cpp b/spikes/s1-qt-rust/cpp/video_surface.cpp
index faae33a..369cba1 100644
--- a/spikes/s1-qt-rust/cpp/video_surface.cpp
+++ b/spikes/s1-qt-rust/cpp/video_surface.cpp
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "video_surface.h"
-#include "frame_notifier.h"
#include "s1-qt-rust/src/video.cxx.h"
#include <rust/cxx.h>
@@ -11,13 +10,15 @@
#include <QtQuick/QSGSimpleTextureNode>
#include <QtQuick/qsgtexture_platform.h>
+#ifdef _WIN32
#include <d3d11_1.h>
#include <dxgi1_2.h>
#include <wrl/client.h>
-#include <optional>
-
using Microsoft::WRL::ComPtr;
+#endif
+
+#include <optional>
namespace nl {
@@ -34,6 +35,12 @@ class VideoNode final : public QSGSimpleTextureNode
public:
static VideoNode *create(QQuickWindow *window, std::shared_ptr<FrameNotifier> notifier, QString *error)
{
+#ifndef _WIN32
+ Q_UNUSED(window);
+ Q_UNUSED(notifier);
+ *error = QStringLiteral("video needs the D3D11 backend (Windows only)");
+ return nullptr;
+#else
QSGRendererInterface *ri = window->rendererInterface();
if (ri->graphicsApi() != QSGRendererInterface::Direct3D11) {
*error = QStringLiteral("video needs the D3D11 backend");
@@ -86,12 +93,17 @@ public:
node->setTexture(node->m_sgTexture.get());
node->setFiltering(QSGTexture::Linear);
return node.release();
+#endif
}
// Copies the newest published frame, GPU to GPU. Returns false if the
// producer held the texture and the copy should be retried next frame.
bool sync(quint64 *shown)
{
+#ifndef _WIN32
+ Q_UNUSED(shown);
+ return true;
+#else
const quint64 published = (*m_source)->frames_published();
if (published == m_lastPublished)
return true;
@@ -104,14 +116,29 @@ public:
++*shown;
markDirty(QSGNode::DirtyMaterial);
return true;
+#endif
+ }
+
+ quint64 published() const {
+#ifndef _WIN32
+ return 0;
+#else
+ return (*m_source)->frames_published();
+#endif
}
- quint64 published() const { return (*m_source)->frames_published(); }
- quint64 dropped() const { return (*m_source)->frames_dropped(); }
+ quint64 dropped() const {
+#ifndef _WIN32
+ return 0;
+#else
+ return (*m_source)->frames_dropped();
+#endif
+ }
private:
VideoNode() = default;
+#ifdef _WIN32
// Declared first so it is destroyed last: the producer stops only after
// Qt's references to the shared texture are released.
std::optional<rust::Box<VideoSource>> m_source;
@@ -122,6 +149,7 @@ private:
std::unique_ptr<QSGTexture> m_sgTexture;
ID3D11DeviceContext *m_context = nullptr; // owned by Qt
quint64 m_lastPublished = 0;
+#endif
};
QRectF fitted(const QRectF &bounds, QSizeF content)
diff --git a/spikes/s1-qt-rust/src/video.rs b/spikes/s1-qt-rust/src/video.rs
index ee50dda..f969b08 100644
--- a/spikes/s1-qt-rust/src/video.rs
+++ b/spikes/s1-qt-rust/src/video.rs
@@ -19,6 +19,7 @@ use std::{
time::{Duration, Instant},
};
+#[cfg(windows)]
use windows::{
Win32::{
Foundation::{CloseHandle, E_FAIL, HANDLE, HMODULE, LUID, RECT, S_OK},
@@ -84,6 +85,7 @@ struct Counters {
dropped: AtomicU64,
}
+#[cfg(windows)]
pub struct VideoSource {
shared: HANDLE,
counters: Arc<Counters>,
@@ -91,9 +93,11 @@ pub struct VideoSource {
thread: Option<JoinHandle<()>>,
}
+#[cfg(windows)]
// SAFETY: the HANDLE is an owned NT handle, usable from any thread.
unsafe impl Send for VideoSource {}
+#[cfg(windows)]
impl VideoSource {
fn shared_handle(&self) -> usize {
self.shared.0 as usize
@@ -108,6 +112,7 @@ impl VideoSource {
}
}
+#[cfg(windows)]
impl Drop for VideoSource {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
@@ -122,6 +127,7 @@ impl Drop for VideoSource {
}
}
+#[cfg(windows)]
fn video_source_start(
adapter_luid: i64,
width: u32,
@@ -174,6 +180,57 @@ fn video_source_start(
Ok(Box::new(VideoSource { shared, counters, stop, thread: Some(thread) }))
}
+#[cfg(not(windows))]
+pub struct VideoSource {
+ counters: Arc<Counters>,
+ stop: Arc<AtomicBool>,
+ thread: Option<JoinHandle<()>>,
+}
+
+#[cfg(not(windows))]
+unsafe impl Send for VideoSource {}
+
+#[cfg(not(windows))]
+impl VideoSource {
+ fn shared_handle(&self) -> usize {
+ 0
+ }
+
+ fn frames_published(&self) -> u64 {
+ self.counters.published.load(Ordering::Relaxed)
+ }
+
+ fn frames_dropped(&self) -> u64 {
+ self.counters.dropped.load(Ordering::Relaxed)
+ }
+}
+
+#[cfg(not(windows))]
+impl Drop for VideoSource {
+ fn drop(&mut self) {
+ self.stop.store(true, Ordering::Relaxed);
+ if let Some(thread) = self.thread.take() {
+ let _ = thread.join();
+ }
+ }
+}
+
+#[cfg(not(windows))]
+fn video_source_start(
+ _adapter_luid: i64,
+ _width: u32,
+ _height: u32,
+ _fps: u32,
+ _notifier: cxx::SharedPtr<ffi::FrameNotifier>,
+) -> Result<Box<VideoSource>, String> {
+ Ok(Box::new(VideoSource {
+ counters: Arc::new(Counters::default()),
+ stop: Arc::new(AtomicBool::new(false)),
+ thread: None,
+ }))
+}
+
+#[cfg(windows)]
/// The producer's GPU state. Lives on the producer thread after creation.
struct Gpu {
context: ID3D11DeviceContext1,
@@ -185,10 +242,12 @@ struct Gpu {
height: u32,
}
+#[cfg(windows)]
// SAFETY: the device is created without D3D11_CREATE_DEVICE_SINGLETHREADED and
// the context is only ever used by one thread at a time (moved, never shared).
unsafe impl Send for Gpu {}
+#[cfg(windows)]
impl Gpu {
fn new(luid: LUID, width: u32, height: u32) -> windows::core::Result<Self> {
// SAFETY: plain D3D11/DXGI object creation; every out-pointer is a