Skip to content

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

Lock or sleep the PC from the phone, and hand links over

Beee2da71421c34
diff --git a/.gitignore b/.gitignore
index f09fc21..537ae38 100644
--- a/.gitignore
+++ b/.gitignore
@@ -56,3 +56,6 @@ desktop.ini
# ---- Logs and tool output ----
*.log
aqtinstall.log
+
+# Kotlin compiler session data
+.kotlin/
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt
index 3bd2633..3252195 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/clipboard/SendActivity.kt
@@ -36,6 +36,7 @@ class SendActivity : Activity() {
val text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString()
when {
stream != null -> sendFiles(listOf(stream))
+ !text.isNullOrBlank() && webLink(text) != null -> sendLink(webLink(text)!!, text)
!text.isNullOrBlank() -> send(text)
else -> finishWith(getString(R.string.clip_nothing_shared))
}
@@ -81,6 +82,28 @@ class SendActivity : Activity() {
}
}
+ /**
+ * A shared link opens on the PC (the one that takes links; the user
+ * picks when there are several). With no such PC, it goes to the
+ * clipboard like other text.
+ */
+ private fun sendLink(url: String, text: String) {
+ sent = true
+ val core = (application as NectarlinkApplication).core
+ val pcs = core.state.value.devices.filter { it.online && it.has("device.links_to_pc") }
+ when (pcs.size) {
+ 0 -> send(text)
+ 1 -> scope.launch { finishWith(core.openLinkOnPc(pcs[0].id, url)) }
+ else -> AlertDialog.Builder(this)
+ .setTitle(R.string.link_pick_pc)
+ .setItems(pcs.map { it.name }.toTypedArray()) { _, which ->
+ scope.launch { finishWith(core.openLinkOnPc(pcs[which].id, url)) }
+ }
+ .setOnCancelListener { finish() }
+ .show()
+ }
+ }
+
private fun send(text: String) {
sent = true
val core = (application as NectarlinkApplication).core
@@ -105,6 +128,16 @@ class SendActivity : Activity() {
}
companion object {
+ /** The text as a web link, if it's one (apps often share "Title https://…"). */
+ fun webLink(text: String): String? {
+ val words = text.trim().split(Regex("\\s+"))
+ val link = words.lastOrNull() ?: return null
+ val lower = link.lowercase()
+ val web = (lower.startsWith("https://") || lower.startsWith("http://")) && link.length in 9..4096
+ // Only when the link is the point: alone, or after a short title.
+ return link.takeIf { web && words.size <= 12 }
+ }
+
const val ACTION_SEND_CLIPBOARD = "app.nectarlink.action.SEND_CLIPBOARD"
fun sendClipboardIntent(context: Context): Intent =
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
index aa2d0a7..f12fadd 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
@@ -8,6 +8,7 @@ import android.util.Log
import android.net.Uri
import app.nectarlink.android.BuildConfig
import app.nectarlink.android.clipboard.PhoneClipboard
+import app.nectarlink.android.links.LinkNotifications
import app.nectarlink.android.media.PcMedia
import app.nectarlink.android.media.PhoneMedia
import app.nectarlink.android.files.OutgoingFiles
@@ -55,7 +56,9 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
private val phoneMedia = PhoneMedia(this.context) { players ->
notificationOps.trySend { it.mediaChanged(players) }
}
- private val platform = PhonePlatform(this.context, ringer, phoneMedia)
+ private val platform = PhonePlatform(this.context, ringer, phoneMedia) { pc, url ->
+ LinkNotifications.show(this.context, _state.value.nameOf(pc).orEmpty(), url)
+ }
/** What plays on the PCs, in Android's media controls. */
val pcMedia = PcMedia(this.context) { pc, player, action, position ->
@@ -341,6 +344,34 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
fun ring(id: String, on: Boolean) = command { it.ring(id, on) }
+ /** Locks a PC, or puts it to sleep; says how it went. */
+ fun pcPower(id: String, sleep: Boolean) {
+ val node = node ?: return
+ val name = _state.value.nameOf(id).orEmpty()
+ scope.launch {
+ val message = try {
+ node.pcPower(id, sleep)
+ context.getString(if (sleep) R.string.pc_sleeping else R.string.pc_locked, name)
+ } catch (e: NectarlinkException) {
+ if (e is NectarlinkException.Denied) context.getString(R.string.pc_actions_off, name) else describe(e)
+ }
+ _messages.tryEmit(message)
+ }
+ }
+
+ /** Opens a link on a PC; returns what to tell the user. */
+ suspend fun openLinkOnPc(id: String, url: String): String {
+ startJob?.join()
+ val node = node ?: return context.getString(R.string.clip_no_pc)
+ val name = _state.value.nameOf(id).orEmpty()
+ return try {
+ node.openLink(id, url)
+ context.getString(R.string.link_opened_on, name)
+ } catch (e: NectarlinkException) {
+ describe(e)
+ }
+ }
+
/** Reconnects to PCs that aren't connected and syncs connected ones. */
fun refresh() {
refreshNotificationAccess()
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
index 37f844b..7c61b2e 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
@@ -45,6 +45,10 @@ data class Device(
val features: List<Feature> = emptyList(),
) {
val online: Boolean get() = link is Link.Online
+
+ /** Whether a feature works with this device now (the capability matrix). */
+ fun has(feature: String): Boolean =
+ features.any { it.id == feature && it.status is app.nectarlink.core.FeatureStatus.Available }
}
/** Everything the UI renders, folded from core events. */
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
index ca7afa1..e565a0f 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
@@ -23,6 +23,8 @@ internal class PhonePlatform(
context: Context,
private val ringer: Ringer,
private val media: PhoneMedia,
+ /** Shows a link a PC sent: (PC's ID, link) → shown. */
+ private val onLink: (String, String) -> Boolean,
) : Platform {
private val context = context.applicationContext
@@ -38,6 +40,8 @@ internal class PhonePlatform(
override fun mediaCommand(player: String, action: MediaAction, position: ULong?) =
media.command(player, action, position)
+ override fun openLink(fromId: String, url: String): Boolean = onLink(fromId, url)
+
override fun dismissNotification(key: String) {
val listener = NotificationListener.instance ?: throw NotificationFailure.Unsupported()
listener.dismiss(key)
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/links/LinkNotifications.kt b/android/app/src/main/kotlin/app/nectarlink/android/links/LinkNotifications.kt
new file mode 100644
index 0000000..1c08579
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/links/LinkNotifications.kt
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.links
+
+import android.Manifest
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import androidx.core.net.toUri
+import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
+import androidx.core.content.ContextCompat
+import app.nectarlink.android.R
+
+/**
+ * Links a PC sent: Android doesn't let an app in the background open
+ * screens, so each link waits in a notification the user taps to open.
+ */
+object LinkNotifications {
+ private const val CHANNEL = "links"
+ private const val TAG = "link"
+
+ fun createChannel(context: Context) {
+ context.getSystemService(NotificationManager::class.java).createNotificationChannel(
+ NotificationChannel(CHANNEL, context.getString(R.string.channel_links), NotificationManager.IMPORTANCE_HIGH),
+ )
+ }
+
+ /** Shows a link from a PC; false if notifications are off for the app. */
+ fun show(context: Context, pcName: String, url: String): Boolean {
+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=
+ PackageManager.PERMISSION_GRANTED
+ ) {
+ return false
+ }
+ val uri = url.toUri()
+ val open = PendingIntent.getActivity(
+ context,
+ url.hashCode(),
+ Intent(Intent.ACTION_VIEW, uri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ // "example.com/path", without the scheme, reads better.
+ val shown = url.substringAfter("://").removeSuffix("/")
+ val notification = NotificationCompat.Builder(context, CHANNEL)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setContentTitle(context.getString(R.string.link_from, pcName.ifEmpty { context.getString(R.string.your_pc) }))
+ .setContentText(shown)
+ .setStyle(NotificationCompat.BigTextStyle().bigText(shown))
+ .setContentIntent(open)
+ .setAutoCancel(true)
+ .setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)
+ .setPriority(NotificationCompat.PRIORITY_HIGH)
+ .build()
+ return runCatching { NotificationManagerCompat.from(context).notify(TAG, url.hashCode(), notification) }.isSuccess
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
index 0d3d4a5..ca268be 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
@@ -38,6 +38,7 @@ class ConnectionService : LifecycleService() {
createChannels(this)
app.nectarlink.android.files.TransferNotifications.createChannels(this)
app.nectarlink.android.media.PcMedia.createChannel(this)
+ app.nectarlink.android.links.LinkNotifications.createChannel(this)
val core = (application as NectarlinkApplication).core
startInForeground(core.state.value)
multicastLock = getSystemService(WifiManager::class.java)
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
index 21a69e7..dbb2df1 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
@@ -163,6 +163,7 @@ private fun App(core: Core, state: CoreState, preferences: Preferences) {
core::stopRinging,
onPairNew = { pairing = true },
onRefresh = core::refresh,
+ onPower = core::pcPower,
onSendFiles = core::sendFiles,
onCancelTransfer = core::cancelTransfer,
modifier = modifier,
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
index cd8e3f6..cf30381 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
@@ -29,6 +29,7 @@ import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -70,6 +71,7 @@ fun HomeScreen(
onStopRinging: () -> Unit,
onPairNew: () -> Unit,
onRefresh: () -> Unit,
+ onPower: (pcId: String, sleep: Boolean) -> Unit,
onSendFiles: (pcId: String, uris: List<Uri>) -> Unit,
onCancelTransfer: (id: String) -> Unit,
modifier: Modifier = Modifier,
@@ -128,7 +130,7 @@ fun HomeScreen(
) { context.startActivity(NotificationListener.settingsIntent(context)) }
}
}
- items(state.devices, key = { it.id }) { device -> PcCard(device, onRing, onSendFiles) }
+ items(state.devices, key = { it.id }) { device -> PcCard(device, onRing, onSendFiles, onPower) }
if (state.transfers.isNotEmpty()) {
item { TransfersCard(state, onCancelTransfer) }
}
@@ -165,7 +167,12 @@ private fun RingingBanner(from: String, onStop: () -> Unit) {
}
@Composable
-private fun PcCard(device: Device, onRing: (String, Boolean) -> Unit, onSendFiles: (String, List<Uri>) -> Unit) {
+private fun PcCard(
+ device: Device,
+ onRing: (String, Boolean) -> Unit,
+ onSendFiles: (String, List<Uri>) -> Unit,
+ onPower: (String, Boolean) -> Unit,
+) {
val pickFiles = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
if (uris.isNotEmpty()) onSendFiles(device.id, uris)
}
@@ -227,6 +234,14 @@ private fun PcCard(device: Device, onRing: (String, Boolean) -> Unit, onSendFile
FilledTonalButton(enabled = device.online, onClick = { pickFiles.launch(arrayOf("*/*")) }) {
Text(stringResource(R.string.action_send_files))
}
+ if (device.has("device.pc_actions")) {
+ OutlinedButton(enabled = device.online, onClick = { onPower(device.id, false) }) {
+ Text(stringResource(R.string.action_lock_pc))
+ }
+ OutlinedButton(enabled = device.online, onClick = { onPower(device.id, true) }) {
+ Text(stringResource(R.string.action_sleep_pc))
+ }
+ }
}
}
}
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index 4928fbb..1fc9abe 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -120,6 +120,15 @@
<string name="action_unpair">Unpair</string>
<string name="action_pair_new">Pair another PC</string>
<string name="action_refresh">Refresh</string>
+ <string name="action_lock_pc">Lock PC</string>
+ <string name="action_sleep_pc">Sleep</string>
+ <string name="pc_locked">%1$s is locked.</string>
+ <string name="pc_sleeping">%1$s is going to sleep.</string>
+ <string name="pc_actions_off">Locking and sleep are turned off for this phone on %1$s.</string>
+ <string name="channel_links">Links from your PC</string>
+ <string name="link_from">Link from %1$s</string>
+ <string name="link_opened_on">Opened on %1$s</string>
+ <string name="link_pick_pc">Open on which PC?</string>
<!-- Notifications -->
<string name="channel_connection">Connection</string>
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index ae404a8..7ff8ae9 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -11,8 +11,8 @@ use clap::{Parser, Subcommand, ValueEnum};
use nectarlink_core::{
Battery, ConnectionPath, DeviceId, DeviceInfo, DeviceKind, Direction, FeatureState, FileSource,
LinkState, MediaAction, MediaError, MediaPlayer, Node, NodeConfig, NodeEvent, Notification,
- NotificationAction, NotificationError, OutgoingFile, PairedDevice, PairingEvent, Platform, PowerLevel,
- TransferState,
+ NotificationAction, NotificationError, OutgoingFile, PairedDevice, PairingEvent, Platform, PowerAction,
+ PowerLevel, TransferState,
features::{Effort, FEATURES, Role, UnsupportedReason, Upgrade, UpgradeAction},
};
use tokio::sync::broadcast::error::RecvError;
@@ -154,6 +154,14 @@ enum Command {
#[arg(long, required_if_eq("action", "seek"))]
position: Option<u64>,
},
+ /// Lock a paired PC, or put it to sleep.
+ Power {
+ device: String,
+ #[arg(value_enum)]
+ action: PowerArg,
+ },
+ /// Open a web link on a paired device.
+ Open { device: String, url: String },
/// Pretend to play a song and share it with paired devices, which can
/// control it; stays online until Ctrl+C.
Play {
@@ -192,6 +200,12 @@ enum Power {
Elevated,
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
+enum PowerArg {
+ Lock,
+ Sleep,
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum MediaCommandArg {
Play,
@@ -262,6 +276,14 @@ impl Platform for TerminalPlatform {
let sender = MEDIA_COMMANDS.get().ok_or(MediaError::NotFound)?;
sender.send((action, position)).map_err(|_| MediaError::NotFound)
}
+ fn open_link(&self, _from: &DeviceId, url: &str) -> Result<(), String> {
+ println!("A paired device sent a link: {url}");
+ Ok(())
+ }
+ fn power(&self, action: PowerAction) -> Result<(), String> {
+ println!("A paired device asked this computer to {} (not done: this is the CLI)", action.as_str());
+ Ok(())
+ }
fn dismiss_notification(&self, key: &str) -> Result<(), NotificationError> {
println!("The PC dismissed {key}");
Ok(())
@@ -459,6 +481,22 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
println!("{name} is now {}", if on { "on" } else { "off" });
}
Command::Run => watch(node).await?,
+ Command::Power { device, action } => {
+ let id = resolve(node, device)?;
+ wait_until_online(node, id).await?;
+ let action = match action {
+ PowerArg::Lock => PowerAction::Lock,
+ PowerArg::Sleep => PowerAction::Sleep,
+ };
+ node.pc_power(id, action).await.context("the PC didn't do it")?;
+ println!("Done.");
+ }
+ Command::Open { device, url } => {
+ let id = resolve(node, device)?;
+ wait_until_online(node, id).await?;
+ node.open_link(id, url.clone()).await.context("the link didn't open")?;
+ println!("Opened.");
+ }
Command::Media { device, action, player, position } => {
let id = resolve(node, device)?;
wait_until_online(node, id).await?;
diff --git a/core/nectarlink-core/src/actions.rs b/core/nectarlink-core/src/actions.rs
new file mode 100644
index 0000000..72cf497
--- /dev/null
+++ b/core/nectarlink-core/src/actions.rs
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: MPL-2.0
+//! One-shot actions on a paired device (docs/protocol/actions.md): lock or
+//! sleep a PC, and open a link on the other device.
+
+use std::sync::Arc;
+
+use nectarlink_protocol::{
+ DeviceId, Envelope, ErrorCode,
+ messages::{LinkOpen, PcPower, types},
+};
+
+use crate::{Error, Result, node::Shared, session::Session};
+
+/// The device toggle that lets a phone lock or sleep this PC.
+pub(crate) const POWER_TOGGLE: &str = "pc_actions";
+/// Offered by PCs that lock and sleep on request.
+pub(crate) const POWER: &str = "pc.power";
+/// Offered by devices that open links sent to them.
+pub(crate) const LINKS: &str = "link.open";
+
+/// What a phone can ask a PC to do.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PowerAction {
+ Lock,
+ Sleep,
+}
+
+impl PowerAction {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ PowerAction::Lock => "lock",
+ PowerAction::Sleep => "sleep",
+ }
+ }
+
+ pub fn parse(action: &str) -> Option<PowerAction> {
+ match action {
+ "lock" => Some(PowerAction::Lock),
+ "sleep" => Some(PowerAction::Sleep),
+ _ => None,
+ }
+ }
+}
+
+impl Shared {
+ fn offers(&self, peer: &DeviceId, capability: &str) -> Result<bool> {
+ Ok(self.store.get_peer(peer)?.is_some_and(|p| p.caps.contains(capability)))
+ }
+}
+
+/// Checks a link the protocol allows: http or https, not too long.
+pub(crate) fn valid_link(url: &str) -> bool {
+ let lower = url.get(..8).map(str::to_ascii_lowercase).unwrap_or_default();
+ (lower.starts_with("http://") || lower.starts_with("https://"))
+ && url.len() <= nectarlink_protocol::messages::LINK_MAX_BYTES
+ && !url.chars().any(|c| c.is_control() || c.is_whitespace())
+ && url.split("://").nth(1).is_some_and(|rest| !rest.is_empty())
+}
+
+pub(crate) async fn pc_power(shared: &Arc<Shared>, session: &Session, action: PowerAction) -> Result<()> {
+ if !shared.offers(&session.peer, POWER)? {
+ return Err(Error::Unsupported);
+ }
+ let env = Envelope::new(types::PC_POWER, &PcPower { action: action.as_str().into() })?;
+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;
+ Ok(())
+}
+
+pub(crate) async fn open_link(shared: &Arc<Shared>, session: &Session, url: String) -> Result<()> {
+ if !valid_link(&url) {
+ return Err(Error::Internal("not a web link".into()));
+ }
+ if !shared.offers(&session.peer, LINKS)? {
+ return Err(Error::Unsupported);
+ }
+ let env = Envelope::new(types::LINK_OPEN, &LinkOpen { url })?;
+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;
+ Ok(())
+}
+
+/// Handles `pc.power` and `link.open`. Returns false for other types.
+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {
+ let peer = session.peer;
+ let reply = match env.t.as_str() {
+ types::PC_POWER => {
+ let PcPower { action } = env.body()?;
+ if !shared.local_capabilities().iter().any(|c| c == POWER) {
+ Envelope::error(ErrorCode::Unsupported, "this device doesn't lock or sleep on request")
+ } else if !shared.toggle_on(&peer, POWER_TOGGLE) {
+ Envelope::error(ErrorCode::Denied, "PC actions are off for this device")
+ } else {
+ match PowerAction::parse(&action) {
+ None => Envelope::error(ErrorCode::Unsupported, "unknown action"),
+ Some(action) => {
+ let platform = shared.platform.clone();
+ // Sleeping cuts the connection: answer first.
+ let reply = Envelope::empty(types::OK).reply_to(env.id);
+ session.send(reply).await?;
+ tokio::spawn(async move {
+ // Give the answer time to leave before sleep cuts the network.
+ if action == PowerAction::Sleep {
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ }
+ if let Err(reason) = tokio::task::spawn_blocking(move || platform.power(action))
+ .await
+ .unwrap_or_else(|e| Err(e.to_string()))
+ {
+ tracing::warn!(reason, "power action failed");
+ }
+ });
+ return Ok(true);
+ }
+ }
+ }
+ }
+ types::LINK_OPEN => {
+ let LinkOpen { url } = env.body()?;
+ if !valid_link(&url) {
+ Envelope::error(ErrorCode::BadMessage, "not a web link")
+ } else {
+ let platform = shared.platform.clone();
+ match tokio::task::spawn_blocking(move || platform.open_link(&peer, &url))
+ .await
+ .unwrap_or_else(|e| Err(e.to_string()))
+ {
+ Ok(()) => Envelope::empty(types::OK),
+ Err(reason) => {
+ tracing::warn!(reason, "can't open a link");
+ Envelope::error(ErrorCode::Internal, "can't open it")
+ }
+ }
+ }
+ }
+ _ => return Ok(false),
+ };
+ session.send(reply.reply_to(env.id)).await?;
+ Ok(true)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_web_links_go() {
+ assert!(valid_link("https://example.com/a?b=c#d"));
+ assert!(valid_link("HTTP://EXAMPLE.COM"));
+ for bad in
+ ["javascript:alert(1)", "file:///C:/x", "https://", "https://a b", "ms-settings:", "ftp://x"]
+ {
+ assert!(!valid_link(bad), "{bad}");
+ }
+ assert!(!valid_link(&format!("https://a.com/{}", "x".repeat(8192))));
+ }
+
+ #[test]
+ fn power_actions_round_trip() {
+ for action in [PowerAction::Lock, PowerAction::Sleep] {
+ assert_eq!(PowerAction::parse(action.as_str()), Some(action));
+ }
+ assert_eq!(PowerAction::parse("shutdown"), None);
+ }
+}
diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rs
index e033f04..4902e7c 100644
--- a/core/nectarlink-core/src/config.rs
+++ b/core/nectarlink-core/src/config.rs
@@ -105,6 +105,17 @@ pub trait Platform: Send + Sync + 'static {
Err("this device has no clipboard".into())
}
+ /// Lock or sleep this PC (a paired phone asked). Runs after the phone
+ /// got its answer. `Err` holds a reason for logs.
+ fn power(&self, _action: crate::actions::PowerAction) -> Result<(), String> {
+ Err("this device doesn't lock or sleep on request".into())
+ }
+
+ /// Open a web link a paired device sent (http or https; checked).
+ fn open_link(&self, _from: &nectarlink_protocol::DeviceId, _url: &str) -> Result<(), String> {
+ Err("this device doesn't open links".into())
+ }
+
/// Run a command on one of this device's media players (a paired device
/// asked); `position` is set for [`MediaAction::Seek`].
fn media_command(
diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rs
index ebba517..17f0e46 100644
--- a/core/nectarlink-core/src/features.rs
+++ b/core/nectarlink-core/src/features.rs
@@ -546,6 +546,18 @@ pub const FEATURES: &[FeatureDef] = &[
requires: &[desktop("pc.power", UPDATE), DeviceToggle("pc_actions")],
partial: None,
},
+ FeatureDef {
+ id: "device.links_to_pc",
+ group: FeatureGroup::Device,
+ requires: &[desktop("link.open", UPDATE)],
+ partial: None,
+ },
+ FeatureDef {
+ id: "device.links_to_phone",
+ group: FeatureGroup::Device,
+ requires: &[phone("link.open", UPDATE)],
+ partial: None,
+ },
// Notifications
FeatureDef {
id: "notifications.mirror",
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index c7b647c..9039dae 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -6,6 +6,7 @@
//! changes is reported as a [`NodeEvent`]. See
//! `docs/architecture/core-api.md` for the design.
+mod actions;
mod clipboard;
mod config;
mod error;
@@ -20,6 +21,7 @@ mod session;
mod store;
mod transfer;
+pub use actions::PowerAction;
pub use config::{NodeConfig, NoopPlatform, Platform};
pub use error::{Error, Result, Side};
pub use events::{
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index 6040126..d8ad1db 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -56,8 +56,15 @@ const STREAM_WINDOW: u32 = 16 * 1024 * 1024;
const CONNECTION_WINDOW: u32 = 32 * 1024 * 1024;
/// Capabilities every build offers.
-const BASE_CAPABILITIES: &[&str] =
- &["core.ping", "device.battery", "device.ring", "files.transfer", "clip.image", "media.remote"];
+const BASE_CAPABILITIES: &[&str] = &[
+ "core.ping",
+ "device.battery",
+ "device.ring",
+ "files.transfer",
+ "clip.image",
+ "media.remote",
+ "link.open",
+];
/// This device's mutable description, sent to peers.
#[derive(Debug, Clone)]
@@ -893,6 +900,20 @@ impl Node {
crate::clipboard::send_image(&self.shared, &session, mime, bytes).await
}
+ // ---- Actions (docs/protocol/actions.md) ----
+
+ /// Locks or sleeps a paired PC.
+ pub async fn pc_power(&self, peer: DeviceId, action: crate::PowerAction) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::actions::pc_power(&self.shared, &session, action).await
+ }
+
+ /// Opens a web link on a paired device.
+ pub async fn open_link(&self, peer: DeviceId, url: String) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::actions::open_link(&self.shared, &session, url).await
+ }
+
// ---- Media (docs/protocol/media.md) ----
/// This device's media players changed (most relevant first); sent to
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index 26af288..e31d970 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -347,6 +347,8 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
}
t if t.starts_with("notify.") && crate::notifications::handle(shared, session, &env).await? => {}
t if t.starts_with("media.") && crate::media::handle(shared, session, &env).await? => {}
+ t if (t.starts_with("pc.") || t.starts_with("link."))
+ && crate::actions::handle(shared, session, &env).await? => {}
t if t.starts_with("clip.") && crate::clipboard::handle(shared, session, &env).await? => {}
other => {
if env.id.is_some() {
diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rs
index 0090e2a..745f86f 100644
--- a/core/nectarlink-core/src/transfer.rs
+++ b/core/nectarlink-core/src/transfer.rs
@@ -568,7 +568,7 @@ async fn receive_bytes(
) -> std::result::Result<(), TransferState> {
let mut done: u64 = have.iter().sum();
for (i, (file, have)) in offer.files.iter().zip(have).enumerate() {
- let out =
+ let mut out =
tokio::fs::OpenOptions::new().create(true).append(true).open(part(i)).await.map_err(|e| {
TransferState::Failed(TransferFailure::Other(format!("can't write: {}", e.kind())))
})?;
@@ -576,7 +576,9 @@ async fn receive_bytes(
if *have < out.metadata().await.map(|m| m.len()).unwrap_or(0) {
out.set_len(*have).await.ok();
}
- let mut out = tokio::io::BufWriter::with_capacity(WRITE_BUFFER, out);
+ // Gathered in memory and written in large pieces. Progress counts
+ // what's on disk, which is also where a resumed transfer continues.
+ let mut pending: Vec<u8> = Vec::with_capacity(WRITE_BUFFER);
let mut left = file.size - have;
while left > 0 {
let max = CHUNK.min(usize::try_from(left).unwrap_or(usize::MAX));
@@ -590,48 +592,54 @@ async fn receive_bytes(
};
let bytes = match chunk {
Ok(Some(bytes)) => bytes,
- Ok(None) => {
- out.flush().await.ok();
- return Err(TransferState::Waiting);
- }
Err(ReadError::Reset(code)) if code.into_inner() == u64::from(files::CANCELLED) => {
return Err(TransferState::Cancelled);
}
- // The connection dropped: keep what arrived; the sender
- // resumes from there when it's back.
- Err(_) => {
- out.flush().await.ok();
+ // The stream or connection ended early: keep what arrived;
+ // the sender resumes from there when it's back.
+ Ok(None) | Err(_) => {
+ if write_out(&mut out, &mut pending, recv).await.is_ok() {
+ reporter.progress(done);
+ }
return Err(TransferState::Waiting);
}
};
- if let Err(e) = out.write_all(&bytes).await {
- let no_space = e.kind() == std::io::ErrorKind::StorageFull;
- let code = if no_space { ErrorCode::Busy } else { ErrorCode::Internal };
- let _ = recv.stop(VarInt::from_u32(code.close_code()));
- return Err(TransferState::Failed(if no_space {
- TransferFailure::NoSpace
- } else {
- TransferFailure::Other(format!("can't write: {}", e.kind()))
- }));
- }
left -= bytes.len() as u64;
done += bytes.len() as u64;
- reporter.progress(done);
- }
- if let Err(e) = out.flush().await {
- let no_space = e.kind() == std::io::ErrorKind::StorageFull;
- let code = if no_space { ErrorCode::Busy } else { ErrorCode::Internal };
- let _ = recv.stop(VarInt::from_u32(code.close_code()));
- return Err(TransferState::Failed(if no_space {
- TransferFailure::NoSpace
- } else {
- TransferFailure::Other(format!("can't write: {}", e.kind()))
- }));
+ pending.extend_from_slice(&bytes);
+ if pending.len() >= WRITE_BUFFER || left == 0 {
+ write_out(&mut out, &mut pending, recv).await?;
+ reporter.progress(done);
+ }
}
}
Ok(())
}
+/// Writes what's gathered; a failure stops the stream and says why.
+async fn write_out(
+ out: &mut tokio::fs::File,
+ pending: &mut Vec<u8>,
+ recv: &mut RecvStream,
+) -> std::result::Result<(), TransferState> {
+ let written = out.write_all(pending).await;
+ let written = match written {
+ Ok(()) => out.flush().await,
+ Err(e) => Err(e),
+ };
+ pending.clear();
+ written.map_err(|e| {
+ let no_space = e.kind() == std::io::ErrorKind::StorageFull;
+ let code = if no_space { ErrorCode::Busy } else { ErrorCode::Internal };
+ let _ = recv.stop(VarInt::from_u32(code.close_code()));
+ TransferState::Failed(if no_space {
+ TransferFailure::NoSpace
+ } else {
+ TransferFailure::Other(format!("can't write: {}", e.kind()))
+ })
+ })
+}
+
/// Moves complete files where the user finds them; returns their paths.
async fn store(
shared: &Shared,
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index 6d6688c..49eee38 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -12,7 +12,7 @@ use nectarlink_core::{
Battery, DeviceInfo, DeviceKind, Direction, Error, FeatureState, FileSource, LinkState, MediaAction,
MediaError, MediaPlayer, Node, NodeConfig, NodeEvent, Notification, NotificationAction,
NotificationError, OutgoingFile, PairingEvent, PairingFailure, PairingUri, PlainKeyProtector, Platform,
- PowerLevel, Transfer, TransferFailure, TransferState,
+ PowerAction, PowerLevel, Transfer, TransferFailure, TransferState,
features::{Effort, Upgrade, UpgradeAction},
};
use tempfile::TempDir;
@@ -28,6 +28,8 @@ struct RecordingPlatform {
clipboard: Mutex<Vec<String>>,
images: Mutex<Vec<(String, Vec<u8>)>>,
media: Mutex<Vec<(String, MediaAction, Option<u64>)>>,
+ power: Mutex<Vec<PowerAction>>,
+ links: Mutex<Vec<String>>,
}
impl Platform for RecordingPlatform {
@@ -61,6 +63,14 @@ impl Platform for RecordingPlatform {
self.images.lock().unwrap().push((mime.to_owned(), bytes.to_vec()));
Ok(())
}
+ fn power(&self, action: PowerAction) -> Result<(), String> {
+ self.power.lock().unwrap().push(action);
+ Ok(())
+ }
+ fn open_link(&self, _from: &nectarlink_core::DeviceId, url: &str) -> Result<(), String> {
+ self.links.lock().unwrap().push(url.to_owned());
+ Ok(())
+ }
fn media_command(
&self,
player: &str,
@@ -119,6 +129,15 @@ async fn device(name: &'static str, kind: DeviceKind) -> TestDevice {
start_in(tempfile::tempdir().unwrap(), name, kind).await
}
+/// A device that offers more than the defaults.
+async fn device_with(name: &'static str, kind: DeviceKind, offers: &[&str]) -> TestDevice {
+ let dev = device(name, kind).await;
+ let mut caps = vec!["media.control".to_owned()];
+ caps.extend(offers.iter().map(|c| (*c).to_owned()));
+ dev.node.update_power(PowerLevel::NotApplicable, caps).await;
+ dev
+}
+
/// Waits for the first event matching `pick`, failing the test on timeout.
async fn wait_for<T>(dev: &mut TestDevice, what: &str, mut pick: impl FnMut(&NodeEvent) -> Option<T>) -> T {
let deadline = tokio::time::Instant::now() + WAIT;
@@ -766,6 +785,38 @@ async fn media_is_shared_and_controlled_with_consent() {
assert_eq!(pc.platform.media.lock().unwrap()[0], ("Spotify.exe".to_owned(), MediaAction::Next, None));
}
+#[tokio::test(flavor = "multi_thread")]
+async fn phones_lock_pcs_and_links_open_on_either_side() {
+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &["pc.power"]).await;
+ let mut phone = device("Pixel", DeviceKind::Phone).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());
+
+ with_timeout("lock", phone.node.pc_power(pc_id, PowerAction::Lock)).await.expect("locked");
+ with_timeout("sleep", phone.node.pc_power(pc_id, PowerAction::Sleep)).await.expect("asleep");
+ // The PC answers first and acts a moment later.
+ tokio::time::sleep(Duration::from_millis(800)).await;
+ assert_eq!(*pc.platform.power.lock().unwrap(), [PowerAction::Lock, PowerAction::Sleep]);
+
+ // A phone doesn't lock or sleep on request.
+ let phone_power = pc.node.pc_power(phone_id, PowerAction::Lock).await;
+ assert!(matches!(phone_power, Err(Error::Unsupported)), "{phone_power:?}");
+
+ // The PC's user turned PC actions off for the phone.
+ pc.node.set_device_toggle(phone_id, "pc_actions", false).unwrap();
+ let denied = phone.node.pc_power(pc_id, PowerAction::Lock).await;
+ assert!(matches!(denied, Err(Error::Denied)), "{denied:?}");
+
+ // Links both ways; only web links.
+ with_timeout("to pc", phone.node.open_link(pc_id, "https://example.com/a".into())).await.expect("opened");
+ with_timeout("to phone", pc.node.open_link(phone_id, "http://example.org".into())).await.expect("opened");
+ assert_eq!(*pc.platform.links.lock().unwrap(), ["https://example.com/a"]);
+ assert_eq!(*phone.platform.links.lock().unwrap(), ["http://example.org"]);
+ let script = pc.node.open_link(phone_id, "javascript:alert(1)".into()).await;
+ assert!(script.is_err());
+ assert_eq!(phone.platform.links.lock().unwrap().len(), 1);
+}
+
/// Deterministic, incompressible-looking test data.
fn data(len: usize, seed: u64) -> Vec<u8> {
let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index f3bcda2..7a9417f 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -876,6 +876,9 @@ pub trait Platform: Send + Sync {
action: MediaAction,
position: Option<u64>,
) -> Result<(), MediaFailure>;
+ /// A paired PC sent a web link (http or https, checked) to open.
+ /// False if it couldn't be shown.
+ fn open_link(&self, from_id: String, url: String) -> bool;
}
/// Encrypts the device key at rest (Android: a Keystore key).
@@ -928,6 +931,9 @@ impl core::Platform for PlatformAdapter {
) -> Result<(), core::MediaError> {
Ok(self.0.media_command(player.to_owned(), action.into(), position)?)
}
+ fn open_link(&self, from: &DeviceId, url: &str) -> Result<(), String> {
+ if self.0.open_link(from.to_string(), url.to_owned()) { Ok(()) } else { Err("not shown".into()) }
+ }
fn set_clipboard_image(&self, mime: &str, bytes: &[u8]) -> Result<(), String> {
if self.0.set_clipboard_image(mime.to_owned(), bytes.to_vec()) {
Ok(())
@@ -1215,6 +1221,21 @@ impl NectarlinkNode {
self.run(async move { node.update_power(power.into(), capabilities).await }).await;
}
+ /// Locks a paired PC (`sleep`: puts it to sleep instead).
+ pub async fn pc_power(&self, id: String, sleep: bool) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ let action = if sleep { core::PowerAction::Sleep } else { core::PowerAction::Lock };
+ self.run(async move { Ok(node.pc_power(id, action).await?) }).await
+ }
+
+ /// Opens a web link on a paired PC.
+ pub async fn open_link(&self, id: String, url: String) -> Result<()> {
+ let id = parse_id(&id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(node.open_link(id, url).await?) }).await
+ }
+
/// Reconnects to PCs that aren't connected and syncs connected ones.
pub async fn refresh(&self) {
let node = self.node.clone();
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index 41ad778..15fe5cc 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -38,6 +38,8 @@ pub mod types {
pub const MEDIA_STATE: &str = "media.state";
pub const MEDIA_SYNC: &str = "media.sync";
pub const MEDIA_COMMAND: &str = "media.command";
+ pub const PC_POWER: &str = "pc.power";
+ pub const LINK_OPEN: &str = "link.open";
}
/// What kind of device this is.
@@ -433,6 +435,30 @@ pub struct MediaCommand {
pub position: Option<u64>,
}
+// ---- Actions (docs/protocol/actions.md) ----
+
+/// Body of `pc.power`: `lock` or `sleep`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PcPower {
+ pub action: String,
+}
+
+/// The longest link sent, in bytes.
+pub const LINK_MAX_BYTES: usize = 4096;
+
+/// Body of `link.open`.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct LinkOpen {
+ pub url: String,
+}
+
+/// Never prints the link (protocol v0 §11).
+impl std::fmt::Debug for LinkOpen {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("LinkOpen").field("bytes", &self.url.len()).finish()
+ }
+}
+
// ---- Files (docs/protocol/files.md) ----
/// The files service and its one operation, for stream headers.
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
index a83fe5d..f3f51b1 100644
--- a/desktop/app/Cargo.toml
+++ b/desktop/app/Cargo.toml
@@ -52,6 +52,7 @@ windows = { workspace = true, features = [
"Win32_System_Memory",
"Win32_System_Power",
"Win32_System_Registry",
+ "Win32_System_Shutdown",
"Win32_System_Threading",
"Win32_System_WinRT",
"Win32_UI_Shell",
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index 4a0c410..b4e4996 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -190,6 +190,7 @@ impl cxx_qt::Initialize for qobject::AppController {
let labels = tray::MenuLabels {
open: "Open Nectarlink".into(),
find_phone: "Find my phone".into(),
+ open_link: "Open copied link on phone".into(),
quit: "Quit Nectarlink".into(),
};
match tray::Tray::create("Nectarlink", labels, move |event| on_tray_event(&qt, event)) {
@@ -204,6 +205,7 @@ fn on_tray_event(qt: &CxxQtThread<qobject::AppController>, event: tray::TrayEven
tray::TrayEvent::Open => {
let _ = qt.queue(|object| object.activate_requested());
}
+ tray::TrayEvent::OpenLinkOnPhone => crate::links::open_copied_link_on_phone(),
tray::TrayEvent::Quit => {
let _ = qt.queue(|object| object.quit_requested());
}
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index 736533a..fe1e528 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -95,7 +95,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
let mut config = NodeConfig::new(&data_dir, this_device(), env!("CARGO_PKG_VERSION"));
config.downloads_dir = Some(downloads_dir());
// This PC's own players, for phones (crate::win::media_sessions).
- config.capabilities = vec!["media.control".into()];
+ config.capabilities = vec!["media.control".into(), "pc.power".into()];
let node = match Node::start(config, platform).await {
Ok(node) => node,
Err(e) => {
diff --git a/desktop/app/src/links.rs b/desktop/app/src/links.rs
new file mode 100644
index 0000000..f49d49d
--- /dev/null
+++ b/desktop/app/src/links.rs
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Links and power between this PC and paired phones
+//! (docs/protocol/actions.md): links a phone shares open in the PC's
+//! browser; a copied link can be opened on the phone from the tray; a phone
+//! can lock this PC or put it to sleep.
+
+use nectarlink_core::{DeviceId, Error, FeatureState, LinkState, PowerAction};
+
+use crate::{
+ bridge::app::describe,
+ core_host,
+ win::{
+ clipboard::{self, Clip},
+ shell,
+ toast::{self, Toast},
+ },
+};
+
+/// The toast "device" for link notices.
+pub const TOAST_GROUP: &str = "links";
+
+/// Opens a link a phone sent, in the default browser.
+pub fn open_here(url: &str) -> Result<(), String> {
+ shell::open_url(url)
+}
+
+/// Locks this PC, or puts it to sleep (a phone asked).
+pub fn power(action: PowerAction) -> Result<(), String> {
+ tracing::info!(action = action.as_str(), "a phone asked");
+ match action {
+ PowerAction::Lock => shell::lock(),
+ PowerAction::Sleep => shell::sleep(),
+ }
+}
+
+/// Whether text is a single web link.
+fn as_link(text: &str) -> Option<&str> {
+ let text = text.trim();
+ let lower = text.get(..8).map(str::to_ascii_lowercase).unwrap_or_default();
+ let web = lower.starts_with("http://") || lower.starts_with("https://");
+ (web && text.len() <= 4096 && !text.chars().any(char::is_whitespace)).then_some(text)
+}
+
+fn notice(title: &str, body: &str) {
+ toast::show(Toast {
+ device: TOAST_GROUP.into(),
+ key: "notice".into(),
+ title: title.into(),
+ body: body.into(),
+ attribution: "Nectarlink".into(),
+ icon: None,
+ actions: Vec::new(),
+ reply: None,
+ silent: true,
+ progress: None,
+ });
+}
+
+/// "Open copied link on phone" (tray): opens the link on the clipboard on
+/// a connected phone that takes links.
+pub fn open_copied_link_on_phone() {
+ let Clip::Text(text) = clipboard::read() else {
+ return notice(
+ "Copy a link first",
+ "Copy a web link, then choose this again to open it on your phone.",
+ );
+ };
+ let Some(url) = as_link(&text).map(str::to_owned) else {
+ return notice("That's not a link", "Copy a web link (https://…), then choose this again.");
+ };
+ let phone = core_host::host().hub.read(|s| {
+ s.devices
+ .iter()
+ .filter(|d| matches!(d.link, LinkState::Online { .. }))
+ .find(|d| {
+ s.matrices.get(&d.id).and_then(|m| m.state("device.links_to_phone"))
+ == Some(FeatureState::Available)
+ })
+ .map(|d| (d.id, d.info.name.clone()))
+ });
+ let Some((phone, name)) = phone else {
+ return notice(
+ "No phone to open it on",
+ "Your phone isn't connected right now, or its app needs an update.",
+ );
+ };
+ send(phone, name, url);
+}
+
+fn send(phone: DeviceId, name: String, url: String) {
+ let Some(node) = core_host::node() else { return };
+ core_host::spawn(async move {
+ match node.open_link(phone, url).await {
+ Ok(()) => notice(&format!("Sent to {name}"), "Tap the notification on your phone to open it."),
+ Err(Error::Unsupported) => notice("Couldn't send it", &format!("Update Nectarlink on {name}.")),
+ Err(e) => notice("Couldn't send it", &describe(&e)),
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn copied_links_are_recognized() {
+ assert_eq!(as_link(" https://example.com/a?b \n"), Some("https://example.com/a?b"));
+ assert_eq!(as_link("HTTP://X.ORG"), Some("HTTP://X.ORG"));
+ assert_eq!(as_link("see https://example.com"), None);
+ assert_eq!(as_link("javascript:alert(1)"), None);
+ assert_eq!(as_link("https://a.com b"), None);
+ }
+}
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 4324ec4..91c042e 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -13,6 +13,7 @@ mod clipboard;
mod core_host;
mod icons;
mod launch;
+mod links;
mod logging;
mod mark;
mod media;
@@ -38,7 +39,7 @@ use std::{
};
use cxx_qt_lib::{QGuiApplication, QQmlApplicationEngine, QString, QUrl};
-use nectarlink_core::{MediaAction, MediaError, Platform};
+use nectarlink_core::{MediaAction, MediaError, Platform, PowerAction};
use crate::{
launch::Request,
@@ -65,6 +66,12 @@ impl Platform for DesktopPlatform {
fn set_clipboard_image(&self, mime: &str, bytes: &[u8]) -> Result<(), String> {
win::clipboard::write_image(mime, bytes)
}
+ fn power(&self, action: PowerAction) -> Result<(), String> {
+ links::power(action)
+ }
+ fn open_link(&self, _from: &nectarlink_core::DeviceId, url: &str) -> Result<(), String> {
+ links::open_here(url)
+ }
fn media_command(
&self,
player: &str,
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
index a987198..db72d0b 100644
--- a/desktop/app/src/win/mod.rs
+++ b/desktop/app/src/win/mod.rs
@@ -11,6 +11,7 @@ pub mod icon;
pub mod image;
pub mod media_sessions;
pub mod net;
+pub mod shell;
pub mod shortcut;
pub mod single_instance;
pub mod smtc;
diff --git a/desktop/app/src/win/shell.rs b/desktop/app/src/win/shell.rs
new file mode 100644
index 0000000..e8517d0
--- /dev/null
+++ b/desktop/app/src/win/shell.rs
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Opening links, locking and sleeping the PC.
+
+use windows::{
+ Win32::{
+ System::{Power::SetSuspendState, Shutdown::LockWorkStation},
+ UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOWNORMAL},
+ },
+ core::{HSTRING, w},
+};
+
+/// Opens a link in the default browser.
+pub fn open_url(url: &str) -> Result<(), String> {
+ // SAFETY: plain ShellExecute with valid strings; the result is a
+ // pseudo-handle that's only compared.
+ let result = unsafe { ShellExecuteW(None, w!("open"), &HSTRING::from(url), None, None, SW_SHOWNORMAL) };
+ // Values above 32 mean success.
+ if result.0 as isize > 32 { Ok(()) } else { Err(format!("ShellExecute returned {}", result.0 as isize)) }
+}
+
+/// Locks the PC (shows the sign-in screen).
+pub fn lock() -> Result<(), String> {
+ // SAFETY: no arguments.
+ unsafe { LockWorkStation() }.map_err(|e| e.to_string())
+}
+
+/// Puts the PC to sleep (not hibernate; wake events stay allowed).
+pub fn sleep() -> Result<(), String> {
+ // SAFETY: plain arguments.
+ if unsafe { SetSuspendState(false, false, false) } {
+ Ok(())
+ } else {
+ Err("SetSuspendState failed".into())
+ }
+}
diff --git a/desktop/app/src/win/tray.rs b/desktop/app/src/win/tray.rs
index 307517b..651d231 100644
--- a/desktop/app/src/win/tray.rs
+++ b/desktop/app/src/win/tray.rs
@@ -39,6 +39,8 @@ use windows::{
pub enum TrayEvent {
Open,
FindPhone,
+ /// Open the link on the clipboard on the phone.
+ OpenLinkOnPhone,
Quit,
/// The PC woke from sleep.
Resumed,
@@ -52,6 +54,7 @@ pub enum TrayEvent {
pub struct MenuLabels {
pub open: String,
pub find_phone: String,
+ pub open_link: String,
pub quit: String,
}
@@ -60,6 +63,7 @@ const ICON_ID: u32 = 1;
const CMD_OPEN: u32 = 1;
const CMD_FIND_PHONE: u32 = 2;
const CMD_QUIT: u32 = 3;
+const CMD_OPEN_LINK: u32 = 4;
const PBT_APMRESUMEAUTOMATIC: usize = 0x12;
/// NIN_SELECT | NINF_KEY (shellapi.h): the icon was activated with the keyboard.
const NIN_KEYSELECT: u32 = NIN_SELECT | 0x1;
@@ -241,6 +245,7 @@ fn show_menu(hwnd: HWND, x: i32, y: i32) {
let Some(labels) = LABELS.with(|l| l.borrow().clone()) else { return };
let to_wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::<Vec<u16>>();
let (open, find, quit) = (to_wide(&labels.open), to_wide(&labels.find_phone), to_wide(&labels.quit));
+ let link = to_wide(&labels.open_link);
// SAFETY: the menu and strings outlive TrackPopupMenuEx; the menu is
// destroyed afterwards. SetForegroundWindow/WM_NULL are the documented
// way to make the menu close when clicking elsewhere.
@@ -249,6 +254,7 @@ fn show_menu(hwnd: HWND, x: i32, y: i32) {
let find_flags = if CAN_FIND_PHONE.with(Cell::get) { MF_STRING } else { MF_STRING | MF_GRAYED };
let _ = AppendMenuW(menu, MF_STRING, CMD_OPEN as usize, PCWSTR(open.as_ptr()));
let _ = AppendMenuW(menu, find_flags, CMD_FIND_PHONE as usize, PCWSTR(find.as_ptr()));
+ let _ = AppendMenuW(menu, find_flags, CMD_OPEN_LINK as usize, PCWSTR(link.as_ptr()));
let _ = AppendMenuW(menu, MF_SEPARATOR, 0, PCWSTR::null());
let _ = AppendMenuW(menu, MF_STRING, CMD_QUIT as usize, PCWSTR(quit.as_ptr()));
let _ = SetForegroundWindow(hwnd);
@@ -261,6 +267,7 @@ fn show_menu(hwnd: HWND, x: i32, y: i32) {
match command {
CMD_OPEN => emit(TrayEvent::Open),
CMD_FIND_PHONE => emit(TrayEvent::FindPhone),
+ CMD_OPEN_LINK => emit(TrayEvent::OpenLinkOnPhone),
CMD_QUIT => emit(TrayEvent::Quit),
_ => {}
}
diff --git a/docs/protocol/actions.md b/docs/protocol/actions.md
new file mode 100644
index 0000000..f969e46
--- /dev/null
+++ b/docs/protocol/actions.md
@@ -0,0 +1,49 @@
+# Actions service (protocol v0)
+
+> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are
+> allowed until v1. License: CC BY 4.0.
+
+One-shot actions on a paired device: a phone locks or sleeps a PC, and
+either device sends a web link to open on the other.
+
+## 1. Capabilities
+
+| ID | Offered by | Meaning |
+|---|---|---|
+| `pc.power` | PCs | Locks or sleeps on request |
+| `link.open` | both | Opens web links sent to it |
+
+A device sends these requests only to peers that announce the capability.
+
+## 2. Messages
+
+All on the control stream.
+
+```
+t = "pc.power" id = n b = { action: "lock" | "sleep" }
+t = "link.open" id = n b = { url: text }
+t = "ok" re = n
+```
+
+**`pc.power`** asks a PC to lock or sleep. The PC answers `ok` first, then
+acts (sleep after a short moment, so the answer leaves before the network
+goes down). Shutting down is deliberately not offered (too easy to trigger
+by accident from a pocket).
+
+Errors: `UNSUPPORTED` when the device doesn't lock or sleep on request, or
+for an unknown action; `DENIED` when the user turned "PC actions" off for the
+phone (the `pc_actions` device toggle, on by default).
+
+**`link.open`** asks the receiver to open `url`. Only http and https links
+are allowed, at most 4096 bytes, without whitespace or control characters;
+receivers **MUST** check and answer `BAD_MESSAGE` otherwise.
+
+A PC opens the link in the default browser; a phone shows a notification the
+user taps to open it (Android doesn't let apps in the background open
+screens).
+
+Errors: `BAD_MESSAGE` as above; `INTERNAL` when it couldn't be opened.
+
+## 3. Rules
+
+- Implementations **MUST NOT** log links (v0 §11).
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index 541f13e..1a4b51e 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -22,6 +22,7 @@ capability is missing.
| `device.battery` | Sends `event.battery` | always offered |
| `device.ring` | Rings on `device.ring`, even on silent | always offered |
| `files.transfer` | Sends and receives files ([files service](files.md)) | app update |
+| `link.open` | Opens web links sent to it ([actions](actions.md)) | app update |
| `clip.image` | Accepts images on its clipboard ([clipboard service](clipboard.md)) | app update |
| `media.control` | Shares its media players for remote control ([media service](media.md); phone: needs notification access) | phone: notification access · desktop: app update |
| `media.remote` | Shows and controls other devices' media players | app update |
@@ -51,7 +52,7 @@ capability is missing.
| ID | Meaning | Unlocked by |
|---|---|---|
-| `pc.power` | Locks, sleeps or shuts down on request | app update |
+| `pc.power` | Locks or sleeps on request ([actions](actions.md)) | app update |
| `files.browse` | Lets a paired phone browse and fetch its files | app update |
| `input.inject` | Accepts pointer and keyboard input (touchpad, air mouse, voice typing) | app update |
| `deck.actions` | Runs Deck actions | app update |
diff --git a/docs/protocol/v0.md b/docs/protocol/v0.md
index 02bdf8f..a1b03d7 100644
--- a/docs/protocol/v0.md
+++ b/docs/protocol/v0.md
@@ -8,7 +8,8 @@ connect and exchange messages. Version 0 covers the Phase 0 scope: identity,
pairing, the session handshake, capabilities, heartbeat and the first events
(device info, battery, ping). Feature services are specified in separate
documents that build on this one: [notifications](notifications.md),
-[clipboard](clipboard.md), [files](files.md) and [media](media.md) so far;
+[clipboard](clipboard.md), [files](files.md), [media](media.md) and
+[actions](actions.md) so far;
mirroring follows.
Key words **MUST**, **SHOULD** and **MAY** are used as in RFC 2119.