Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

Dock: the badges apps put on their taskbar buttons show on their icons (705)

denfry091bdbc59bf1
diff --git a/crates/rf-app/src/dock/middle.rs b/crates/rf-app/src/dock/middle.rs
index 94a8bdbc..b427075c 100644
--- a/crates/rf-app/src/dock/middle.rs
+++ b/crates/rf-app/src/dock/middle.rs
@@ -190,6 +190,8 @@ pub struct MiddleIsland {
drag_watch: Option<gpui_kit::Task<()>>,
/// The apps (keys) that have a window asking for attention: their icon carries a dot (`rf_win::dock::attention`).
wanting: Vec<String>,
+ /// The apps (keys) with a badge on one of their windows (`rf_win::dock::badges`), the badge's generation and its picture.
+ badges: Vec<(String, u64, std::sync::Arc<RenderImage>)>,
/// With the pinned apps that are not running in the left island (`Settings::dock_pins_left`): those apps, with their icon's key and
/// sources. The home dock's island holds them and loads their pictures; the left island draws them (`left.rs`).
left_pins: Vec<(rf_win::dock::DockApp, String, Vec<IconSource>)>,
@@ -276,6 +278,7 @@ impl MiddleIsland {
last_slots: Vec::new(),
drag_watch: None,
wanting: Vec::new(),
+ badges: Vec::new(),
left_pins: Vec::new(),
};
// (the app menu tells it when the dock's own pin list changed)
@@ -369,7 +372,8 @@ impl MiddleIsland {
let wanting = wanting_attention(&items);
let attention_changed = wanting != self.wanting;
self.wanting = wanting;
- if attention_changed && items == self.items {
+ let badges_changed = self.take_badges(&items, cx);
+ if (attention_changed || badges_changed) && items == self.items {
cx.notify();
return;
}
@@ -643,6 +647,31 @@ impl MiddleIsland {
/// The icon of item `ix` for a picture `logical_px` wide in a window at the monitor's scale (the preview and the menu draw it at
/// their own sizes), if it has been loaded: the kept picture nearest above that size, so it is not reduced by much.
+ /// Reads the badges of the apps' windows and makes a picture of each new one; `true` when a badge came, changed or went. The
+ /// pictures no longer drawn go back to the toolkit after this update (as the tray strip's do).
+ fn take_badges(&mut self, items: &[DockItem], cx: &mut Context<Self>) -> bool {
+ let mut next = Vec::new();
+ for item in items {
+ let DockItem::App(a) = item else { continue };
+ let Some(b) = rf_win::dock::badges::of(&a.windows) else { continue };
+ let kept = self.badges.iter().find(|(k, g, _)| *k == a.key && *g == b.generation).map(|(_, _, img)| img.clone());
+ if let Some(img) = kept.or_else(|| badge_image(&b.picture)) {
+ next.push((a.key.clone(), b.generation, img));
+ }
+ }
+ let same = next.len() == self.badges.len() && next.iter().zip(&self.badges).all(|(n, o)| n.0 == o.0 && n.1 == o.1);
+ let old = std::mem::replace(&mut self.badges, next);
+ let retired: Vec<_> = old.into_iter().map(|(_, _, img)| img).filter(|img| !self.badges.iter().any(|(_, _, n)| std::sync::Arc::ptr_eq(img, n))).collect();
+ if !retired.is_empty() {
+ cx.defer(move |cx| {
+ for img in retired {
+ cx.drop_image(img, None);
+ }
+ });
+ }
+ !same
+ }
+
fn icon_for(&self, ix: usize, logical_px: f32, cx: &App) -> Option<std::sync::Arc<RenderImage>> {
let (key, _) = self.icon_srcs.get(ix)?.as_ref()?;
match self.levels.get(key) {
@@ -1413,6 +1442,11 @@ impl Render for MiddleIsland {
};
// an app whose window asks for attention (Discord on a message): a dot at the icon's top right, inside its box
let wants = matches!(item, DockItem::App(a) if self.wanting.contains(&a.key));
+ // the badge the app put on its taskbar button (a chat's unread count), at the icon's bottom right as on the taskbar
+ let badge = match item {
+ DockItem::App(a) => self.badges.iter().find(|(k, _, _)| *k == a.key).map(|(_, _, img)| img.clone()),
+ _ => None,
+ };
// the app's sound level, while the wheel has just been turned over this icon
let hud = match (item, &self.vol_hud) {
(DockItem::App(a), Some(h)) if h.key == a.key => Some(vol_hud_look(h.level)),
@@ -1457,6 +1491,10 @@ impl Render for MiddleIsland {
.child(div().mt(u(w * 0.03)).w(u(bar)).h(u(w * 0.05)).rounded_full().bg(track).child(div().h_full().w(u(bar * fill)).rounded_full().bg(ink))),
)
})
+ .when_some(badge, |d, img| {
+ let b = w * 0.46;
+ d.child(gpui_kit::img(img).absolute().bottom(u(0.0)).right(u(0.0)).size(u(b)))
+ })
.when(wants, |d| {
let r = (w * 0.26).clamp(7.0, 14.0);
d.child(
@@ -1613,6 +1651,12 @@ impl Render for MiddleIsland {
}
/// The keys of the apps that have a window asking for attention.
+/// A badge's picture as the toolkit draws it (the tray host keeps it as straight BGRA, what `RenderImage` takes).
+fn badge_image(p: &rf_win::trayhost::IconBitmap) -> Option<std::sync::Arc<RenderImage>> {
+ let buf = image::RgbaImage::from_raw(p.width, p.height, p.bgra.clone())?;
+ Some(std::sync::Arc::new(RenderImage::new(vec![image::Frame::new(buf)])))
+}
+
fn wanting_attention(items: &[DockItem]) -> Vec<String> {
items
.iter()
diff --git a/crates/rf-app/src/dock/task_feed.rs b/crates/rf-app/src/dock/task_feed.rs
index c517863a..cb1b1b3e 100644
--- a/crates/rf-app/src/dock/task_feed.rs
+++ b/crates/rf-app/src/dock/task_feed.rs
@@ -51,6 +51,8 @@ pub fn subscribe(tx: UnboundedSender<()>) {
feed.watch = tasklist::watch(on_change).map_err(|e| log::warn!("dock: cannot watch the task windows: {e:#}")).ok();
// a window that asks for attention (or stops) is news too: its icon gets or loses its dot
rf_win::dock::attention::start(|| on_change(Changes { list: false, titles: false, active: true }));
+ // so is a badge an app puts on its taskbar button, or takes away
+ rf_win::dock::badges::on_change(|| on_change(Changes { list: false, titles: false, active: true }));
// Windows' notification banners stand right above the dock, not where Windows' own margin puts them
rf_win::dock::toastpos::start();
}
diff --git a/crates/rf-app/src/dock_page.rs b/crates/rf-app/src/dock_page.rs
index db83c400..c90559ab 100644
--- a/crates/rf-app/src/dock_page.rs
+++ b/crates/rf-app/src/dock_page.rs
@@ -489,6 +489,17 @@ pub(crate) fn entries() -> Vec<Entry> {
Some(t!("Sabitlenmiş uygulamalarla sabitlenmemiş çalışan uygulamalar arasına bir çizgi konur.")),
Control::Switch(|s| s.dock_running_divider, |s, v| s.dock_running_divider = v),
),
+ e(
+ "dock-app-badges",
+ "dock_app_badges",
+ Middle,
+ dock,
+ L::Bell,
+ // (English until the maintainer gives the Turkish)
+ t!("Show the badges apps put on their taskbar buttons"),
+ Some(t!("A chat's unread count, for example, shows on its icon in the dock. Needs the tray icons; an app that was already running shows its badge after it is restarted.")),
+ Control::Switch(|s| s.dock_app_badges, |s, v| s.dock_app_badges = v),
+ ),
e(
"dock-ignored-apps",
"dock_ignored_apps",
@@ -894,7 +905,7 @@ mod tests {
let ids = |sec: Section| g.iter().find(|(s, _)| *s == sec).map(|(_, v)| v.iter().map(|e| e.field).collect::<Vec<_>>()).unwrap();
assert_eq!(ids(Section::General), ["dock_enabled", "dock_reserve", "dock_position", "dock_size", "dock_side_tall", "dock_autohide", "dock_autohide_windows", "dock_opaque", "dock_adaptive_tone", "dock_performance", "dock_show_desktop", "dock_tray_compact", "dock_pins_left", "dock_labels", "dock_tray_two_rows", "dock_all_monitors", "dock_magnify", "dock_lively", "dock_lock_icons", "dock_corner_radius", "dock_preview_size", "dock_scroll_volume", "dock_start_grow"]);
assert_eq!(ids(Section::Left), ["dock_own_start", "dock_start_recommended", "dock_search", "dock_search_hypersearch", "dock_weather_city"]);
- assert_eq!(ids(Section::Middle), ["dock_hover_previews", "dock_app_menu", "dock_thin_when_maximized", "dock_apps_where", "dock_hide_places", "dock_running_divider", "dock_ignored_apps"]);
+ assert_eq!(ids(Section::Middle), ["dock_hover_previews", "dock_app_menu", "dock_thin_when_maximized", "dock_apps_where", "dock_hide_places", "dock_running_divider", "dock_app_badges", "dock_ignored_apps"]);
assert_eq!(ids(Section::Right), ["dock_own_control_centre", "dock_own_calendar", "dock_own_notifications", "dock_clock_seconds"]);
}
diff --git a/crates/rf-app/src/i18n_en.rs b/crates/rf-app/src/i18n_en.rs
index 3e20e189..aac8bbd1 100644
--- a/crates/rf-app/src/i18n_en.rs
+++ b/crates/rf-app/src/i18n_en.rs
@@ -2296,6 +2296,12 @@ pub const EN: &[(&str, &str)] = &[
("Geri Dönüşüm Kutusu ve İndirilenler'i gizle", "Hide the Recycle Bin and Downloads"),
("Orta adanın sonundaki Geri Dönüşüm Kutusu ve İndirilenler simgeleri gösterilmez.", "The Recycle Bin and Downloads icons at the end of the middle island are not shown."),
("Sabitlenenlerle çalışanlar arasında ayırıcı", "Divider between pinned and running apps"),
+ // (issue 705: the Turkish is the maintainer's to give; until then the key is the English)
+ ("Show the badges apps put on their taskbar buttons", "Show the badges apps put on their taskbar buttons"),
+ (
+ "A chat's unread count, for example, shows on its icon in the dock. Needs the tray icons; an app that was already running shows its badge after it is restarted.",
+ "A chat's unread count, for example, shows on its icon in the dock. Needs the tray icons; an app that was already running shows its badge after it is restarted.",
+ ),
("Sabitlenmiş uygulamalarla sabitlenmemiş çalışan uygulamalar arasına bir çizgi konur.", "A line goes between the pinned apps and the running apps that are not pinned."),
("Dock'ta gösterilmeyecek uygulamalar (örneğin chrome.exe, Spotify)", "Apps not shown in the dock (for example chrome.exe, Spotify)"),
("Pencere büyütüldüğünde dock'u incelt", "Make the dock thin when a window is maximized"),
diff --git a/crates/rf-app/src/settings.rs b/crates/rf-app/src/settings.rs
index 07a39eb2..673a406d 100644
--- a/crates/rf-app/src/settings.rs
+++ b/crates/rf-app/src/settings.rs
@@ -1226,6 +1226,9 @@ pub struct Settings {
pub dock_hide_places: bool,
/// A line between the pinned apps and the running ones that are not pinned (off; the same request).
pub dock_running_divider: bool,
+ /// The badges programs put on their taskbar buttons (a chat's unread count) are shown on their icons in the dock (off; issue 705).
+ /// They come through the tray host (`rf_win::dock::badges`), so only while it runs.
+ pub dock_app_badges: bool,
/// The dock's springs swing a little past their target and back (off): the icons' growth as the pointer comes in, an icon's
/// slide into its new place.
pub dock_lively: bool,
@@ -1610,6 +1613,7 @@ impl Default for Settings {
dock_pins_left: false,
dock_hide_places: false,
dock_running_divider: false,
+ dock_app_badges: false,
dock_lively: false,
dock_lock_icons: false,
dock_corner_radius: 24,
diff --git a/crates/rf-app/src/shell/trayhost.rs b/crates/rf-app/src/shell/trayhost.rs
index 9350234d..b329251a 100644
--- a/crates/rf-app/src/shell/trayhost.rs
+++ b/crates/rf-app/src/shell/trayhost.rs
@@ -136,6 +136,8 @@ impl Global for TrayGlobal {}
/// The settings file was (re)read, or the host started: brings the tray host in line with the setting. Cheap when nothing changed.
pub fn on_settings(cx: &mut App) {
+ // (read by the tray host's window on its next tick: it names its own taskband window only while this is on)
+ rf_win::dock::badges::set_enabled(cx.try_global::<Settings>().is_some_and(|s| s.dock_app_badges));
let want = cx.try_global::<Settings>().is_some_and(wanted);
match decide(want, cx.has_global::<TrayGlobal>()) {
Action::Start => start(cx),
diff --git a/crates/rf-win/src/dock/badges.rs b/crates/rf-win/src/dock/badges.rs
new file mode 100644
index 00000000..3e80d4e8
--- /dev/null
+++ b/crates/rf-win/src/dock/badges.rs
@@ -0,0 +1,157 @@
+//! The badges programs put on their taskbar buttons (a chat's unread count): the dock shows them on the app's icon (issue 705).
+//!
+//! HOW THEY COME. A program calls `ITaskbarList3::SetOverlayIcon`. That interface runs in the program's own process: its `HrInit`
+//! finds the first window of class `Shell_TrayWnd`, reads that window's `TaskbandHWND` property, and from then on sends its calls to
+//! the window the property names, as plain messages: [`MSG_OVERLAY`] with the program's window in `wParam` and the badge in `lParam`
+//! (none takes the badge away), `WM_USER+85` the badge's text, `WM_USER+64` / `+65` the progress bar, and more. Explorer's taskbar
+//! buttons are that window. While the tray host runs, the first `Shell_TrayWnd` is ours; with the setting on, its `TaskbandHWND`
+//! names a window of the tray host ([`taskband`]), which keeps the badge here and passes EVERY message on to Explorer's window, so
+//! Explorer's taskbar shows what it always did. (Tried on Windows 10 22H2 with a test window's badge, text and progress, and with
+//! Telegram's unread count. Cairo shell's `TasksService.cs` reads the same numbers.)
+//!
+//! NOT SEEN. The interface reads the property at `HrInit` and keeps the window while that window lives; it looks again only when the
+//! window is gone (tried: a test program's badge, set while one dock ran, reached the next dock after a restart). So a program that
+//! was running before the setting went on keeps sending to Explorer's window, which never goes away, and its badge shows here only
+//! after the program is restarted. The other way round costs nothing: when the tray host stops, its window goes, and programs that
+//! used it find Explorer's again with their next call.
+//!
+//! The badge is kept as a picture read at once (the icon handle belongs to the sender and is gone when its call returns), for the
+//! window it was set on. Nothing of it is logged.
+
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+
+use crate::trayhost::IconBitmap;
+
+/// `ITaskbarList3::SetOverlayIcon`'s message to the taskbar buttons' window: `WM_USER + 79`.
+pub const MSG_OVERLAY: u32 = 0x0400 + 79;
+
+/// One window's badge. `generation` is new for every picture set, so a reader knows a changed one without comparing pixels.
+#[derive(Clone, Debug)]
+pub struct Badge {
+ pub picture: Arc<IconBitmap>,
+ pub generation: u64,
+}
+
+static ON: AtomicBool = AtomicBool::new(false);
+static NEXT: AtomicU64 = AtomicU64::new(1);
+static BADGES: Mutex<Option<HashMap<isize, Badge>>> = Mutex::new(None);
+static NOTIFY: OnceLock<Box<dyn Fn() + Send + Sync>> = OnceLock::new();
+
+/// The window the tray host's `Shell_TrayWnd` names in its `TaskbandHWND` property: its own (`ours`) while badges are wanted and it
+/// has one, Explorer's otherwise.
+pub fn taskband(wanted: bool, ours: isize, explorers: isize) -> isize {
+ if wanted && ours != 0 { ours } else { explorers }
+}
+
+/// What one overlay message does to the badges; `true` when something the dock shows changed. `picture` is `None` when the badge is
+/// taken away. Windows that are gone (`alive` says no) lose theirs on the way, so a closed program's badge does not stay.
+pub fn apply(badges: &mut HashMap<isize, Badge>, hwnd: isize, picture: Option<IconBitmap>, generation: u64, alive: impl Fn(isize) -> bool) -> bool {
+ let before = badges.len();
+ badges.retain(|h, _| alive(*h));
+ let mut changed = badges.len() != before;
+ if hwnd == 0 {
+ return changed;
+ }
+ match picture {
+ Some(p) => {
+ badges.insert(hwnd, Badge { picture: Arc::new(p), generation });
+ changed = true;
+ }
+ None => changed |= badges.remove(&hwnd).is_some(),
+ }
+ changed
+}
+
+/// Turns the badges on or off (the setting). Turning them off forgets every badge.
+pub fn set_enabled(on: bool) {
+ if ON.swap(on, Ordering::SeqCst) && !on {
+ clear();
+ }
+}
+
+/// Whether the setting asks for badges.
+pub fn enabled() -> bool {
+ ON.load(Ordering::SeqCst)
+}
+
+/// `changed` is called (on the tray host's thread) whenever a badge comes, changes or goes. Only the first call counts.
+pub fn on_change(changed: impl Fn() + Send + Sync + 'static) {
+ let _ = NOTIFY.set(Box::new(changed));
+}
+
+/// A badge was set on window `hwnd` (`None`: taken away). Called by the tray host.
+pub fn overlay(hwnd: isize, picture: Option<IconBitmap>, alive: impl Fn(isize) -> bool) {
+ if !enabled() {
+ return;
+ }
+ let generation = NEXT.fetch_add(1, Ordering::Relaxed);
+ let set = picture.is_some();
+ let changed = {
+ let mut guard = BADGES.lock().unwrap_or_else(|e| e.into_inner());
+ apply(guard.get_or_insert_with(HashMap::new), hwnd, picture, generation, alive)
+ };
+ if changed {
+ log::debug!("dock: window {hwnd:#x} {} a badge", if set { "has" } else { "no longer has" });
+ notify();
+ }
+}
+
+/// Forgets every badge (the setting went off, the tray host stopped: nothing would take them away any more).
+pub fn clear() {
+ let had = BADGES.lock().unwrap_or_else(|e| e.into_inner()).take().is_some_and(|b| !b.is_empty());
+ if had {
+ notify();
+ }
+}
+
+/// The badge of the first of `windows` that has one.
+pub fn of(windows: &[isize]) -> Option<Badge> {
+ let guard = BADGES.lock().unwrap_or_else(|e| e.into_inner());
+ let badges = guard.as_ref()?;
+ windows.iter().find_map(|h| badges.get(h).cloned())
+}
+
+fn notify() {
+ if let Some(f) = NOTIFY.get() {
+ f();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn pic() -> IconBitmap {
+ IconBitmap::new(1, 1, vec![0, 0, 255, 255]).unwrap()
+ }
+
+ #[test]
+ fn the_taskband_is_ours_only_while_badges_are_wanted_and_we_have_a_window() {
+ assert_eq!(taskband(true, 7, 9), 7);
+ assert_eq!(taskband(false, 7, 9), 9, "off: Explorer's, as before");
+ assert_eq!(taskband(true, 0, 9), 9, "no window of ours: Explorer's");
+ }
+
+ #[test]
+ fn a_badge_comes_changes_and_goes_with_its_window() {
+ let mut b = HashMap::new();
+ let all = |_: isize| true;
+ assert!(apply(&mut b, 10, Some(pic()), 1, all), "a badge comes");
+ assert!(apply(&mut b, 10, Some(pic()), 2, all), "a new picture is news");
+ assert_eq!(b[&10].generation, 2);
+ assert!(apply(&mut b, 10, None, 3, all), "taken away");
+ assert!(!apply(&mut b, 10, None, 4, all), "taken away again: nothing new");
+ assert!(!apply(&mut b, 0, Some(pic()), 5, all), "no window, no badge");
+ assert!(b.is_empty());
+ }
+
+ #[test]
+ fn a_closed_windows_badge_goes_with_the_next_message() {
+ let mut b = HashMap::new();
+ apply(&mut b, 10, Some(pic()), 1, |_| true);
+ assert!(apply(&mut b, 20, None, 2, |h| h != 10), "10 is gone: its badge too, though 20 had none");
+ assert!(b.is_empty());
+ }
+}
diff --git a/crates/rf-win/src/dock/mod.rs b/crates/rf-win/src/dock/mod.rs
index 3a380bf7..c8714ba0 100644
--- a/crates/rf-win/src/dock/mod.rs
+++ b/crates/rf-win/src/dock/mod.rs
@@ -75,6 +75,7 @@
pub mod appmenu;
pub mod attention;
+pub mod badges;
pub mod band;
pub mod calendar;
pub mod clock;
diff --git a/crates/rf-win/src/trayhost/mod.rs b/crates/rf-win/src/trayhost/mod.rs
index d76676f6..be63fa99 100644
--- a/crates/rf-win/src/trayhost/mod.rs
+++ b/crates/rf-win/src/trayhost/mod.rs
@@ -152,14 +152,17 @@ mod scans {
// one ShowWindow, on our own window, only for the visible option
assert_eq!(win.matches("ShowWindow(").count(), 1);
assert!(win.contains("ShowWindow(hwnd, SW_SHOWNOACTIVATE)"));
- // the only DestroyWindow calls are on our own handles
+ // the only DestroyWindow calls are on our own handles (`b` is our taskband window)
for call in win.split("DestroyWindow(").skip(1) {
let first = call.split(')').next().unwrap_or("").trim();
- assert!(["h", "hwnd"].contains(&first), "DestroyWindow on `{first}`");
+ assert!(["h", "hwnd", "b"].contains(&first), "DestroyWindow on `{first}`");
}
- // Explorer's window is only ever sent messages that came to ours (through the relay), never a message of our own making
- assert_eq!(win.matches("SendMessageTimeoutW(").count(), 1);
+ // Explorer's windows are only ever sent messages that came to ours (the tray's through the relay, the taskband's as they
+ // came to our taskband window), never a message of our own making
+ assert_eq!(win.matches("SendMessageTimeoutW(").count(), 2);
assert!(win.contains("SendMessageTimeoutW(h, raw.msg, WPARAM(raw.wparam), LPARAM(raw.lparam)"));
+ assert!(win.contains("SendMessageTimeoutW(hwnd_of(explorer), msg, wp, lp,"));
+ assert!(win.contains("PostMessageW(Some(hwnd_of(explorer)), msg, wp, lp)"));
// the broadcast is one call
assert_eq!(win.matches("HWND_BROADCAST,").count(), 2, "the import and the one call");
}
diff --git a/crates/rf-win/src/trayhost/win.rs b/crates/rf-win/src/trayhost/win.rs
index e526cd63..c8e19ffd 100644
--- a/crates/rf-win/src/trayhost/win.rs
+++ b/crates/rf-win/src/trayhost/win.rs
@@ -7,7 +7,10 @@
//! * [`Win32Window`]: our `Shell_TrayWnd` (hidden unless asked) with its `TrayNotifyWnd` child; kept the first one a program finds with
//! `SetWindowPos(HWND_TOPMOST)` on OUR window only (Explorer's is never moved, hidden or restyled); its rectangle, its child's
//! rectangle and its window properties (`TaskbandHWND`: programs read it from the first `Shell_TrayWnd` to find the taskbar's
-//! button window) are copied from Explorer's;
+//! button window) are copied from Explorer's, except that `TaskbandHWND` names our own taskband window while the dock's badges are
+//! on (`crate::dock::badges`);
+//! * the taskband window: a message-only window that reads the badges programs put on their taskbar buttons and passes every message
+//! on to Explorer's taskbar buttons (`band_proc`);
//! * [`Win32Broadcast`]: `SendNotifyMessage(HWND_BROADCAST, TaskbarCreated)`, and the same to each message-only window;
//! * [`Win32Owners`]: `IsWindow`, `GetWindowThreadProcessId`, `AllowSetForegroundWindow`, `SendNotifyMessage` to an icon's owner;
//! * [`Win32Pixels`]: `GetIconInfo` + `GetDIBits`, with the arithmetic in `pixels.rs`;
@@ -390,6 +393,8 @@ pub fn taskbar_created_id() -> u32 {
pub struct Win32Window {
hwnd: Option<HWND>,
child: Option<HWND>,
+ /// The taskband window (see `band_proc`); made with the main window, destroyed with it.
+ band: Option<HWND>,
visible: bool,
/// Names of the properties set on our window (removed before it is destroyed).
props: Vec<Vec<u16>>,
@@ -398,7 +403,7 @@ pub struct Win32Window {
impl Win32Window {
pub fn new(visible: bool) -> Win32Window {
- Win32Window { hwnd: None, child: None, visible, props: Vec::new(), class_registered: false }
+ Win32Window { hwnd: None, child: None, band: None, visible, props: Vec::new(), class_registered: false }
}
/// Removes the properties, forgets the handle, destroys the window. Called by the window procedure for `WM_CLOSE` (so the handle
@@ -415,6 +420,12 @@ impl Win32Window {
self.child = None;
let _ = DestroyWindow(h);
}
+ if let Some(b) = self.band.take() {
+ let _ = DestroyWindow(b);
+ EXPLORER_BAND.with(|e| e.set(0));
+ // (nothing takes a badge away any more)
+ crate::dock::badges::clear();
+ }
}
}
}
@@ -440,6 +451,12 @@ impl TrayWindow for Win32Window {
.map_err(|e| format!("CreateWindowExW: {e}"))?;
self.hwnd = Some(hwnd);
self.child = CreateWindowExW(Default::default(), child_class, w!(""), WS_CHILD, 0, 0, 1, 1, Some(hwnd), None, Some(hinst.into()), None).ok();
+ let bc = WNDCLASSEXW { cbSize: size_of::<WNDCLASSEXW>() as u32, lpfnWndProc: Some(band_proc), hInstance: hinst.into(), lpszClassName: BAND_CLASS_W, ..Default::default() };
+ let _ = RegisterClassExW(&bc);
+ // (no band window, no badges: the taskband stays Explorer's)
+ self.band = CreateWindowExW(Default::default(), BAND_CLASS_W, w!(""), Default::default(), 0, 0, 0, 0, Some(HWND_MESSAGE), None, Some(hinst.into()), None)
+ .map_err(|e| log::warn!("tray host: no taskband window, so no badges: {e}"))
+ .ok();
if self.visible {
// click-through and almost invisible: the taskbar underneath keeps working
let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
@@ -458,6 +475,7 @@ impl TrayWindow for Win32Window {
self.class_registered = false;
if let Ok(hinst) = GetModuleHandleW(None) {
let _ = UnregisterClassW(CHILD_CLASS_W, Some(hinst.into()));
+ let _ = UnregisterClassW(BAND_CLASS_W, Some(hinst.into()));
let _ = UnregisterClassW(w!("Shell_TrayWnd"), Some(hinst.into()));
}
}
@@ -504,6 +522,14 @@ impl TrayWindow for Win32Window {
if !should_mirror_prop(&String::from_utf16_lossy(&name[..name.len().saturating_sub(1)])) {
continue;
}
+ // (programs send their taskbar buttons' badges and progress to the window this names: ours while the dock wants the
+ // badges, which passes everything on to Explorer's; Explorer's own otherwise)
+ let value = if name[..name.len().saturating_sub(1)] == *TASKBAND_W {
+ EXPLORER_BAND.with(|e| e.set(value));
+ crate::dock::badges::taskband(crate::dock::badges::enabled(), self.band.map_or(0, |b| b.0 as isize), value)
+ } else {
+ value
+ };
// (read back first: only a property that differs is written)
let now = GetPropW(me, PCWSTR(name.as_ptr()));
if now.0 as isize != value && SetPropW(me, PCWSTR(name.as_ptr()), Some(HANDLE(value as *mut c_void))).is_ok() && !self.props.contains(&name) {
@@ -519,6 +545,43 @@ impl TrayWindow for Win32Window {
}
const CHILD_CLASS_W: PCWSTR = w!("TrayNotifyWnd");
+const BAND_CLASS_W: PCWSTR = w!("RustyfilesTaskband");
+/// "TaskbandHWND" in UTF-16, without its NUL.
+const TASKBAND_W: &[u16] = &[84, 97, 115, 107, 98, 97, 110, 100, 72, 87, 78, 68];
+
+thread_local! {
+ /// Explorer's taskbar buttons' window, as Explorer's `Shell_TrayWnd` last named it (0: none).
+ static EXPLORER_BAND: Cell<isize> = const { Cell::new(0) };
+}
+
+/// The taskband window's procedure. Programs that found our `Shell_TrayWnd` while it named this window send it their
+/// `ITaskbarList` calls (`crate::dock::badges` has the numbers). Every one of them goes on to Explorer's taskbar buttons FIRST, the
+/// way it came (sent or posted), whatever the setting says now: a program that found this window keeps using it. Then a badge is
+/// read for the dock while its icon is still valid (the sender waits for our answer). `WM_COPYDATA` is passed on too, in case a
+/// Windows version sends a call with data that way.
+unsafe extern "system" fn band_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
+ if msg < 0x0400 && msg != WM_COPYDATA {
+ return unsafe { DefWindowProcW(hwnd, msg, wp, lp) };
+ }
+ let explorer = EXPLORER_BAND.with(Cell::get);
+ let mut answer = 0usize;
+ if explorer != 0 {
+ unsafe {
+ if InSendMessage().as_bool() || msg == WM_COPYDATA {
+ let _ = SendMessageTimeoutW(hwnd_of(explorer), msg, wp, lp, SMTO_ABORTIFHUNG, FORWARD_TIMEOUT_MS, Some(&mut answer));
+ } else {
+ let _ = PostMessageW(Some(hwnd_of(explorer)), msg, wp, lp);
+ }
+ }
+ }
+ if msg == crate::dock::badges::MSG_OVERLAY && crate::dock::badges::enabled() {
+ let _ = catch_unwind(|| {
+ let picture = if lp.0 == 0 { None } else { read_icon(lp.0) };
+ crate::dock::badges::overlay(wp.0 as isize, picture, |h| unsafe { IsWindow(Some(hwnd_of(h))).as_bool() });
+ });
+ }
+ LRESULT(answer as isize)
+}
// ---------------------------------------------------------------- the window procedure