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:
1 parent
9e4349fe42
commit
5377d88ca6
5 files changed
+107
-26
No files matched your search
+2
-1
@@ -657,7 +657,7 @@ pub fn setup(app: &mut App, waker: rune::Waker) {
|
||||
}
|
||||
|
||||
let (tx, rx) = channel::<rune::TrayEvent>();
|
||||
let spec = rune::TraySpec::new(os::APP_ID, os::APP_NAME, os::tray_icon())
|
||||
let spec = rune::TraySpec::new(os::APP_ID, os::APP_NAME, os::tray_icon(false))
|
||||
.tooltip("League Recorder")
|
||||
.menu(os::tray_menu(false));
|
||||
let wake = waker.clone();
|
||||
@@ -685,6 +685,7 @@ impl App {
|
||||
if self.status.is_recording != was_recording {
|
||||
if let Some(tray) = &self.tray {
|
||||
tray.set_menu(os::tray_menu(self.status.is_recording));
|
||||
tray.set_icon(os::tray_icon(self.status.is_recording));
|
||||
}
|
||||
if self.status.is_recording {
|
||||
os::notify(
|
||||
|
||||
+48
-5
@@ -81,20 +81,44 @@ pub fn set_app_icon() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A 32 px tray icon: the app's medallion, decoded to the straight RGBA rows the tray takes.
|
||||
pub fn tray_icon() -> rune::TrayIcon {
|
||||
let (width, height, pixels) = tray_icon_pixels();
|
||||
/// A 32 px tray icon: the app's medallion, or a plain red disc while the daemon records.
|
||||
pub fn tray_icon(recording: bool) -> rune::TrayIcon {
|
||||
let (width, height, pixels) = if recording {
|
||||
recording_pixels()
|
||||
} else {
|
||||
medallion_pixels()
|
||||
};
|
||||
rune::TrayIcon::rgba(width, height, pixels)
|
||||
}
|
||||
|
||||
/// The medallion at its bundled 32 px: straight RGBA rows for [`rune::TrayIcon`].
|
||||
fn tray_icon_pixels() -> (u32, u32, Vec<u8>) {
|
||||
fn medallion_pixels() -> (u32, u32, Vec<u8>) {
|
||||
let image = image::load_from_memory(include_bytes!("../icons/32x32.png"))
|
||||
.expect("the bundled tray icon decodes")
|
||||
.into_rgba8();
|
||||
(image.width(), image.height(), image.into_raw())
|
||||
}
|
||||
|
||||
/// A red disc on clear pixels. The edge gets one pixel of coverage, so a tray that scales the
|
||||
/// icon down to 16 px does not show a jagged ring.
|
||||
fn recording_pixels() -> (u32, u32, Vec<u8>) {
|
||||
const SIZE: u32 = 32;
|
||||
const RADIUS: f32 = 11.0;
|
||||
const RED: [u8; 3] = [220, 38, 38];
|
||||
let center = SIZE as f32 / 2.0;
|
||||
let mut pixels = Vec::with_capacity((SIZE * SIZE * 4) as usize);
|
||||
for y in 0..SIZE {
|
||||
for x in 0..SIZE {
|
||||
let dx = x as f32 + 0.5 - center;
|
||||
let dy = y as f32 + 0.5 - center;
|
||||
let distance = (dx * dx + dy * dy).sqrt();
|
||||
let alpha = ((RADIUS + 0.5 - distance).clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
pixels.extend_from_slice(&[RED[0], RED[1], RED[2], alpha]);
|
||||
}
|
||||
}
|
||||
(SIZE, SIZE, pixels)
|
||||
}
|
||||
|
||||
/// The tray menu. `recording` flips the record item's label.
|
||||
pub fn tray_menu(recording: bool) -> Vec<rune::TrayItem> {
|
||||
vec![
|
||||
@@ -120,8 +144,27 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_tray_icon_decodes_to_32_px_of_rgba() {
|
||||
let (width, height, pixels) = tray_icon_pixels();
|
||||
let (width, height, pixels) = medallion_pixels();
|
||||
assert_eq!((width, height), (32, 32));
|
||||
assert_eq!(pixels.len(), (32 * 32 * 4) as usize);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_recording_icon_is_a_red_disc_on_a_clear_square() {
|
||||
let (width, height, pixels) = recording_pixels();
|
||||
assert_eq!((width, height), (32, 32));
|
||||
let at = |x: usize, y: usize| {
|
||||
let i = (y * 32 + x) * 4;
|
||||
[pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
|
||||
};
|
||||
assert_eq!(at(16, 16), [220, 38, 38, 255]);
|
||||
assert_eq!(at(0, 0)[3], 0);
|
||||
assert_eq!(at(31, 16)[3], 0);
|
||||
assert!(
|
||||
pixels
|
||||
.chunks_exact(4)
|
||||
.filter(|p| p[3] == 255)
|
||||
.all(|p| p[..3] == [220, 38, 38])
|
||||
);
|
||||
}
|
||||
}
|
||||
+9
@@ -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
@@ -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
@@ -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
|
||||
|
||||
Reference in new issue
Block a user