Skip to content

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

Battery alerts, and the phone's battery in the tray

Bee7a26adf9ed1f
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index 8c4a00e..3f35b1b 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -930,7 +930,10 @@ async fn folders_arrive_with_their_layout() {
assert_eq!(received, [folder.clone(), downloads.join("ticket.pdf")]);
assert_eq!(std::fs::read(folder.join("Day 1").join("beach.jpg")).unwrap(), b"sand");
assert_eq!(std::fs::read(folder.join("notes.txt")).unwrap(), b"fun");
- assert!(std::fs::read_dir(downloads.join("Trip")).unwrap().next().is_none(), "the old folder is untouched");
+ assert!(
+ std::fs::read_dir(downloads.join("Trip")).unwrap().next().is_none(),
+ "the old folder is untouched"
+ );
}
#[tokio::test(flavor = "multi_thread")]
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index aaa8cc1..3d87a34 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -188,6 +188,18 @@ Item {
onToggled: (on) => Preferences.sendToMenu = on
}
}
+ Divider { width: parent.width }
+ ListRow {
+ width: parent.width
+ iconPath: Icons.battery
+ title: qsTr("Battery alerts")
+ description: qsTr("Get a notification when your phone's battery is low, and when it's fully charged.")
+ Toggle {
+ label: qsTr("Battery alerts")
+ checked: Preferences.batteryAlerts
+ onToggled: (on) => Preferences.batteryAlerts = on
+ }
+ }
}
}
diff --git a/desktop/app/src/battery.rs b/desktop/app/src/battery.rs
new file mode 100644
index 0000000..5ef4e63
--- /dev/null
+++ b/desktop/app/src/battery.rs
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Battery alerts: a Windows notification when a phone's battery runs low,
+//! and when it's fully charged. Once each, until the battery has moved on.
+
+use std::{
+ collections::HashMap,
+ sync::{
+ Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
+};
+
+use nectarlink_core::{Battery, DeviceId, NodeEvent};
+
+use crate::{
+ core_host,
+ win::toast::{self, Toast},
+};
+
+/// The toast "device" for battery alerts; their key is the phone's ID.
+pub const TOAST_GROUP: &str = "battery";
+/// At or under this (and not charging): low.
+const LOW: u8 = 15;
+/// A low alert comes again only after charging or climbing past this.
+const RECOVERED: u8 = 25;
+
+static ENABLED: AtomicBool = AtomicBool::new(true);
+static WATCHES: Mutex<Option<HashMap<DeviceId, Watch>>> = Mutex::new(None);
+
+pub fn set_enabled(on: bool) {
+ ENABLED.store(on, Ordering::Relaxed);
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Alert {
+ Low(u8),
+ Full,
+}
+
+/// What a phone has been told about already.
+#[derive(Debug, Default)]
+struct Watch {
+ told_low: bool,
+ told_full: bool,
+ /// The first report after connecting only sets the scene: a phone that
+ /// was already low or full when it connected isn't news.
+ seen: bool,
+}
+
+impl Watch {
+ fn update(&mut self, battery: &Battery) -> Option<Alert> {
+ let low = !battery.charging && battery.level <= LOW;
+ let full = battery.charging && battery.level >= 100;
+ if battery.charging || battery.level >= RECOVERED {
+ self.told_low = false;
+ }
+ if !battery.charging || battery.level < 100 {
+ self.told_full = false;
+ }
+ let first = !self.seen;
+ self.seen = true;
+ if low && !self.told_low {
+ self.told_low = true;
+ // Low is worth saying even right after connecting.
+ Some(Alert::Low(battery.level))
+ } else if full && !self.told_full {
+ self.told_full = true;
+ (!first).then_some(Alert::Full)
+ } else {
+ None
+ }
+ }
+}
+
+pub fn on_event(event: &NodeEvent) {
+ let NodeEvent::Battery { device, battery } = event else { return };
+ let alert = {
+ let mut watches = WATCHES.lock().unwrap_or_else(|e| e.into_inner());
+ watches.get_or_insert_default().entry(*device).or_default().update(battery)
+ };
+ let Some(alert) = alert else { return };
+ if !ENABLED.load(Ordering::Relaxed) {
+ return;
+ }
+ let name = core_host::host().hub.read(|s| s.name_of(device)).unwrap_or_else(|| "Your phone".into());
+ let (title, body) = match alert {
+ Alert::Low(level) => (format!("{name}'s battery is low"), format!("{level}% left. Charge it soon.")),
+ Alert::Full => (format!("{name} is fully charged"), "You can unplug it.".to_owned()),
+ };
+ toast::show(Toast {
+ device: TOAST_GROUP.into(),
+ key: device.to_string(),
+ title,
+ body,
+ attribution: "Nectarlink".into(),
+ icon: None,
+ image: None,
+ actions: Vec::new(),
+ reply: None,
+ silent: false,
+ progress: None,
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn at(level: u8, charging: bool) -> Battery {
+ Battery { level, charging, plugged: None }
+ }
+
+ #[test]
+ fn low_is_told_once_until_it_recovers() {
+ let mut w = Watch::default();
+ assert_eq!(w.update(&at(40, false)), None);
+ assert_eq!(w.update(&at(15, false)), Some(Alert::Low(15)));
+ assert_eq!(w.update(&at(12, false)), None);
+ // Plugged in, then out again while still low: worth saying again.
+ assert_eq!(w.update(&at(13, true)), None);
+ assert_eq!(w.update(&at(13, false)), Some(Alert::Low(13)));
+ // Bouncing around the line doesn't repeat it.
+ assert_eq!(w.update(&at(16, false)), None);
+ assert_eq!(w.update(&at(15, false)), None);
+ assert_eq!(w.update(&at(30, false)), None);
+ assert_eq!(w.update(&at(14, false)), Some(Alert::Low(14)));
+ }
+
+ #[test]
+ fn low_is_told_right_after_connecting() {
+ assert_eq!(Watch::default().update(&at(9, false)), Some(Alert::Low(9)));
+ }
+
+ #[test]
+ fn full_is_told_when_it_gets_there() {
+ let mut w = Watch::default();
+ assert_eq!(w.update(&at(99, true)), None);
+ assert_eq!(w.update(&at(100, true)), Some(Alert::Full));
+ assert_eq!(w.update(&at(100, true)), None);
+ assert_eq!(w.update(&at(100, false)), None);
+ assert_eq!(w.update(&at(100, true)), Some(Alert::Full));
+ // Already full when it connected: not news.
+ assert_eq!(Watch::default().update(&at(100, true)), None);
+ }
+}
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index 803dab7..16bbec6 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -364,10 +364,19 @@ fn ring_device(device: DeviceId, on: bool) {
impl qobject::AppController {
fn refresh(mut self: Pin<&mut Self>) {
let hub = &core_host::host().hub;
- let (status, devices, ringing, online, caps_version) = hub.read(|s| {
+ let (status, devices, ringing, online, caps_version, battery) = hub.read(|s| {
let ringing = s.ringing_from.and_then(|id| s.name_of(&id)).unwrap_or_default();
- let online = s.devices.iter().filter(|d| matches!(d.link, LinkState::Online { .. })).count();
- (s.core_status(), s.devices.len(), ringing, online, s.matrices_version)
+ let connected: Vec<_> =
+ s.devices.iter().filter(|d| matches!(d.link, LinkState::Online { .. })).collect();
+ // With one phone connected, the tray shows its battery.
+ let battery = match connected.as_slice() {
+ [one] => one.battery.as_ref().map(|b| {
+ let charging = if b.charging { ", charging" } else { "" };
+ format!("{} · {}%{charging}", one.info.name, b.level)
+ }),
+ _ => None,
+ };
+ (s.core_status(), s.devices.len(), ringing, connected.len(), s.matrices_version, battery)
});
let (status_text, error) = match &status {
CoreStatus::Starting => ("starting", String::new()),
@@ -390,7 +399,10 @@ impl qobject::AppController {
tray.set_tooltip(&match (devices, online) {
(0, _) => "Nectarlink · no devices paired".to_owned(),
(_, 0) => "Nectarlink · not connected".to_owned(),
- (_, 1) => "Nectarlink · 1 device connected".to_owned(),
+ (_, 1) => battery.map_or_else(
+ || "Nectarlink · 1 device connected".to_owned(),
+ |b| format!("Nectarlink · {b}"),
+ ),
(_, n) => format!("Nectarlink · {n} devices connected"),
});
}
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
index 163f5b4..0630c11 100644
--- a/desktop/app/src/bridge/prefs.rs
+++ b/desktop/app/src/bridge/prefs.rs
@@ -47,6 +47,8 @@ pub mod qobject {
#[qproperty(bool, start_with_windows)]
/// Check for updates on their own.
#[qproperty(bool, auto_update)]
+ /// Tell when a phone's battery is low, or full.
+ #[qproperty(bool, battery_alerts)]
type Preferences = super::PreferencesRust;
}
@@ -64,6 +66,7 @@ pub struct PreferencesRust {
send_to_menu: bool,
start_with_windows: bool,
auto_update: bool,
+ battery_alerts: bool,
/// What the user chose (`start_with_windows` shows the default until then).
start_choice: Option<bool>,
}
@@ -87,6 +90,7 @@ impl cxx_qt::Initialize for qobject::Preferences {
crate::clipboard::set_auto_send(settings.auto_clipboard);
self.as_mut().set_send_to_menu(settings.send_to_menu);
self.as_mut().set_auto_update(settings.auto_update);
+ self.as_mut().set_battery_alerts(settings.battery_alerts);
self.as_mut().set_start_with_windows(crate::startup::effective(settings.start_with_windows));
self.as_mut().rust_mut().start_choice = settings.start_with_windows;
@@ -115,6 +119,12 @@ impl cxx_qt::Initialize for qobject::Preferences {
p.save();
})
.release();
+ self.as_mut()
+ .on_battery_alerts_changed(|p| {
+ crate::battery::set_enabled(p.battery_alerts);
+ p.save();
+ })
+ .release();
self.as_mut()
.on_start_with_windows_changed(|mut p| {
let on = p.start_with_windows;
@@ -142,6 +152,7 @@ impl qobject::Preferences {
auto_clipboard: p.auto_clipboard,
send_to_menu: p.send_to_menu,
auto_update: p.auto_update,
+ battery_alerts: p.battery_alerts,
start_with_windows: p.start_choice,
};
save_in_background(settings);
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index fe1e528..1ad08e5 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -143,6 +143,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
crate::clipboard::on_event(&event);
crate::transfers::on_event(&event);
crate::send_to::on_event(&event);
+ crate::battery::on_event(&event);
}
Err(RecvError::Lagged(missed)) => {
// Resynchronize what can be re-read; transient events are lost.
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 5a9a459..417011e 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -8,6 +8,7 @@
// A GUI app: no console window in release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+mod battery;
mod bridge;
mod clipboard;
mod core_host;
@@ -233,6 +234,7 @@ fn main() -> ExitCode {
win::media_sessions::start(media::local_changed);
let settings = settings::Settings::load(&data_dir);
send_to::set_enabled(settings.send_to_menu);
+ battery::set_enabled(settings.battery_alerts);
// A test instance (own data folder) leaves the user's menu and sign-in
// alone.
if options.data_dir.is_none() {
diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rs
index a4b64a7..181dd99 100644
--- a/desktop/app/src/notifications.rs
+++ b/desktop/app/src/notifications.rs
@@ -210,6 +210,11 @@ pub fn on_toast(event: ToastEvent) {
return crate::bridge::app::install_update_in_background();
}
ToastEvent::Dismissed { device, .. } if device == crate::updater::TOAST_GROUP => return,
+ ToastEvent::Dismissed { device, .. } | ToastEvent::Action { device, .. }
+ if device == crate::battery::TOAST_GROUP =>
+ {
+ return;
+ }
_ => {}
}
match event {
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
index 194ca79..3b7e511 100644
--- a/desktop/app/src/settings.rs
+++ b/desktop/app/src/settings.rs
@@ -47,6 +47,8 @@ pub struct Settings {
pub send_to_menu: bool,
/// Check for updates on its own (installed copies).
pub auto_update: bool,
+ /// Tell when a phone's battery is low, or full.
+ pub battery_alerts: bool,
/// Start when the user signs in. Unset until the user chooses: then an
/// installed copy starts with Windows and a build run from its folder
/// doesn't.
@@ -65,6 +67,7 @@ impl Default for Settings {
auto_clipboard: true,
send_to_menu: true,
auto_update: true,
+ battery_alerts: true,
start_with_windows: None,
}
}
@@ -128,6 +131,7 @@ mod tests {
auto_clipboard: false,
send_to_menu: false,
auto_update: false,
+ battery_alerts: false,
start_with_windows: Some(true),
};
settings.save(dir.path()).unwrap();