Skip to content

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

Desktop: send files to a phone from File Explorer

Beec1a04dd5df0d
diff --git a/Cargo.lock b/Cargo.lock
index 40f4de0..2fb0c77 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1023,6 +1023,20 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "embed-resource"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd"
+dependencies = [
+ "cc",
+ "memchr",
+ "rustc_version",
+ "toml",
+ "vswhom",
+ "winreg",
+]
+
[[package]]
name = "embedded-io"
version = "0.4.0"
@@ -2331,6 +2345,7 @@ dependencies = [
"cxx-qt-build",
"cxx-qt-lib",
"dirs",
+ "embed-resource",
"hostname",
"material-colors",
"nectarlink-core",
@@ -4400,6 +4415,26 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+[[package]]
+name = "vswhom"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"
+dependencies = [
+ "libc",
+ "vswhom-sys",
+]
+
+[[package]]
+name = "vswhom-sys"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"
+dependencies = [
+ "cc",
+ "libc",
+]
+
[[package]]
name = "walkdir"
version = "2.5.0"
@@ -4726,6 +4761,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -4874,6 +4918,16 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "winreg"
+version = "0.55.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
+dependencies = [
+ "cfg-if",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "wit-bindgen"
version = "0.57.1"
diff --git a/Cargo.toml b/Cargo.toml
index 0e6d957..b04d90d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -27,6 +27,7 @@ clap = { version = "4.6", features = ["derive"] }
cxx = "1"
cxx-qt = "0.10"
cxx-qt-build = "0.10"
+embed-resource = "3"
cxx-qt-lib = { version = "0.10", features = ["qt_gui", "qt_qml"] }
data-encoding = "2.11"
dirs = "7"
diff --git a/README.md b/README.md
index 1a47dca..83bf38e 100644
--- a/README.md
+++ b/README.md
@@ -79,8 +79,9 @@ place and tested; the user-facing features of Phase 1 come next.
in the app (Android lets only the app in front read the clipboard).
Passwords that password managers mark private are never sent.
- **Files** in both directions, at Wi-Fi speed. On the PC, drop files on the
- window or pick them; on the phone, share them from any app or pick them in
- Nectarlink. They land in `Downloads\Nectarlink` on the PC and
+ window, pick them, or right-click them in File Explorer and choose
+ **Send to** and your phone (a notification follows the transfer); on the
+ phone, share them from any app or pick them in Nectarlink. They land in `Downloads\Nectarlink` on the PC and
`Download/Nectarlink` on the phone, with progress, cancelling, and transfers
that pick up where they left off after a dropped connection.
- **Capability matrix**: both apps compute which features work for a pair of
@@ -94,8 +95,8 @@ place and tested; the user-facing features of Phase 1 come next.
connection service, and an identity key protected by the Android Keystore.
- **Command-line client** for development and testing (`nectarlink`).
-**Next (Phase 1)**: "Send to phone" in Explorer, images on the clipboard, media
-controls, notification filters and history, and a Windows installer. Mirroring, messages, calls and the other
+**Next (Phase 1)**: images on the clipboard, media controls, notification
+filters and history, and a Windows installer. Mirroring, messages, calls and the other
features in the plan follow in later phases.
## Screenshots
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
index 83324fa..8f24735 100644
--- a/desktop/app/Cargo.toml
+++ b/desktop/app/Cargo.toml
@@ -58,6 +58,7 @@ windows = { workspace = true, features = [
[build-dependencies]
cxx-qt-build = { workspace = true, features = ["link_qt_object_files"] }
+embed-resource.workspace = true
[dev-dependencies]
tempfile.workspace = true
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
index 3e4ad33..8bed864 100644
--- a/desktop/app/build.rs
+++ b/desktop/app/build.rs
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Builds the QML module `app.nectarlink` (QML files compiled ahead of time,
-//! Rust QObjects, C++ helpers), compiles in the bundled fonts and links the
-//! Windows libraries C++ uses.
+//! Rust QObjects, C++ helpers), compiles in the bundled fonts, gives the
+//! executable its icon and version information, and links the Windows
+//! libraries C++ uses.
use std::{
fs,
@@ -10,6 +11,10 @@ use std::{
use cxx_qt_build::{CxxQtBuilder, QmlFile, QmlModule};
+// The mark the app draws at runtime, rendered here for the .exe's icon.
+#[path = "src/mark.rs"]
+mod mark;
+
const QML: &[&str] = &[
"qml/App.qml",
"qml/MainWindow.qml",
@@ -66,7 +71,109 @@ fn fonts_qrc() -> PathBuf {
out
}
+/// Icon sizes in the .exe: what Explorer, the taskbar and Start ask for at
+/// 100–200% scale.
+const ICON_SIZES: &[u32] = &[16, 20, 24, 32, 40, 48, 64, 256];
+
+/// An .ico file with the mark at every size, as 32-bit bitmaps (alpha used,
+/// AND mask empty).
+fn icon_file() -> Vec<u8> {
+ let images: Vec<Vec<u8>> = ICON_SIZES
+ .iter()
+ .map(|&size| {
+ let rgba = mark::render(size as usize);
+ let mask_row = size.div_ceil(32) * 4;
+ let mut image = Vec::new();
+ // BITMAPINFOHEADER; the height counts the color and mask halves.
+ for field in [40, size, size * 2] {
+ image.extend_from_slice(&field.to_le_bytes());
+ }
+ image.extend_from_slice(&1u16.to_le_bytes());
+ image.extend_from_slice(&32u16.to_le_bytes());
+ image.extend_from_slice(&[0; 24]);
+ // Bottom-up BGRA rows.
+ for row in rgba.chunks_exact(size as usize * 4).rev() {
+ for p in row.as_chunks::<4>().0 {
+ image.extend_from_slice(&[p[2], p[1], p[0], p[3]]);
+ }
+ }
+ image.resize(image.len() + (mask_row * size) as usize, 0);
+ image
+ })
+ .collect();
+ let count = u16::try_from(images.len()).expect("a few sizes");
+ let mut ico = Vec::new();
+ for field in [0u16, 1, count] {
+ ico.extend_from_slice(&field.to_le_bytes());
+ }
+ let mut offset = 6 + 16 * images.len();
+ for (&size, image) in ICON_SIZES.iter().zip(&images) {
+ // 256 is written as 0.
+ let side = u8::try_from(size).unwrap_or(0);
+ ico.extend_from_slice(&[side, side, 0, 0]);
+ ico.extend_from_slice(&1u16.to_le_bytes());
+ ico.extend_from_slice(&32u16.to_le_bytes());
+ ico.extend_from_slice(&u32::try_from(image.len()).expect("small").to_le_bytes());
+ ico.extend_from_slice(&u32::try_from(offset).expect("small").to_le_bytes());
+ offset += image.len();
+ }
+ for image in images {
+ ico.extend_from_slice(&image);
+ }
+ ico
+}
+
+/// The .exe's icon and version information (what Explorer, shortcuts and
+/// Task Manager show).
+fn windows_resources() {
+ let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR"));
+ let ico = out.join("nectarlink.ico");
+ fs::write(&ico, icon_file()).expect("write the icon");
+ let version = std::env::var("CARGO_PKG_VERSION").expect("version");
+ let numbers: Vec<&str> = version.split(['.', '-', '+']).take(3).collect();
+ let numeric = format!("{},0", numbers.join(","));
+ // No #include: numeric constants keep rc.exe off the SDK headers.
+ // 0x40004 is VOS_NT_WINDOWS32, 0x1 is VFT_APP.
+ let rc = format!(
+ r#"1 ICON "{ico}"
+1 VERSIONINFO
+FILEVERSION {numeric}
+PRODUCTVERSION {numeric}
+FILEOS 0x40004
+FILETYPE 0x1
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904B0"
+ BEGIN
+ VALUE "CompanyName", "The Nectarlink contributors"
+ VALUE "FileDescription", "Nectarlink"
+ VALUE "FileVersion", "{version}"
+ VALUE "InternalName", "nectarlink-desktop"
+ VALUE "LegalCopyright", "GPL-3.0-or-later"
+ VALUE "OriginalFilename", "nectarlink-desktop.exe"
+ VALUE "ProductName", "Nectarlink"
+ VALUE "ProductVersion", "{version}"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x409, 1200
+ END
+END
+"#,
+ ico = ico.display().to_string().replace('\\', "/"),
+ );
+ let rc_path = out.join("nectarlink.rc");
+ fs::write(&rc_path, rc).expect("write the resource script");
+ embed_resource::compile(&rc_path, embed_resource::NONE).manifest_required().expect("compile resources");
+}
+
fn main() {
+ println!("cargo:rerun-if-changed=src/mark.rs");
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
+ windows_resources();
+ }
let module = QmlModule::new("app.nectarlink")
.qml_files(QML.iter().map(|f| QmlFile::from(*f)))
.qml_files(QML_SINGLETONS.iter().map(|f| QmlFile::from(*f).singleton(true)));
diff --git a/desktop/app/qml/App.qml b/desktop/app/qml/App.qml
index bced4ad..03475f6 100644
--- a/desktop/app/qml/App.qml
+++ b/desktop/app/qml/App.qml
@@ -11,6 +11,7 @@ QtObject {
property MainWindow mainWindow: null
readonly property Component mainComponent: Component { MainWindow {} }
readonly property bool startMinimized: Qt.application.arguments.indexOf("--minimized") >= 0
+ || Qt.application.arguments.indexOf("--send-to") >= 0
function showMain() {
if (!mainWindow) {
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index c719aee..30fa963 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -162,6 +162,18 @@ Item {
onToggled: (on) => Preferences.autoClipboard = on
}
}
+ Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.send
+ title: qsTr("Show your phones in File Explorer")
+ description: qsTr("Right-click files, choose Send to, then your phone.")
+ Toggle {
+ label: qsTr("Show your phones in File Explorer")
+ checked: Preferences.sendToMenu
+ onToggled: (on) => Preferences.sendToMenu = on
+ }
+ }
}
}
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index 28d7592..b4b1466 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -137,6 +137,13 @@ fn controller() -> Option<CxxQtThread<qobject::AppController>> {
CONTROLLER.get()?.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
+/// Asks the app to quit (from any thread), as Quit in the tray does.
+pub fn request_quit() {
+ if let Some(qt) = controller() {
+ let _ = qt.queue(|object| object.quit_requested());
+ }
+}
+
/// Asks the UI to show the main window (from any thread).
pub fn request_activation() {
if let Some(qt) = controller() {
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
index 749f966..da3b50b 100644
--- a/desktop/app/src/bridge/prefs.rs
+++ b/desktop/app/src/bridge/prefs.rs
@@ -41,6 +41,8 @@ pub mod qobject {
#[qproperty(bool, close_to_tray)]
/// Send what's copied on this PC to connected phones.
#[qproperty(bool, auto_clipboard)]
+ /// Paired phones in Explorer's "Send to" menu.
+ #[qproperty(bool, send_to_menu)]
type Preferences = super::PreferencesRust;
}
@@ -55,6 +57,7 @@ pub struct PreferencesRust {
backdrop: bool,
close_to_tray: bool,
auto_clipboard: bool,
+ send_to_menu: bool,
}
impl cxx_qt::Initialize for qobject::Preferences {
@@ -74,6 +77,7 @@ impl cxx_qt::Initialize for qobject::Preferences {
self.as_mut().set_close_to_tray(settings.close_to_tray);
self.as_mut().set_auto_clipboard(settings.auto_clipboard);
crate::clipboard::set_auto_send(settings.auto_clipboard);
+ self.as_mut().set_send_to_menu(settings.send_to_menu);
// Save after any change (connected after loading, so loading doesn't
// rewrite the file).
@@ -88,6 +92,12 @@ impl cxx_qt::Initialize for qobject::Preferences {
p.save();
})
.release();
+ self.as_mut()
+ .on_send_to_menu_changed(|p| {
+ crate::send_to::set_enabled(p.send_to_menu);
+ p.save();
+ })
+ .release();
}
}
@@ -105,6 +115,7 @@ impl qobject::Preferences {
backdrop: p.backdrop,
close_to_tray: p.close_to_tray,
auto_clipboard: p.auto_clipboard,
+ send_to_menu: p.send_to_menu,
};
save_in_background(settings);
}
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index 57bd5e7..4e4c7f7 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -12,7 +12,10 @@ use std::{
};
use nectarlink_core::{DeviceInfo, DeviceKind, LinkState, Node, NodeConfig, Platform};
-use tokio::{runtime::Runtime, sync::broadcast::error::RecvError};
+use tokio::{
+ runtime::Runtime,
+ sync::{Notify, broadcast::error::RecvError},
+};
use crate::state::{Changes, CoreStatus, Hub};
@@ -22,6 +25,8 @@ const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
pub struct CoreHost {
runtime: Runtime,
node: OnceLock<Node>,
+ /// Signaled once the node is up, or has failed to start.
+ started: Notify,
pub hub: Arc<Hub>,
pub data_dir: PathBuf,
}
@@ -38,6 +43,22 @@ pub fn node() -> Option<Node> {
host().node.get().cloned()
}
+/// The node once it has started, or `None` if it couldn't.
+pub async fn wait_for_node() -> Option<Node> {
+ let host = host();
+ loop {
+ // Created before checking, so a signal in between isn't missed.
+ let started = host.started.notified();
+ if let Some(node) = node() {
+ return Some(node);
+ }
+ if host.hub.read(|s| matches!(s.status, Some(CoreStatus::Failed(_)))) {
+ return None;
+ }
+ started.await;
+ }
+}
+
/// Runs a command on the core's runtime.
pub fn spawn(fut: impl Future<Output = ()> + Send + 'static) {
host().runtime.spawn(fut);
@@ -50,7 +71,13 @@ pub fn start(data_dir: PathBuf, platform: Arc<dyn Platform>) -> std::io::Result<
.thread_name("nectarlink-core")
.enable_all()
.build()?;
- let host = CoreHost { runtime, node: OnceLock::new(), hub: Hub::new(), data_dir: data_dir.clone() };
+ let host = CoreHost {
+ runtime,
+ node: OnceLock::new(),
+ started: Notify::new(),
+ hub: Hub::new(),
+ data_dir: data_dir.clone(),
+ };
if HOST.set(host).is_err() {
panic!("core host started twice");
}
@@ -75,6 +102,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
s.status = Some(CoreStatus::Failed(e.to_string()));
Changes::STATUS
});
+ host.started.notify_waiters();
return;
}
};
@@ -102,6 +130,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
changes |= Changes::STATUS | Changes::CAPABILITIES;
changes
});
+ host.started.notify_waiters();
loop {
match events.recv().await {
@@ -110,6 +139,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
crate::notifications::update_toasts(&event);
crate::clipboard::on_event(&event);
crate::transfers::on_event(&event);
+ crate::send_to::on_event(&event);
}
Err(RecvError::Lagged(missed)) => {
// Resynchronize what can be re-read; transient events are lost.
diff --git a/desktop/app/src/launch.rs b/desktop/app/src/launch.rs
new file mode 100644
index 0000000..d0bdb89
--- /dev/null
+++ b/desktop/app/src/launch.rs
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! What another launch of Nectarlink asks the running one to do: show its
+//! window (Start menu, shortcuts), send files (Explorer's "Send to") or
+//! quit (the installer, before replacing or removing the app).
+//!
+//! The launch writes a request file into the data folder, then wakes the
+//! running instance (`win::single_instance`), which drains the folder. The
+//! data folder is private to the user, and files survive the moment between
+//! a first launch taking over and the app being ready to send.
+
+use std::{
+ fs,
+ io::{self, Write},
+ path::{Path, PathBuf},
+ time::{Duration, SystemTime, UNIX_EPOCH},
+};
+
+use serde::{Deserialize, Serialize};
+
+const DIR: &str = "requests";
+/// Requests older than this were left by a launch whose instance went away
+/// before handling them; acting on them later would surprise the user.
+const MAX_AGE: Duration = Duration::from_secs(120);
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum Request {
+ /// Show the window.
+ Show,
+ /// Send files to a paired device.
+ Send { device: String, paths: Vec<PathBuf> },
+ /// Quit.
+ Quit,
+}
+
+fn dir(data_dir: &Path) -> PathBuf {
+ data_dir.join(DIR)
+}
+
+/// Leaves a request for the running instance (or for this one, if it turns
+/// out to be the first).
+pub fn queue(data_dir: &Path, request: &Request) -> io::Result<()> {
+ let dir = dir(data_dir);
+ fs::create_dir_all(&dir)?;
+ let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos());
+ // Sorts by time; the process ID keeps simultaneous launches apart.
+ let name = format!("{nanos:024}-{}", std::process::id());
+ let partial = dir.join(format!("{name}.tmp"));
+ let mut file = fs::File::create(&partial)?;
+ file.write_all(&serde_json::to_vec(request).map_err(io::Error::other)?)?;
+ file.sync_all()?;
+ drop(file);
+ // Whole files only: the instance never reads one half-written.
+ fs::rename(&partial, dir.join(format!("{name}.json")))
+}
+
+/// Takes the waiting requests, oldest first.
+pub fn drain(data_dir: &Path) -> Vec<Request> {
+ let Ok(entries) = fs::read_dir(dir(data_dir)) else { return Vec::new() };
+ let mut files: Vec<PathBuf> = entries
+ .filter_map(|e| e.ok().map(|e| e.path()))
+ .filter(|p| p.extension().is_some_and(|e| e == "json"))
+ .collect();
+ files.sort();
+ let now = SystemTime::now();
+ files
+ .into_iter()
+ .filter_map(|path| {
+ let fresh = fs::metadata(&path)
+ .and_then(|m| m.modified())
+ .is_ok_and(|t| now.duration_since(t).unwrap_or_default() <= MAX_AGE);
+ let request = fs::read(&path).ok().and_then(|bytes| serde_json::from_slice(&bytes).ok());
+ if let Err(e) = fs::remove_file(&path) {
+ tracing::warn!(error = %e, "can't remove a handled request");
+ }
+ match request {
+ Some(request) if fresh => Some(request),
+ Some(_) => {
+ tracing::info!("dropped a stale request");
+ None
+ }
+ None => {
+ tracing::warn!("dropped an unreadable request");
+ None
+ }
+ }
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn send(n: u8) -> Request {
+ Request::Send {
+ device: format!("device{n}"),
+ paths: vec![PathBuf::from(format!(r"C:\files\{n} é.txt"))],
+ }
+ }
+
+ #[test]
+ fn requests_come_back_once_in_order() {
+ let data = tempfile::tempdir().unwrap();
+ assert!(drain(data.path()).is_empty(), "nothing queued yet");
+ queue(data.path(), &send(1)).unwrap();
+ queue(data.path(), &Request::Show).unwrap();
+ queue(data.path(), &send(2)).unwrap();
+ assert_eq!(drain(data.path()), vec![send(1), Request::Show, send(2)]);
+ assert!(drain(data.path()).is_empty(), "drained");
+ }
+
+ #[test]
+ fn unreadable_and_partial_files_are_skipped() {
+ let data = tempfile::tempdir().unwrap();
+ let dir = dir(data.path());
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("1.json"), b"{not json").unwrap();
+ fs::write(dir.join("2.tmp"), b"{}").unwrap();
+ queue(data.path(), &Request::Show).unwrap();
+ assert_eq!(drain(data.path()), vec![Request::Show]);
+ assert!(!dir.join("1.json").exists(), "removed");
+ assert!(dir.join("2.tmp").exists(), "a write in progress is left alone");
+ }
+
+ #[test]
+ fn stale_requests_are_dropped() {
+ let data = tempfile::tempdir().unwrap();
+ queue(data.path(), &send(1)).unwrap();
+ let path = fs::read_dir(dir(data.path())).unwrap().next().unwrap().unwrap().path();
+ let old = SystemTime::now() - MAX_AGE - Duration::from_secs(5);
+ fs::File::options().write(true).open(&path).unwrap().set_modified(old).unwrap();
+ assert!(drain(data.path()).is_empty());
+ assert!(!path.exists());
+ }
+}
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 740af80..fc37fdd 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -12,10 +12,13 @@ mod bridge;
mod clipboard;
mod core_host;
mod icons;
+mod launch;
mod logging;
+mod mark;
mod notifications;
mod palette;
mod qr;
+mod send_to;
mod settings;
mod state;
mod transfers;
@@ -34,7 +37,10 @@ use std::{
use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QString, QUrl};
use nectarlink_core::Platform;
-use crate::win::single_instance::{self, Instance};
+use crate::{
+ launch::Request,
+ win::single_instance::{self, Instance},
+};
/// How many fonts `build.rs` compiles in.
const BUNDLED_FONTS: i32 = 4;
@@ -62,19 +68,40 @@ struct Options {
data_dir: Option<PathBuf>,
/// Start in the tray without opening the window (autostart).
minimized: bool,
+ /// `--send-to <device> <files…>`: Explorer's "Send to" menu.
+ send_to: Option<(String, Vec<PathBuf>)>,
+ /// Ask the running app to quit (the installer, before an update).
+ quit: bool,
+ /// Quit the running app and undo what it set up in Windows (the
+ /// uninstaller). Data is kept.
+ uninstall: bool,
}
fn parse_options() -> Options {
let mut options = Options::default();
- let mut args = std::env::args().skip(1);
+ let mut paths = Vec::new();
+ let mut args = std::env::args_os().skip(1);
while let Some(arg) = args.next() {
- match arg.as_str() {
- "--data-dir" => options.data_dir = args.next().map(PathBuf::from),
- "--minimized" => options.minimized = true,
- // Qt reads its own arguments; ignore everything else.
+ match arg.to_str() {
+ Some("--data-dir") => options.data_dir = args.next().map(PathBuf::from),
+ Some("--minimized") => options.minimized = true,
+ Some("--quit") => options.quit = true,
+ Some("--uninstall") => options.uninstall = true,
+ Some(send_to::ARG) => {
+ let device = args.next().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default();
+ options.send_to = Some((device, Vec::new()));
+ }
+ // Explorer adds the chosen files after the shortcut's arguments.
+ _ if !arg.to_string_lossy().starts_with('-') => paths.push(PathBuf::from(arg)),
+ // Qt reads its own options; ignore everything else.
_ => {}
}
}
+ if let Some((_, files)) = &mut options.send_to {
+ *files = paths;
+ // Sending doesn't need the window.
+ options.minimized = true;
+ }
options
}
@@ -107,6 +134,16 @@ fn start_toasts() {
win::toast::start(icon, notifications::on_toast);
}
+/// Removes what the app set up in Windows: the "Send to" entries and the
+/// notification sender registration.
+fn uninstall() {
+ tracing::info!("uninstalling");
+ if let Err(e) = send_to::remove_all() {
+ tracing::warn!(error = %e, "can't remove the Send to entries");
+ }
+ win::toast::unregister();
+}
+
fn install_panic_logging() {
let default = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
@@ -126,10 +163,25 @@ fn main() -> ExitCode {
install_panic_logging();
tracing::info!(version = env!("CARGO_PKG_VERSION"), minimized = options.minimized, "starting");
+ if options.uninstall {
+ uninstall();
+ }
+ let request = match options.send_to.clone() {
+ _ if options.quit || options.uninstall => Request::Quit,
+ Some((device, paths)) => Request::Send { device, paths },
+ None => Request::Show,
+ };
let instance = match single_instance::acquire(&data_dir) {
+ // Nothing running to quit.
+ Ok(Instance::Primary(_)) if request == Request::Quit => return ExitCode::SUCCESS,
Ok(Instance::Primary(primary)) => Some(&*Box::leak(Box::new(primary))),
Ok(Instance::Secondary) => {
- tracing::info!("already running; asked it to show itself");
+ // Without the request, the running instance still shows itself.
+ if let Err(e) = launch::queue(&data_dir, &request) {
+ tracing::warn!(error = %e, "can't pass the request on");
+ }
+ single_instance::wake(&data_dir);
+ tracing::info!("already running; passed the request on");
return ExitCode::SUCCESS;
}
Err(e) => {
@@ -140,13 +192,27 @@ fn main() -> ExitCode {
// Before any window: toasts and the taskbar both go by this ID.
win::toast::set_process_id();
- if let Err(e) = core_host::start(data_dir, Arc::new(DesktopPlatform)) {
+ if let Err(e) = core_host::start(data_dir.clone(), Arc::new(DesktopPlatform)) {
tracing::error!(error = %e, "can't start the core runtime");
return ExitCode::FAILURE;
}
watch_network();
start_toasts();
clipboard::start();
+ send_to::set_enabled(settings::Settings::load(&data_dir).send_to_menu);
+ // A test instance (own data folder) leaves the user's menu alone.
+ if options.data_dir.is_none() {
+ send_to::start();
+ }
+ // Requests left while no instance was running, then this launch's own.
+ for waiting in launch::drain(&data_dir) {
+ if matches!(waiting, Request::Send { .. }) {
+ send_to::handle(waiting);
+ }
+ }
+ if matches!(request, Request::Send { .. }) {
+ send_to::handle(request);
+ }
bridge::native::ffi::prepare_qt();
let mut app = QGuiApplication::new();
@@ -161,12 +227,19 @@ fn main() -> ExitCode {
tracing::warn!(loaded = fonts, expected = BUNDLED_FONTS, "some bundled fonts didn't load");
}
for size in [16, 20, 24, 32, 40, 48, 64, 256] {
- bridge::native::ffi::add_app_icon_image(size, &win::icon::render(size as usize));
+ bridge::native::ffi::add_app_icon_image(size, &mark::render(size as usize));
}
bridge::native::ffi::apply_app_icon();
if let Some(instance) = instance {
- instance.watch(bridge::app::request_activation);
+ let data_dir = data_dir.clone();
+ instance.watch(move || {
+ let requests = launch::drain(&data_dir);
+ if requests.is_empty() {
+ bridge::app::request_activation();
+ }
+ requests.into_iter().for_each(send_to::handle);
+ });
}
let mut engine = QQmlApplicationEngine::new();
diff --git a/desktop/app/src/mark.rs b/desktop/app/src/mark.rs
new file mode 100644
index 0000000..de1d7bb
--- /dev/null
+++ b/desktop/app/src/mark.rs
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! The Nectarlink mark (a hexagon on a rounded square, as in the app's nav
+//! rail), drawn in code at any pixel size: the tray, window and toast icons
+//! at runtime, and the executable's icon at build time (`build.rs` includes
+//! this file), so every size is sharp without bitmap assets.
+
+/// Honey primary (docs/design/tokens.json) and the mark's ink.
+const BACKGROUND: [u8; 3] = [0x8A, 0x51, 0x00];
+const INK: [u8; 3] = [0xFF, 0xFF, 0xFF];
+
+/// Hexagon and bar of the mark, in a 24×24 design grid.
+const HEXAGON: [(f32, f32); 6] =
+ [(12.0, 2.5), (20.2, 7.25), (20.2, 16.75), (12.0, 21.5), (3.8, 16.75), (3.8, 7.25)];
+const BAR: ((f32, f32), (f32, f32)) = ((9.0, 12.0), (15.0, 12.0));
+
+/// Supersampling grid per pixel (SS×SS samples) for smooth edges.
+const SS: usize = 4;
+
+/// Renders the mark as straight-alpha RGBA, row by row, `size`×`size`.
+pub fn render(size: usize) -> Vec<u8> {
+ let s = size as f32;
+ let radius = s * 0.28;
+ // The glyph fills 62% of the tile, centered; stroke scales with it but
+ // never gets thinner than ~1.4 px so small sizes stay legible.
+ let glyph = s * 0.62;
+ let scale = glyph / 24.0;
+ let offset = (s - glyph) / 2.0;
+ let stroke = (1.8 * scale).max(1.4);
+ let hex: Vec<(f32, f32)> =
+ HEXAGON.iter().map(|&(x, y)| (offset + x * scale, offset + y * scale)).collect();
+ let bar = (
+ (offset + BAR.0.0 * scale, offset + BAR.0.1 * scale),
+ (offset + BAR.1.0 * scale, offset + BAR.1.1 * scale),
+ );
+
+ let mut out = vec![0u8; size * size * 4];
+ for py in 0..size {
+ for px in 0..size {
+ let (mut tile, mut ink) = (0usize, 0usize);
+ for sy in 0..SS {
+ for sx in 0..SS {
+ let x = px as f32 + (sx as f32 + 0.5) / SS as f32;
+ let y = py as f32 + (sy as f32 + 0.5) / SS as f32;
+ if !in_rounded_square(x, y, s, radius) {
+ continue;
+ }
+ tile += 1;
+ let on_hex = (0..hex.len())
+ .any(|i| dist_to_segment((x, y), hex[i], hex[(i + 1) % hex.len()]) <= stroke / 2.0);
+ if on_hex || dist_to_segment((x, y), bar.0, bar.1) <= stroke / 2.0 {
+ ink += 1;
+ }
+ }
+ }
+ let i = (py * size + px) * 4;
+ if tile == 0 {
+ continue;
+ }
+ // Ink over background, then the tile's coverage as alpha.
+ let t = ink as f32 / tile as f32;
+ for c in 0..3 {
+ out[i + c] = (BACKGROUND[c] as f32 * (1.0 - t) + INK[c] as f32 * t).round() as u8;
+ }
+ out[i + 3] = ((tile as f32 / (SS * SS) as f32) * 255.0).round() as u8;
+ }
+ }
+ out
+}
+
+fn in_rounded_square(x: f32, y: f32, size: f32, r: f32) -> bool {
+ let cx = x.clamp(r, size - r);
+ let cy = y.clamp(r, size - r);
+ (x - cx).powi(2) + (y - cy).powi(2) <= r * r
+}
+
+fn dist_to_segment(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 {
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let len2 = dx * dx + dy * dy;
+ let t = if len2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / len2).clamp(0.0, 1.0) };
+ let (qx, qy) = (a.0 + t * dx, a.1 + t * dy);
+ ((p.0 - qx).powi(2) + (p.1 - qy).powi(2)).sqrt()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn pixel(img: &[u8], size: usize, x: usize, y: usize) -> [u8; 4] {
+ let i = (y * size + x) * 4;
+ [img[i], img[i + 1], img[i + 2], img[i + 3]]
+ }
+
+ #[test]
+ fn corners_are_transparent_and_the_tile_is_opaque() {
+ let size = 32;
+ let img = render(size);
+ assert_eq!(img.len(), size * size * 4);
+ assert_eq!(pixel(&img, size, 0, 0)[3], 0, "rounded corner");
+ // Between the hexagon and the tile edge: solid background.
+ assert_eq!(pixel(&img, size, 3, 16), [BACKGROUND[0], BACKGROUND[1], BACKGROUND[2], 255]);
+ // The bar through the middle is (anti-aliased) ink on an opaque tile.
+ let mid = pixel(&img, size, 16, 16);
+ assert!(mid[0] > 200 && mid[3] == 255, "{mid:?}");
+ }
+
+ #[test]
+ fn renders_every_tray_size() {
+ for size in [16, 20, 24, 32, 48, 64, 256] {
+ let img = render(size);
+ assert!(img.chunks(4).any(|p| p[3] == 255), "{size}px has an opaque tile");
+ }
+ }
+}
diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rs
index f57cd48..4e7ef22 100644
--- a/desktop/app/src/notifications.rs
+++ b/desktop/app/src/notifications.rs
@@ -105,6 +105,7 @@ fn show(device: DeviceId, n: &Notification) {
actions: n.actions.iter().filter(|a| !a.reply).map(|a| (a.id.clone(), a.title.clone())).collect(),
reply: reply.map(|a| (a.id.clone(), a.title.clone())),
silent: n.silent,
+ progress: None,
};
toasted(|t| t.entry(device).or_default().insert(n.key.clone()));
toast::show(toast);
@@ -121,6 +122,14 @@ pub fn on_toast(event: ToastEvent) {
return crate::transfers::show_in_folder(std::path::Path::new(key));
}
ToastEvent::Dismissed { device, .. } if device == crate::transfers::TOAST_GROUP => return,
+ // Sends from Explorer: open the app, or cancel.
+ ToastEvent::Action { device, key, action } if device == crate::send_to::TOAST_GROUP => {
+ if action == crate::send_to::ACTION_CANCEL {
+ crate::transfers::cancel(key);
+ }
+ return;
+ }
+ ToastEvent::Dismissed { device, .. } if device == crate::send_to::TOAST_GROUP => return,
_ => {}
}
match event {
diff --git a/desktop/app/src/send_to.rs b/desktop/app/src/send_to.rs
new file mode 100644
index 0000000..2757013
--- /dev/null
+++ b/desktop/app/src/send_to.rs
@@ -0,0 +1,439 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Explorer's "Send to" menu: a shortcut per paired phone, which starts
+//! Nectarlink with `--send-to <device> <files…>`. The running app sends the
+//! files and follows the transfer in a Windows notification with a progress
+//! bar, so nothing else needs to open.
+
+use std::{
+ collections::HashMap,
+ io,
+ path::{Path, PathBuf},
+ sync::{
+ Mutex, MutexGuard,
+ atomic::{AtomicBool, Ordering},
+ },
+ time::{Duration, Instant},
+};
+
+use nectarlink_core::{
+ DeviceId, Error, FileSource, NodeEvent, OutgoingFile, Transfer, TransferFailure, TransferState,
+};
+
+use crate::{
+ bridge::app::{describe, request_activation},
+ core_host,
+ launch::Request,
+ state::{Changes, CoreStatus},
+ win::{
+ shortcut::{self, Shortcut},
+ toast::{self, Progress, Toast},
+ },
+};
+
+/// The command-line option the shortcuts pass.
+pub const ARG: &str = "--send-to";
+/// The toast "device" for sends from Explorer; their key is the transfer ID.
+pub const TOAST_GROUP: &str = "sends";
+/// The toast's "Cancel" action.
+pub const ACTION_CANCEL: &str = "cancel";
+
+/// How long a send from Explorer waits for the app to start.
+const START_TIMEOUT: Duration = Duration::from_secs(60);
+/// Progress bars move at most this often (Windows animates in between).
+const PROGRESS_INTERVAL: Duration = Duration::from_millis(500);
+
+fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
+ m.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+// ---- Shortcuts ----
+
+/// Whether this instance keeps the shortcuts: only the installed app with
+/// its usual data folder, never a test instance with its own.
+static MANAGED: AtomicBool = AtomicBool::new(false);
+/// The "Show your phones in Send to" preference.
+static ENABLED: AtomicBool = AtomicBool::new(true);
+/// The devices the shortcuts were last made for.
+static APPLIED: Mutex<Option<Vec<(DeviceId, String)>>> = Mutex::new(None);
+/// One update of the folder at a time.
+static UPDATING: Mutex<()> = Mutex::new(());
+
+/// Keeps the shortcuts in step with the paired devices from now on.
+pub fn start() {
+ MANAGED.store(true, Ordering::Relaxed);
+ core_host::host().hub.subscribe(Changes::DEVICES | Changes::STATUS, || {
+ sync();
+ true
+ });
+}
+
+pub fn set_enabled(on: bool) {
+ ENABLED.store(on, Ordering::Relaxed);
+ sync();
+}
+
+fn sync() {
+ if !MANAGED.load(Ordering::Relaxed) {
+ return;
+ }
+ let host = core_host::host();
+ // Until the core is up, the device list is empty, not known.
+ let desired = host.hub.read(|s| {
+ matches!(s.status, Some(CoreStatus::Ready { .. }))
+ .then(|| s.devices.iter().map(|d| (d.id, d.info.name.clone())).collect::<Vec<_>>())
+ });
+ let Some(mut desired) = desired else { return };
+ if !ENABLED.load(Ordering::Relaxed) {
+ desired.clear();
+ }
+ {
+ let mut applied = lock(&APPLIED);
+ if applied.as_ref() == Some(&desired) {
+ return;
+ }
+ *applied = Some(desired.clone());
+ }
+ let spawned = std::thread::Builder::new().name("send-to".into()).spawn(move || {
+ let _one = lock(&UPDATING);
+ let (Some(dir), Ok(exe)) = (shortcut::send_to_dir(), std::env::current_exe()) else { return };
+ if let Err(e) = reconcile(&dir, &desired, &exe) {
+ tracing::warn!(error = %e, "can't update the Send to menu");
+ // Try again on the next change.
+ *lock(&APPLIED) = None;
+ }
+ });
+ if let Err(e) = spawned {
+ tracing::warn!(error = %e, "can't update the Send to menu");
+ }
+}
+
+/// Removes this app's shortcuts (when uninstalling).
+pub fn remove_all() -> io::Result<()> {
+ match (shortcut::send_to_dir(), std::env::current_exe()) {
+ (Some(dir), Ok(exe)) => reconcile(&dir, &[], &exe),
+ _ => Ok(()),
+ }
+}
+
+/// Makes `dir` hold exactly one shortcut per device in `desired` (named
+/// after it) and none for any other; other apps' shortcuts are left alone.
+fn reconcile(dir: &Path, desired: &[(DeviceId, String)], exe: &Path) -> io::Result<()> {
+ let mut ours = Vec::new();
+ let mut theirs = Vec::new();
+ for entry in std::fs::read_dir(dir)? {
+ let path = entry?.path();
+ let Some(name) = path.file_name().map(|n| n.to_string_lossy().to_lowercase()) else { continue };
+ let is_ours = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("lnk"))
+ && shortcut::arguments(&path).is_some_and(|a| a.starts_with(&format!("{ARG} ")));
+ if is_ours { ours.push(path) } else { theirs.push(name) }
+ }
+
+ let mut planned: Vec<(PathBuf, Shortcut)> = Vec::new();
+ for (id, name) in desired {
+ let base = file_name(name);
+ let taken = |candidate: &str| {
+ let lower = format!("{candidate}.lnk").to_lowercase();
+ theirs.contains(&lower)
+ || planned
+ .iter()
+ .any(|(p, _)| p.file_name().is_some_and(|n| n.to_string_lossy().to_lowercase() == lower))
+ };
+ let candidate = std::iter::once(base.clone())
+ .chain(std::iter::once(format!("{base} (Nectarlink)")))
+ .chain((2..).map(|n| format!("{base} (Nectarlink {n})")))
+ .find(|c| !taken(c))
+ .expect("an endless list has a free name");
+ planned.push((
+ dir.join(format!("{candidate}.lnk")),
+ Shortcut {
+ target: exe.to_owned(),
+ arguments: format!("{ARG} {id}"),
+ description: format!("Send to {name} with Nectarlink"),
+ },
+ ));
+ }
+
+ for path in ours {
+ let lower = path.to_string_lossy().to_lowercase();
+ if !planned.iter().any(|(p, _)| p.to_string_lossy().to_lowercase() == lower) {
+ std::fs::remove_file(&path)?;
+ }
+ }
+ // Always rewritten: keeps them pointing at this copy of the app.
+ for (path, link) in &planned {
+ shortcut::write(path, link).map_err(io::Error::other)?;
+ }
+ Ok(())
+}
+
+/// A device name as a file name Explorer accepts, and shows as the device.
+fn file_name(device: &str) -> String {
+ let cleaned: String =
+ device.chars().map(|c| if c.is_control() || r#"<>:"/\|?*"#.contains(c) { ' ' } else { c }).collect();
+ let mut name = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");
+ name = name.trim_end_matches(['.', ' ']).chars().take(64).collect();
+ let stem = name.split('.').next().unwrap_or_default().to_ascii_uppercase();
+ let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
+ || ((stem.starts_with("COM") || stem.starts_with("LPT"))
+ && stem.len() == 4
+ && stem.as_bytes()[3].is_ascii_digit());
+ if name.is_empty() {
+ "Phone".into()
+ } else if reserved {
+ format!("{name} phone")
+ } else {
+ name
+ }
+}
+
+// ---- Sending ----
+
+/// What another launch asked for.
+pub fn handle(request: Request) {
+ match request {
+ Request::Show => request_activation(),
+ Request::Quit => crate::bridge::app::request_quit(),
+ Request::Send { device, paths } => send(device, paths),
+ }
+}
+
+/// A send from Explorer, followed in a notification.
+#[derive(Debug)]
+struct Tracked {
+ device_name: String,
+ /// Folders were in the selection; they aren't sent.
+ skipped_folders: bool,
+ shown: Option<(Instant, Progress)>,
+}
+
+static TRACKED: Mutex<Option<HashMap<String, Tracked>>> = Mutex::new(None);
+
+fn send(device: String, paths: Vec<PathBuf>) {
+ core_host::spawn(async move {
+ let Ok(Some(node)) = tokio::time::timeout(START_TIMEOUT, core_host::wait_for_node()).await else {
+ tracing::warn!("files from Explorer weren't sent: the core didn't start");
+ return;
+ };
+ let name = device
+ .parse::<DeviceId>()
+ .ok()
+ .and_then(|id| core_host::host().hub.read(|s| s.name_of(&id)).map(|name| (id, name)));
+ let Some((id, name)) = name else {
+ return failed("Couldn't send", "That device isn't paired with this PC anymore.");
+ };
+ let (files, folders): (Vec<PathBuf>, Vec<PathBuf>) = paths.into_iter().partition(|p| p.is_file());
+ if files.is_empty() {
+ let body = if folders.is_empty() {
+ "Those files can't be found."
+ } else {
+ "Folders can't be sent yet. Choose the files in them instead."
+ };
+ return failed(&format!("Couldn't send to {name}"), body);
+ }
+ let outgoing = files
+ .into_iter()
+ .map(|path| OutgoingFile {
+ name: path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
+ source: FileSource::Path(path),
+ })
+ .collect();
+ match node.send_files(id, outgoing).await {
+ Ok(transfer_id) => track(transfer_id, name, !folders.is_empty()),
+ Err(Error::Denied) => failed(
+ &format!("Couldn't send to {name}"),
+ "Files are turned off for this device. Turn them on in Nectarlink.",
+ ),
+ Err(e) => failed(&format!("Couldn't send to {name}"), &describe(&e)),
+ }
+ });
+}
+
+fn failed(title: &str, body: &str) {
+ toast::show(Toast {
+ device: TOAST_GROUP.into(),
+ key: format!("failed-{title}"),
+ title: title.into(),
+ body: body.into(),
+ attribution: "Nectarlink".into(),
+ icon: None,
+ actions: Vec::new(),
+ reply: None,
+ silent: false,
+ progress: None,
+ });
+}
+
+fn track(id: String, device_name: String, skipped_folders: bool) {
+ let mut tracked = lock(&TRACKED);
+ let map = tracked.get_or_insert_default();
+ map.insert(id.clone(), Tracked { device_name, skipped_folders, shown: None });
+ // Events before this point went to the hub only; catch up from there.
+ let now = core_host::host()
+ .hub
+ .read(|s| s.transfers.iter().find(|t| t.transfer.id == id).map(|t| t.transfer.clone()));
+ if let Some(transfer) = now {
+ update(map, &transfer);
+ }
+}
+
+/// Follows sends from Explorer in their notification.
+pub fn on_event(event: &NodeEvent) {
+ let NodeEvent::Transfer(transfer) = event else { return };
+ let mut tracked = lock(&TRACKED);
+ if let Some(map) = tracked.as_mut() {
+ update(map, transfer);
+ }
+}
+
+fn update(map: &mut HashMap<String, Tracked>, transfer: &Transfer) {
+ let Some(tracked) = map.get_mut(&transfer.id) else { return };
+ let title = match transfer.names.as_slice() {
+ [one] => one.clone(),
+ names => format!("{} files", names.len()),
+ };
+ let device = tracked.device_name.clone();
+ let finished = |title: String, body: String| Toast {
+ device: TOAST_GROUP.into(),
+ key: transfer.id.clone(),
+ title,
+ body,
+ attribution: "Nectarlink".into(),
+ icon: None,
+ actions: Vec::new(),
+ reply: None,
+ silent: false,
+ progress: None,
+ };
+ match &transfer.state {
+ TransferState::Waiting | TransferState::Running => {
+ let progress = Progress {
+ status: if transfer.state == TransferState::Waiting {
+ format!("Waiting for {device}…")
+ } else {
+ format!("Sending to {device}…")
+ },
+ value: (transfer.total > 0).then(|| transfer.done as f64 / transfer.total as f64),
+ label: format!("{} of {}", size(transfer.done), size(transfer.total)),
+ };
+ match &tracked.shown {
+ None => toast::show(Toast {
+ actions: vec![(ACTION_CANCEL.into(), "Cancel".into())],
+ progress: Some(progress.clone()),
+ ..finished(title, String::new())
+ }),
+ Some((at, last))
+ if *last != progress
+ && (at.elapsed() >= PROGRESS_INTERVAL || last.status != progress.status) =>
+ {
+ toast::update_progress(TOAST_GROUP, &transfer.id, progress.clone());
+ }
+ Some(_) => return,
+ }
+ tracked.shown = Some((Instant::now(), progress));
+ }
+ TransferState::Done { .. } => {
+ let mut body = format!("Sent to {device}");
+ if tracked.skipped_folders {
+ body.push_str(". Folders were left out.");
+ }
+ toast::show(finished(title, body));
+ map.remove(&transfer.id);
+ }
+ TransferState::Failed(failure) => {
+ let body = match failure {
+ TransferFailure::Denied => format!("{device} doesn't accept files from this PC."),
+ TransferFailure::Unreachable => format!("Couldn't reach {device}."),
+ TransferFailure::NoSpace => format!("{device} is out of space."),
+ TransferFailure::Interrupted | TransferFailure::Other(_) => {
+ "The transfer didn't go through.".into()
+ }
+ };
+ toast::show(finished(format!("Couldn't send {title}"), body));
+ map.remove(&transfer.id);
+ }
+ TransferState::Cancelled => {
+ toast::remove(TOAST_GROUP, &transfer.id);
+ map.remove(&transfer.id);
+ }
+ }
+}
+
+/// "12.5 MB": decimal units, as Explorer shows them.
+fn size(bytes: u64) -> String {
+ const UNITS: [&str; 5] = ["bytes", "KB", "MB", "GB", "TB"];
+ let mut value = bytes as f64;
+ let mut unit = 0;
+ while value >= 1000.0 && unit < UNITS.len() - 1 {
+ value /= 1000.0;
+ unit += 1;
+ }
+ match unit {
+ 0 => format!("{bytes} bytes"),
+ _ if value < 10.0 => format!("{value:.1} {}", UNITS[unit]),
+ _ => format!("{value:.0} {}", UNITS[unit]),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn device_names_become_file_names() {
+ assert_eq!(file_name("Pixel 9 Pro"), "Pixel 9 Pro");
+ assert_eq!(file_name("Bee's \"phone\": <1/2>?"), "Bee's phone 1 2");
+ assert_eq!(file_name(" phone.. "), "phone");
+ assert_eq!(file_name("\u{7}"), "Phone");
+ assert_eq!(file_name("CON"), "CON phone");
+ assert_eq!(file_name("com1"), "com1 phone");
+ assert_eq!(file_name("Combo"), "Combo");
+ assert_eq!(file_name(&"x".repeat(100)).len(), 64);
+ }
+
+ #[test]
+ fn sizes_read_like_explorer() {
+ assert_eq!(size(0), "0 bytes");
+ assert_eq!(size(999), "999 bytes");
+ assert_eq!(size(1_500), "1.5 KB");
+ assert_eq!(size(12_600_000), "13 MB");
+ assert_eq!(size(3_200_000_000), "3.2 GB");
+ }
+
+ fn names(dir: &Path) -> Vec<String> {
+ let mut names: Vec<String> = std::fs::read_dir(dir)
+ .unwrap()
+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
+ .collect();
+ names.sort();
+ names
+ }
+
+ #[test]
+ fn shortcuts_follow_the_paired_devices() {
+ let dir = tempfile::tempdir().unwrap();
+ let exe = std::env::current_exe().unwrap();
+ // Someone else's entry with a device's name is kept.
+ std::fs::write(dir.path().join("Tab.lnk"), b"not ours").unwrap();
+ let (a, b, c) = (DeviceId([1; 32]), DeviceId([2; 32]), DeviceId([3; 32]));
+
+ reconcile(dir.path(), &[(a, "Pixel".into()), (b, "Tab".into()), (c, "Pixel".into())], &exe).unwrap();
+ assert_eq!(
+ names(dir.path()),
+ ["Pixel (Nectarlink).lnk", "Pixel.lnk", "Tab (Nectarlink).lnk", "Tab.lnk"]
+ );
+ assert_eq!(shortcut::arguments(&dir.path().join("Pixel.lnk")).unwrap(), format!("{ARG} {a}"));
+ assert_eq!(
+ shortcut::arguments(&dir.path().join("Pixel (Nectarlink).lnk")).unwrap(),
+ format!("{ARG} {c}")
+ );
+
+ // Unpairing and renaming.
+ reconcile(dir.path(), &[(c, "Pixel 9".into())], &exe).unwrap();
+ assert_eq!(names(dir.path()), ["Pixel 9.lnk", "Tab.lnk"]);
+ assert_eq!(shortcut::arguments(&dir.path().join("Pixel 9.lnk")).unwrap(), format!("{ARG} {c}"));
+
+ // Turned off.
+ reconcile(dir.path(), &[], &exe).unwrap();
+ assert_eq!(names(dir.path()), ["Tab.lnk"]);
+ }
+}
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
index 058acc0..0164c96 100644
--- a/desktop/app/src/settings.rs
+++ b/desktop/app/src/settings.rs
@@ -43,6 +43,8 @@ pub struct Settings {
pub close_to_tray: bool,
/// Send what's copied on this PC to connected phones.
pub auto_clipboard: bool,
+ /// Paired phones in Explorer's "Send to" menu.
+ pub send_to_menu: bool,
}
impl Default for Settings {
@@ -54,6 +56,7 @@ impl Default for Settings {
backdrop: true,
close_to_tray: true,
auto_clipboard: true,
+ send_to_menu: true,
}
}
}
@@ -114,6 +117,7 @@ mod tests {
backdrop: false,
close_to_tray: false,
auto_clipboard: false,
+ send_to_menu: false,
};
settings.save(dir.path()).unwrap();
assert_eq!(Settings::load(dir.path()), settings);
diff --git a/desktop/app/src/transfers.rs b/desktop/app/src/transfers.rs
index 44f013e..3ca18b4 100644
--- a/desktop/app/src/transfers.rs
+++ b/desktop/app/src/transfers.rs
@@ -88,5 +88,6 @@ pub fn on_event(event: &NodeEvent) {
actions: vec![(ACTION_SHOW.into(), "Show in folder".into())],
reply: None,
silent: false,
+ progress: None,
});
}
diff --git a/desktop/app/src/win/icon.rs b/desktop/app/src/win/icon.rs
index 597e457..6b7cef8 100644
--- a/desktop/app/src/win/icon.rs
+++ b/desktop/app/src/win/icon.rs
@@ -1,84 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-//! The Nectarlink mark (a hexagon on a rounded square, as in the app's nav
-//! rail), drawn in code at any pixel size. Used for the tray and window
-//! icons, so they are sharp at every display scale without bitmap assets.
+//! The app's mark as an image file, for places that want one (the
+//! notification sender icon).
-/// Honey primary (docs/design/tokens.json) and the mark's ink.
-const BACKGROUND: [u8; 3] = [0x8A, 0x51, 0x00];
-const INK: [u8; 3] = [0xFF, 0xFF, 0xFF];
-
-/// Hexagon and bar of the mark, in a 24×24 design grid.
-const HEXAGON: [(f32, f32); 6] =
- [(12.0, 2.5), (20.2, 7.25), (20.2, 16.75), (12.0, 21.5), (3.8, 16.75), (3.8, 7.25)];
-const BAR: ((f32, f32), (f32, f32)) = ((9.0, 12.0), (15.0, 12.0));
-
-/// Supersampling grid per pixel (SS×SS samples) for smooth edges.
-const SS: usize = 4;
-
-/// Renders the mark as straight-alpha RGBA, row by row, `size`×`size`.
-pub fn render(size: usize) -> Vec<u8> {
- let s = size as f32;
- let radius = s * 0.28;
- // The glyph fills 62% of the tile, centered; stroke scales with it but
- // never gets thinner than ~1.4 px so small sizes stay legible.
- let glyph = s * 0.62;
- let scale = glyph / 24.0;
- let offset = (s - glyph) / 2.0;
- let stroke = (1.8 * scale).max(1.4);
- let hex: Vec<(f32, f32)> =
- HEXAGON.iter().map(|&(x, y)| (offset + x * scale, offset + y * scale)).collect();
- let bar = (
- (offset + BAR.0.0 * scale, offset + BAR.0.1 * scale),
- (offset + BAR.1.0 * scale, offset + BAR.1.1 * scale),
- );
-
- let mut out = vec![0u8; size * size * 4];
- for py in 0..size {
- for px in 0..size {
- let (mut tile, mut ink) = (0usize, 0usize);
- for sy in 0..SS {
- for sx in 0..SS {
- let x = px as f32 + (sx as f32 + 0.5) / SS as f32;
- let y = py as f32 + (sy as f32 + 0.5) / SS as f32;
- if !in_rounded_square(x, y, s, radius) {
- continue;
- }
- tile += 1;
- let on_hex = (0..hex.len())
- .any(|i| dist_to_segment((x, y), hex[i], hex[(i + 1) % hex.len()]) <= stroke / 2.0);
- if on_hex || dist_to_segment((x, y), bar.0, bar.1) <= stroke / 2.0 {
- ink += 1;
- }
- }
- }
- let i = (py * size + px) * 4;
- if tile == 0 {
- continue;
- }
- // Ink over background, then the tile's coverage as alpha.
- let t = ink as f32 / tile as f32;
- for c in 0..3 {
- out[i + c] = (BACKGROUND[c] as f32 * (1.0 - t) + INK[c] as f32 * t).round() as u8;
- }
- out[i + 3] = ((tile as f32 / (SS * SS) as f32) * 255.0).round() as u8;
- }
- }
- out
-}
-
-fn in_rounded_square(x: f32, y: f32, size: f32, r: f32) -> bool {
- let cx = x.clamp(r, size - r);
- let cy = y.clamp(r, size - r);
- (x - cx).powi(2) + (y - cy).powi(2) <= r * r
-}
-
-fn dist_to_segment(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 {
- let (dx, dy) = (b.0 - a.0, b.1 - a.1);
- let len2 = dx * dx + dy * dy;
- let t = if len2 == 0.0 { 0.0 } else { (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / len2).clamp(0.0, 1.0) };
- let (qx, qy) = (a.0 + t * dx, a.1 + t * dy);
- ((p.0 - qx).powi(2) + (p.1 - qy).powi(2)).sqrt()
-}
+use crate::mark::render;
/// Writes the mark as a PNG file (for places that want an image file, such
/// as the notification sender icon).
@@ -121,33 +45,3 @@ pub fn write_png(path: &std::path::Path, size: u32) -> windows::core::Result<()>
encoder.Commit()
}
}
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn pixel(img: &[u8], size: usize, x: usize, y: usize) -> [u8; 4] {
- let i = (y * size + x) * 4;
- [img[i], img[i + 1], img[i + 2], img[i + 3]]
- }
-
- #[test]
- fn corners_are_transparent_and_the_tile_is_opaque() {
- let size = 32;
- let img = render(size);
- assert_eq!(img.len(), size * size * 4);
- assert_eq!(pixel(&img, size, 0, 0)[3], 0, "rounded corner");
- // Between the hexagon and the tile edge: solid background.
- assert_eq!(pixel(&img, size, 3, 16), [BACKGROUND[0], BACKGROUND[1], BACKGROUND[2], 255]);
- // The bar through the middle is (anti-aliased) ink on an opaque tile.
- let mid = pixel(&img, size, 16, 16);
- assert!(mid[0] > 200 && mid[3] == 255, "{mid:?}");
- }
-
- #[test]
- fn renders_every_tray_size() {
- for size in [16, 20, 24, 32, 48, 64, 256] {
- let img = render(size);
- assert!(img.chunks(4).any(|p| p[3] == 255), "{size}px has an opaque tile");
- }
- }
-}
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
index 6b6d690..77be6c2 100644
--- a/desktop/app/src/win/mod.rs
+++ b/desktop/app/src/win/mod.rs
@@ -8,6 +8,7 @@
pub mod clipboard;
pub mod icon;
pub mod net;
+pub mod shortcut;
pub mod single_instance;
pub mod sound;
pub mod toast;
diff --git a/desktop/app/src/win/shortcut.rs b/desktop/app/src/win/shortcut.rs
new file mode 100644
index 0000000..103624a
--- /dev/null
+++ b/desktop/app/src/win/shortcut.rs
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Shell shortcuts (.lnk files), and where Explorer's "Send to" menu lives.
+
+use std::path::{Path, PathBuf};
+
+use windows::{
+ Win32::{
+ System::Com::{
+ CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree,
+ CoUninitialize, IPersistFile,
+ },
+ UI::Shell::{FOLDERID_SendTo, IShellLinkW, KF_FLAG_DEFAULT, SHGetKnownFolderPath, ShellLink},
+ },
+ core::{HSTRING, Interface},
+};
+
+/// What a shortcut starts.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Shortcut {
+ pub target: PathBuf,
+ pub arguments: String,
+ /// The tooltip.
+ pub description: String,
+}
+
+/// Runs `f` with COM available on this thread.
+fn with_com<T>(f: impl FnOnce() -> T) -> T {
+ // SAFETY: balanced below; if the thread already has COM in another mode
+ // (RPC_E_CHANGED_MODE), it's usable as is and isn't uninitialized here.
+ let initialized = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }.is_ok();
+ let result = f();
+ if initialized {
+ // SAFETY: pairs with the successful CoInitializeEx above.
+ unsafe { CoUninitialize() };
+ }
+ result
+}
+
+/// Writes (or replaces) a shortcut at `path`, with the target's own icon.
+pub fn write(path: &Path, shortcut: &Shortcut) -> windows::core::Result<()> {
+ with_com(|| {
+ // SAFETY: plain COM calls on a live ShellLink object; the strings
+ // outlive the calls.
+ unsafe {
+ let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?;
+ link.SetPath(&HSTRING::from(shortcut.target.as_os_str()))?;
+ link.SetArguments(&HSTRING::from(shortcut.arguments.as_str()))?;
+ link.SetDescription(&HSTRING::from(shortcut.description.as_str()))?;
+ link.SetIconLocation(&HSTRING::from(shortcut.target.as_os_str()), 0)?;
+ link.cast::<IPersistFile>()?.Save(&HSTRING::from(path.as_os_str()), true)
+ }
+ })
+}
+
+/// The arguments a shortcut passes, or `None` if it can't be read.
+pub fn arguments(path: &Path) -> Option<String> {
+ with_com(|| {
+ // SAFETY: as in `write`; the buffer is large enough for any
+ // shortcut's arguments (INFOTIPSIZE is 1024).
+ unsafe {
+ let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?;
+ link.cast::<IPersistFile>()
+ .ok()?
+ .Load(&HSTRING::from(path.as_os_str()), Default::default())
+ .ok()?;
+ let mut buffer = [0u16; 4096];
+ link.GetArguments(&mut buffer).ok()?;
+ let len = buffer.iter().position(|&c| c == 0).unwrap_or(buffer.len());
+ Some(String::from_utf16_lossy(&buffer[..len]))
+ }
+ })
+}
+
+/// The user's "Send to" folder.
+pub fn send_to_dir() -> Option<PathBuf> {
+ // SAFETY: the returned string is freed with CoTaskMemFree as documented.
+ unsafe {
+ let path = SHGetKnownFolderPath(&FOLDERID_SendTo, KF_FLAG_DEFAULT, None).ok()?;
+ let result = path.to_string().ok().map(PathBuf::from);
+ CoTaskMemFree(Some(path.as_ptr().cast()));
+ result
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn shortcuts_round_trip() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("Pixel 9 é.lnk");
+ let shortcut = Shortcut {
+ target: std::env::current_exe().unwrap(),
+ arguments: r#"--send-to abc --data-dir "C:\some dir""#.into(),
+ description: "Send to Pixel".into(),
+ };
+ write(&path, &shortcut).unwrap();
+ assert_eq!(arguments(&path).as_deref(), Some(shortcut.arguments.as_str()));
+ // Replacing works too.
+ write(&path, &Shortcut { arguments: "--send-to def".into(), ..shortcut }).unwrap();
+ assert_eq!(arguments(&path).as_deref(), Some("--send-to def"));
+ assert_eq!(arguments(&dir.path().join("missing.lnk")), None);
+ }
+
+ #[test]
+ fn finds_the_send_to_folder() {
+ let dir = send_to_dir().expect("every user has one");
+ assert!(dir.ends_with("SendTo"), "{}", dir.display());
+ }
+}
diff --git a/desktop/app/src/win/single_instance.rs b/desktop/app/src/win/single_instance.rs
index da8cd4e..982a4e2 100644
--- a/desktop/app/src/win/single_instance.rs
+++ b/desktop/app/src/win/single_instance.rs
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! One Nectarlink per user session and data folder. A second launch (from
-//! the Start menu, a shortcut or a jump list) asks the running one to show
-//! its window and exits.
+//! the Start menu, a shortcut or Explorer's "Send to") leaves its request
+//! (`crate::launch`), wakes the running one with [`wake`] and exits.
use std::{
hash::{DefaultHasher, Hash, Hasher},
@@ -35,7 +35,7 @@ unsafe impl Sync for PrimaryInstance {}
#[derive(Debug)]
pub enum Instance {
Primary(PrimaryInstance),
- /// Another instance is running and was asked to show itself.
+ /// Another instance is running.
Secondary,
}
@@ -59,14 +59,6 @@ pub fn acquire(data_dir: &Path) -> windows::core::Result<Instance> {
let mutex = CreateMutexW(None, true, &mutex_name)?;
if GetLastError() == ERROR_ALREADY_EXISTS {
let _ = CloseHandle(mutex);
- // We were just launched by the user, so we may take the
- // foreground; pass that right on so the running instance's
- // window comes to the front instead of only flashing.
- let _ = AllowSetForegroundWindow(ASFW_ANY);
- if let Ok(event) = OpenEventW(EVENT_MODIFY_STATE, false, &event_name) {
- let _ = SetEvent(event);
- let _ = CloseHandle(event);
- }
return Ok(Instance::Secondary);
}
// Auto-reset: each SetEvent wakes the waiter once.
@@ -75,9 +67,25 @@ pub fn acquire(data_dir: &Path) -> windows::core::Result<Instance> {
}
}
+/// Wakes the running instance (after leaving it a request).
+pub fn wake(data_dir: &Path) {
+ let (_, event_name) = names(data_dir);
+ // SAFETY: plain kernel object calls; the handle is closed right away.
+ unsafe {
+ // We were just launched by the user, so we may take the foreground;
+ // pass that right on so the running instance's window comes to the
+ // front instead of only flashing.
+ let _ = AllowSetForegroundWindow(ASFW_ANY);
+ if let Ok(event) = OpenEventW(EVENT_MODIFY_STATE, false, &event_name) {
+ let _ = SetEvent(event);
+ let _ = CloseHandle(event);
+ }
+ }
+}
+
impl PrimaryInstance {
/// Calls `on_activate` (on a background thread) whenever another launch
- /// asks this instance to show itself.
+ /// wakes this instance.
pub fn watch(&'static self, on_activate: impl Fn() + Send + 'static) {
let spawned = std::thread::Builder::new().name("single-instance".into()).spawn(move || {
loop {
@@ -110,11 +118,13 @@ mod tests {
use super::*;
#[test]
- fn second_acquire_is_secondary_and_activates_the_first() {
+ fn second_acquire_is_secondary_and_wakes_the_first() {
let dir = tempfile::tempdir().unwrap();
let Instance::Primary(primary) = acquire(dir.path()).unwrap() else { panic!("first is primary") };
assert!(matches!(acquire(dir.path()).unwrap(), Instance::Secondary));
- // The secondary set the activation event.
+ // SAFETY: as below.
+ assert_ne!(unsafe { WaitForSingleObject(primary.activate, 0) }, WAIT_OBJECT_0, "not woken yet");
+ wake(dir.path());
// SAFETY: the handle is owned by `primary`, alive for this call.
assert_eq!(unsafe { WaitForSingleObject(primary.activate, 0) }, WAIT_OBJECT_0);
drop(primary);
diff --git a/desktop/app/src/win/toast.rs b/desktop/app/src/win/toast.rs
index 6339dc1..4627289 100644
--- a/desktop/app/src/win/toast.rs
+++ b/desktop/app/src/win/toast.rs
@@ -18,15 +18,16 @@ use windows::{
Data::Xml::Dom::XmlDocument,
Foundation::{IPropertyValue, TypedEventHandler},
UI::Notifications::{
- NotificationSetting, ToastActivatedEventArgs, ToastDismissalReason, ToastDismissedEventArgs,
- ToastNotification, ToastNotificationManager, ToastNotifier,
+ NotificationData, NotificationSetting, ToastActivatedEventArgs, ToastDismissalReason,
+ ToastDismissedEventArgs, ToastNotification, ToastNotificationManager, ToastNotifier,
},
Win32::{
+ Foundation::ERROR_FILE_NOT_FOUND,
System::{
Com::{COINIT_MULTITHREADED, CoInitializeEx},
Registry::{
HKEY, HKEY_CURRENT_USER, KEY_WRITE, REG_OPTION_NON_VOLATILE, REG_SZ, RegCloseKey,
- RegCreateKeyExW, RegSetValueExW,
+ RegCreateKeyExW, RegDeleteTreeW, RegSetValueExW,
},
},
UI::Shell::SetCurrentProcessExplicitAppUserModelID,
@@ -67,6 +68,19 @@ pub struct Toast {
/// `(action id, placeholder)` for an inline reply.
pub reply: Option<(String, String)>,
pub silent: bool,
+ /// A progress bar, updated in place with [`update_progress`].
+ pub progress: Option<Progress>,
+}
+
+/// A toast's progress bar.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Progress {
+ /// Under the bar, on the left ("Sending…").
+ pub status: String,
+ /// 0 to 1, or `None` while it's not known yet.
+ pub value: Option<f64>,
+ /// Under the bar, on the right ("12 MB of 80 MB").
+ pub label: String,
}
impl std::fmt::Debug for Toast {
@@ -79,6 +93,7 @@ enum Command {
Show(Box<Toast>),
Remove { device: String, key: String },
RemoveDevice { device: String },
+ Progress { device: String, key: String, progress: Progress },
}
type Handler = Box<dyn Fn(ToastEvent) + Send + Sync>;
@@ -130,6 +145,11 @@ pub fn show(toast: Toast) {
send(Command::Show(Box::new(toast)));
}
+/// Moves a shown toast's progress bar, without showing the toast again.
+pub fn update_progress(device: &str, key: &str, progress: Progress) {
+ send(Command::Progress { device: device.to_owned(), key: key.to_owned(), progress });
+}
+
pub fn remove(device: &str, key: &str) {
send(Command::Remove { device: device.to_owned(), key: key.to_owned() });
}
@@ -139,10 +159,26 @@ pub fn remove_device(device: &str) {
send(Command::RemoveDevice { device: device.to_owned() });
}
+fn registration_key() -> HSTRING {
+ HSTRING::from(format!(r"Software\Classes\AppUserModelId\{AUMID}"))
+}
+
+/// Removes the registration (when uninstalling), and the app's toasts.
+pub fn unregister() {
+ if let Ok(history) = ToastNotificationManager::History() {
+ let _ = history.ClearWithId(&HSTRING::from(AUMID));
+ }
+ // SAFETY: deletes a key under HKCU by a valid path.
+ let result = unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, &registration_key()) };
+ if result.is_err() && result != ERROR_FILE_NOT_FOUND {
+ tracing::warn!(error = ?result, "can't remove the notification registration");
+ }
+}
+
/// `HKCU\Software\Classes\AppUserModelId\<AUMID>`: how Windows names the
/// sender of toasts from an unpackaged app.
fn register(icon: &Path) -> windows::core::Result<()> {
- let key_path = HSTRING::from(format!(r"Software\Classes\AppUserModelId\{AUMID}"));
+ let key_path = registration_key();
let mut key = HKEY::default();
// SAFETY: creating/opening a key under HKCU with a valid path; the handle
// is closed below.
@@ -225,6 +261,11 @@ fn run(icon: &Path, queue: mpsc::Receiver<Command>, handler: Handler) {
Some(h) => h.RemoveGroupWithId(&HSTRING::from(group(&device)), &aumid),
None => Ok(()),
},
+ Command::Progress { device, key, progress } => progress_data(&progress).and_then(|data| {
+ notifier
+ .UpdateWithTagAndGroup(&data, &HSTRING::from(tag(&key)), &HSTRING::from(group(&device)))
+ .map(drop)
+ }),
};
if let Err(e) = result {
tracing::debug!(error = %e, "toast command failed");
@@ -240,6 +281,9 @@ fn show_now(notifier: &ToastNotifier, toast: Toast, handler: &'static Handler) -
notification.SetGroup(&HSTRING::from(group(&toast.device)))?;
// Silent on the phone: straight to the notification center, no pop-up.
notification.SetSuppressPopup(toast.silent)?;
+ if let Some(progress) = &toast.progress {
+ notification.SetData(&progress_data(progress)?)?;
+ }
let (device, key) = (toast.device.clone(), toast.key.clone());
notification.Activated(&TypedEventHandler::<ToastNotification, IInspectable>::new(move |_, args| {
@@ -278,6 +322,22 @@ fn show_now(notifier: &ToastNotifier, toast: Toast, handler: &'static Handler) -
notifier.Show(&notification)
}
+/// The values bound into a toast's progress bar.
+fn progress_data(progress: &Progress) -> windows::core::Result<NotificationData> {
+ let data = NotificationData::new()?;
+ let values = data.Values()?;
+ let value =
+ progress.value.map_or_else(|| "indeterminate".to_owned(), |v| format!("{:.3}", v.clamp(0.0, 1.0)));
+ values.Insert(&HSTRING::from(PROGRESS_VALUE), &HSTRING::from(value))?;
+ values.Insert(&HSTRING::from(PROGRESS_STATUS), &HSTRING::from(&progress.status))?;
+ values.Insert(&HSTRING::from(PROGRESS_LABEL), &HSTRING::from(&progress.label))?;
+ Ok(data)
+}
+
+const PROGRESS_VALUE: &str = "progressValue";
+const PROGRESS_STATUS: &str = "progressStatus";
+const PROGRESS_LABEL: &str = "progressLabel";
+
/// The text typed in the reply field, if any.
fn reply_text(args: &ToastActivatedEventArgs) -> Option<String> {
let value = args.UserInput().ok()?.Lookup(&HSTRING::from(REPLY_INPUT)).ok()?;
@@ -325,6 +385,11 @@ fn toast_xml(toast: &Toast) -> String {
xml.push_str(&format!("<text>{}</text>", escape(&toast.body)));
}
xml.push_str(&format!(r#"<text placement="attribution">{}</text>"#, escape(&toast.attribution)));
+ if toast.progress.is_some() {
+ xml.push_str(&format!(
+ r#"<progress value="{{{PROGRESS_VALUE}}}" status="{{{PROGRESS_STATUS}}}" valueStringOverride="{{{PROGRESS_LABEL}}}"/>"#
+ ));
+ }
if let Some(icon) = &toast.icon {
xml.push_str(&format!(
r#"<image placement="appLogoOverride" src="{}"/>"#,
@@ -373,6 +438,7 @@ mod tests {
actions: (0..6).map(|i| (i.to_string(), format!("Action {i}"))).collect(),
reply: Some(("r".into(), "Reply".into())),
silent: true,
+ progress: None,
}
}
@@ -389,6 +455,23 @@ mod tests {
XmlDocument::new().unwrap().LoadXml(&HSTRING::from(xml)).expect("well-formed XML");
}
+ #[test]
+ fn progress_bars_are_bound_to_data() {
+ let toast = Toast {
+ progress: Some(Progress { status: "Sending…".into(), value: None, label: String::new() }),
+ ..toast()
+ };
+ let xml = toast_xml(&toast);
+ assert!(
+ xml.contains(r#"<progress value="{progressValue}" status="{progressStatus}" valueStringOverride="{progressLabel}"/>"#),
+ "{xml}"
+ );
+ XmlDocument::new().unwrap().LoadXml(&HSTRING::from(xml)).expect("well-formed XML");
+ let data =
+ progress_data(&Progress { status: "s".into(), value: Some(1.5), label: "l".into() }).unwrap();
+ assert_eq!(data.Values().unwrap().Lookup(&HSTRING::from(PROGRESS_VALUE)).unwrap(), "1.000");
+ }
+
#[test]
fn tags_are_short_and_stable() {
assert_eq!(tag("a"), tag("a"));
diff --git a/desktop/app/src/win/tray.rs b/desktop/app/src/win/tray.rs
index a73b45e..307517b 100644
--- a/desktop/app/src/win/tray.rs
+++ b/desktop/app/src/win/tray.rs
@@ -194,7 +194,7 @@ fn add_icon(hwnd: HWND) {
fn create_icon() -> windows::core::Result<HICON> {
// SAFETY: GetSystemMetrics has no preconditions.
let size = unsafe { GetSystemMetrics(SM_CXSMICON) }.clamp(16, 64) as usize;
- let rgba = super::icon::render(size);
+ let rgba = crate::mark::render(size);
// SAFETY: a top-down 32-bit DIB of `size`×`size`; we write exactly
// size*size*4 bytes into its pixel buffer, then hand both bitmaps to
// CreateIconIndirect, which copies them, and delete ours.