app: show a red tray icon while recording

The tray kept the app's medallion while the daemon recorded, so the
notification area said nothing about it. The icon now becomes a plain
red disc, set with the menu whenever the recording state changes. The
state comes from the daemon's status, so a recording started from
another program shows too.

Rune's tray could only replace its menu and tooltip, so the vendored
rune takes Tray::set_icon: Windows rebuilds the HICON and sends
NIM_MODIFY, Linux swaps IconPixmap and emits NewIcon.
This commit is contained in:
vhaudiquet committed 2026-11-23 18:44:12 +01:00
1 parent 9e4349fe42
commit 5377d88ca6
5 files changed
+107 -26

No files matched your search

+9
View File
@@ -121,6 +121,15 @@ impl Tray {
#[cfg(not(any(all(target_os = "linux", feature = "dbus"), target_os = "windows")))]
let _ = tooltip;
}
/// Replaces the icon the tray draws. An icon whose pixel count doesn't match its size is
/// ignored, as [`Tray::new`] refuses one.
pub fn set_icon(&self, icon: TrayIcon) {
if icon.rgba.len() != icon.width as usize * icon.height as usize * 4 { return; }
#[cfg(any(all(target_os = "linux", feature = "dbus"), target_os = "windows"))]
self.native.set_icon(icon);
#[cfg(not(any(all(target_os = "linux", feature = "dbus"), target_os = "windows")))]
let _ = icon;
}
}
/// Escapes a tray menu label so Win32 `AppendMenuW` shows it literally: `&` would underline the
+17 -8
View File
@@ -1,7 +1,7 @@
//! StatusNotifierItem (`org.kde.StatusNotifierItem`) with a `com.canonical.dbusmenu` menu, on
//! its own session-bus connection and thread. The watcher is asked to show the item, again
//! whenever a new watcher takes the name (a bar that starts later or restarts).
use super::{Handler, TrayError, TrayEvent, TrayItem, TraySpec};
use super::{Handler, TrayError, TrayEvent, TrayIcon, TrayItem, TraySpec};
use crate::platform::portal;
use async_channel::{Sender, unbounded};
use futures_lite::{FutureExt, StreamExt};
@@ -26,15 +26,15 @@ type Layout = (i32, HashMap<String, OwnedValue>, Vec<OwnedValue>);
struct Model { id: String, title: String, tooltip: String, icon_name: String, pixmaps: Pixmaps, menu: Vec<TrayItem>, revision: u32, token: Option<String> }
type Shared = Arc<Mutex<Model>>;
enum Command { Menu(Vec<TrayItem>), Tooltip(String) }
enum Command { Menu(Vec<TrayItem>), Tooltip(String), Icon(TrayIcon) }
pub(super) struct Native { commands: Option<Sender<Command>>, worker: Option<JoinHandle<()>> }
fn backend(e: impl std::fmt::Display) -> TrayError { TrayError::Backend(e.to_string()) }
/// ARGB32 in network byte order, as the spec's `IconPixmap` wants.
fn pixmaps(spec: &TraySpec) -> Pixmaps {
let argb = spec.icon.rgba.chunks_exact(4).flat_map(|p| [p[3], p[0], p[1], p[2]]).collect();
vec![(spec.icon.width as i32, spec.icon.height as i32, argb)]
fn pixmaps(icon: &TrayIcon) -> Pixmaps {
let argb = icon.rgba.chunks_exact(4).flat_map(|p| [p[3], p[0], p[1], p[2]]).collect();
vec![(icon.width as i32, icon.height as i32, argb)]
}
/// Menu ids are the item's position plus one; 0 is the root.
@@ -97,6 +97,8 @@ impl Item {
fn menu(&self) -> OwnedObjectPath { OwnedObjectPath::try_from(MENU_PATH).expect("MENU_PATH is an object path") }
#[zbus(signal)]
async fn new_tool_tip(emitter: &SignalEmitter<'_>) -> zbus::Result<()>;
#[zbus(signal)]
async fn new_icon(emitter: &SignalEmitter<'_>) -> zbus::Result<()>;
}
struct Menu { model: Shared, on_event: Handler }
@@ -159,7 +161,7 @@ async fn register(conn: &Connection) {
impl Native {
pub(super) fn new(spec: TraySpec, on_event: Handler) -> Result<Self, TrayError> {
let model = Arc::new(Mutex::new(Model { pixmaps: pixmaps(&spec), id: spec.id, title: spec.title, tooltip: spec.tooltip,
let model = Arc::new(Mutex::new(Model { pixmaps: pixmaps(&spec.icon), id: spec.id, title: spec.title, tooltip: spec.tooltip,
icon_name: spec.icon_name, menu: spec.menu, revision: 1, token: None }));
let (commands, receiver) = unbounded();
let (ready, result) = mpsc::sync_channel(1);
@@ -197,6 +199,10 @@ impl Native {
model.lock().unwrap().tooltip = tooltip;
if let Ok(emitter) = SignalEmitter::new(&conn, ITEM_PATH) { Item::new_tool_tip(&emitter).await.ok(); }
}
Wake::Command(Some(Command::Icon(icon))) => {
model.lock().unwrap().pixmaps = pixmaps(&icon);
if let Ok(emitter) = SignalEmitter::new(&conn, ITEM_PATH) { Item::new_icon(&emitter).await.ok(); }
}
Wake::Command(None) | Wake::Owner(None) => break,
Wake::Owner(Some(changed)) => {
let owner = changed.body().deserialize::<(String, String, String)>().map(|(_, _, new)| new);
@@ -220,6 +226,9 @@ impl Native {
pub(super) fn set_tooltip(&self, tooltip: String) {
if let Some(c) = &self.commands { c.try_send(Command::Tooltip(tooltip)).ok(); }
}
pub(super) fn set_icon(&self, icon: TrayIcon) {
if let Some(c) = &self.commands { c.try_send(Command::Icon(icon)).ok(); }
}
}
impl Drop for Native {
@@ -260,12 +269,12 @@ mod tests {
#[test]
fn the_icon_is_argb_in_network_order() {
let spec = TraySpec::new("t", "T", super::super::TrayIcon::rgba(1, 1, vec![1, 2, 3, 4]));
assert_eq!(pixmaps(&spec), vec![(1, 1, vec![4, 1, 2, 3])]);
assert_eq!(pixmaps(&spec.icon), vec![(1, 1, vec![4, 1, 2, 3])]);
}
fn item(icon_name: &str) -> Item {
let spec = TraySpec::new("t", "T", super::super::TrayIcon::rgba(1, 1, vec![1, 2, 3, 4])).icon_name(icon_name);
let pixmaps = pixmaps(&spec);
let pixmaps = pixmaps(&spec.icon);
let model = Model { id: spec.id, title: spec.title, tooltip: spec.tooltip, icon_name: spec.icon_name,
pixmaps, menu: spec.menu, revision: 1, token: None };
Item { model: Arc::new(Mutex::new(model)), on_event: Arc::new(|_| {}) }
+31 -12
View File
@@ -4,16 +4,16 @@
#![allow(unsafe_code)]
use super::{Handler, TrayError, TrayEvent, TrayItem, TraySpec};
use std::{ptr, sync::{Arc, Mutex, mpsc}, thread::JoinHandle};
use super::{Handler, TrayError, TrayEvent, TrayIcon, TrayItem, TraySpec};
use std::{cell::Cell, ptr, sync::{Arc, Mutex, mpsc}, thread::JoinHandle};
use windows_sys::Win32::{Foundation::*, System::LibraryLoader::GetModuleHandleW, UI::{Shell::*, WindowsAndMessaging::*}};
const CALLBACK: u32 = WM_APP + 1;
const UPDATE: u32 = WM_APP + 2;
const ICON_ID: u32 = 1;
struct Model { tooltip: String, menu: Vec<TrayItem> }
struct Context { model: Arc<Mutex<Model>>, on_event: Handler, icon: HICON, taskbar_created: u32 }
struct Model { tooltip: String, menu: Vec<TrayItem>, icon: TrayIcon }
struct Context { model: Arc<Mutex<Model>>, on_event: Handler, icon: Cell<HICON>, taskbar_created: u32 }
pub(super) struct Native { window: isize, model: Arc<Mutex<Model>>, worker: Option<JoinHandle<()>> }
fn wide(s: &str) -> Vec<u16> { s.encode_utf16().chain(Some(0)).collect() }
@@ -23,12 +23,12 @@ fn last_error(what: &str) -> TrayError {
}
/// A 32-bit BGRA icon; the AND mask is the inverted alpha, which Windows ignores beside alpha.
fn create_icon(spec: &TraySpec) -> HICON {
let mut bgra = spec.icon.rgba.clone();
fn create_icon(icon: &TrayIcon) -> HICON {
let mut bgra = icon.rgba.clone();
let mut mask = Vec::with_capacity(bgra.len() / 4);
for p in bgra.chunks_exact_mut(4) { p.swap(0, 2); mask.push(p[3].wrapping_sub(u8::MAX)); }
// SAFETY: Both buffers hold width × height pixels and outlive the call, which copies them.
unsafe { CreateIcon(ptr::null_mut(), spec.icon.width as i32, spec.icon.height as i32, 1, 32, mask.as_ptr(), bgra.as_ptr()) }
unsafe { CreateIcon(ptr::null_mut(), icon.width as i32, icon.height as i32, 1, 32, mask.as_ptr(), bgra.as_ptr()) }
}
pub(super) fn data(hwnd: HWND, flags: u32) -> NOTIFYICONDATAW {
@@ -48,12 +48,29 @@ pub(super) fn set_tip(data: &mut NOTIFYICONDATAW, tooltip: &str) {
fn notify(hwnd: HWND, context: &Context, message: NOTIFY_ICON_MESSAGE) -> bool {
let mut data = data(hwnd, NIF_MESSAGE | NIF_ICON | NIF_TIP);
data.uCallbackMessage = CALLBACK;
data.hIcon = context.icon;
data.hIcon = context.icon.get();
set_tip(&mut data, &context.model.lock().unwrap().tooltip);
// SAFETY: `data` is fully initialized for this window's icon.
unsafe { Shell_NotifyIconW(message, &data) != 0 }
}
/// Makes the icon the model now names and swaps it in, destroying the one it replaces. A
/// failed `NIM_MODIFY` keeps the old icon.
fn replace_icon(hwnd: HWND, context: &Context) {
let icon = context.model.lock().unwrap().icon.clone();
let created = create_icon(&icon);
if created.is_null() { return; }
let previous = context.icon.replace(created);
if !notify(hwnd, context, NIM_MODIFY) {
context.icon.set(previous);
// SAFETY: `created` was made above and only this branch still refers to it.
unsafe { DestroyIcon(created) };
return;
}
// SAFETY: The tray now draws `created`; `previous` is this process's and unreferenced.
if !previous.is_null() { unsafe { DestroyIcon(previous) }; }
}
/// Shows the menu at the cursor and returns the picked item's id.
fn pick(hwnd: HWND, context: &Context) -> Option<String> {
let menu = context.model.lock().unwrap().menu.clone();
@@ -106,7 +123,7 @@ unsafe extern "system" fn procedure(hwnd: HWND, message: u32, w: WPARAM, l: LPAR
}
0
}
UPDATE => { notify(hwnd, context, NIM_MODIFY); 0 }
UPDATE => { replace_icon(hwnd, context); 0 }
WM_DESTROY => {
Shell_NotifyIconW(NIM_DELETE, &data(hwnd, 0));
PostQuitMessage(0);
@@ -137,14 +154,14 @@ fn create(context: &mut Context) -> Result<HWND, TrayError> {
impl Native {
pub(super) fn new(spec: TraySpec, on_event: Handler) -> Result<Self, TrayError> {
let model = Arc::new(Mutex::new(Model { tooltip: spec.tooltip.clone(), menu: spec.menu.clone() }));
let model = Arc::new(Mutex::new(Model { tooltip: spec.tooltip.clone(), menu: spec.menu.clone(), icon: spec.icon.clone() }));
let shared = model.clone();
let (ready, result) = mpsc::sync_channel(1);
let worker = std::thread::Builder::new().name("rune-tray".into()).spawn(move || {
let icon = create_icon(&spec);
let icon = create_icon(&spec.icon);
// SAFETY: The name is NUL-terminated.
let taskbar_created = unsafe { RegisterWindowMessageW(wide("TaskbarCreated").as_ptr()) };
let mut context = Box::new(Context { model: shared, on_event, icon, taskbar_created });
let mut context = Box::new(Context { model: shared, on_event, icon: Cell::new(icon), taskbar_created });
match create(&mut context) {
Ok(hwnd) => { ready.send(Ok(hwnd as isize)).ok(); }
Err(e) => {
@@ -158,6 +175,7 @@ impl Native {
unsafe {
let mut msg: MSG = std::mem::zeroed();
while GetMessageW(&mut msg, ptr::null_mut(), 0, 0) > 0 { TranslateMessage(&msg); DispatchMessageW(&msg); }
let icon = context.icon.get();
if !icon.is_null() { DestroyIcon(icon); }
}
drop(context);
@@ -177,6 +195,7 @@ impl Native {
}
pub(super) fn set_menu(&self, menu: Vec<TrayItem>) { self.model.lock().unwrap().menu = menu; }
pub(super) fn set_tooltip(&self, tooltip: String) { self.model.lock().unwrap().tooltip = tooltip; self.update(); }
pub(super) fn set_icon(&self, icon: TrayIcon) { self.model.lock().unwrap().icon = icon; self.update(); }
}
/// The windows of the trays alive now, so a fast exit can take their icons off the