Skip to content

A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.

feat(notifications): add macOS-style notification banners, dock badges, and attention bounce

Saivarshith Mitukula52871a6d040f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 15c70dc..e8ced8f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,12 @@ copia la sección de la versión que se publica a la release de GitHub.
### English
+- Added macOS-style glass notification banners supporting configurable screen positions (top-right or bottom-right), auto-dismiss with hover pause, click-to-activate, and dismiss button or middle-click.
+- Added red unread notification count badges on dock icons, cleared automatically when the app is focused or dismissed.
+- Added dock icon attention bounce on shell alert events (`HSHELL_FLASH`), respecting Windows reduced-motion settings.
+- Added Do Not Disturb (Focus) toggle in the menu bar to silence banners while preserving dock badges.
+- Added local notification CLI and IPC: `muelle notify --title <TITLE> --body <BODY> [--app <APP>] [--icon <PATH>] [--duration <SECS>]` via lightweight zero-polling `WM_COPYDATA`.
+- New Settings → Notifications section with toggles for banners, position, duration, badges, attention bounce, and Do Not Disturb.
- Hover previews on dock icons now display a close button ("✕") at the top-left
corner on hover with localized tooltip ("Close window"), allowing closing
individual windows gracefully via WM_CLOSE without activating them.
@@ -31,6 +37,12 @@ copia la sección de la versión que se publica a la release de GitHub.
### Español
+- Incorporadas alertas en banners de cristal estilo macOS con posición configurable (superior o inferior derecha), desaparición automática con pausa al pasar el cursor, clic para activar y botón de cierre o clic central para descartar.
+- Incorporadas insignias rojas de contador de notificaciones pendientes en los iconos del dock, eliminadas automáticamente al enfocar la app o descartar sus avisos.
+- Incorporada animación de rebote de atención en el dock cuando una app solicita atención (`HSHELL_FLASH`), respetando las preferencias de movimiento reducido de Windows.
+- Incorporado conmutador de concentración / «No molestar» en la barra superior para silenciar avisos manteniendo las insignias en el dock.
+- Incorporada interfaz local por línea de comandos e IPC: `muelle notify --title <TÍTULO> --body <CUERPO> [--app <APP>] [--icon <RUTA>] [--duration <SEGS>]` mediante `WM_COPYDATA` ligero y sin sondeos.
+- Nueva sección Ajustes → Notificaciones con opciones de banners, posición, duración, insignias, rebote de atención y No molestar.
- Las previsualizaciones al pasar el cursor sobre los iconos del dock ahora muestran
un botón de cerrar («✕») en la esquina superior izquierda al posarse sobre ellas
con mensaje localizado («Cerrar ventana»), permitiendo cerrar ventanas individuales
diff --git a/Cargo.lock b/Cargo.lock
index 29fcef0..90cd28e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -242,12 +242,6 @@ version = "0.21.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
-[[package]]
-name = "base64"
-version = "0.22.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
-
[[package]]
name = "base64"
version = "0.23.1"
@@ -2262,7 +2256,6 @@ name = "muelle"
version = "0.1.15"
dependencies = [
"anyhow",
- "base64 0.22.1",
"chrono",
"muelle-config",
"muelle-core",
diff --git a/README.es.md b/README.es.md
index 889e66f..ee98984 100644
--- a/README.es.md
+++ b/README.es.md
@@ -151,5 +151,6 @@ dos tipos de conexión de red, ambas opcionales:
y Flash; Antigravity se consulta mediante su servicio local. Las credenciales
permanecen en memoria; Muelle no las guarda. Se desactiva en Ajustes → Barra
superior → *Mostrar uso de proveedores de IA*.
+- **Notificaciones:** el contenido y los avisos de las notificaciones se procesan exclusivamente en la memoria local de tu equipo; nunca se escriben en disco, ni se guardan en registros ni se transmiten por la red.
Detalles: [muellee.vercel.app/privacy](https://muellee.vercel.app/privacy).
diff --git a/README.md b/README.md
index 09f5470..ca1ef3b 100644
--- a/README.md
+++ b/README.md
@@ -153,5 +153,6 @@ project. It makes two kinds of network requests, both optional:
available; Antigravity is queried through its local service. Credentials stay
in memory and are never stored by Muelle. Turn it off in Settings → Menu bar
→ *Show AI provider usage*.
+- **Notifications:** notification content and banners are processed strictly in memory on your local machine and are never written to disk, saved in log files, or transmitted over the network.
Details: [muellee.vercel.app/privacy](https://muellee.vercel.app/privacy).
diff --git a/apps/dock/Cargo.toml b/apps/dock/Cargo.toml
index aa3edc1..21421db 100644
--- a/apps/dock/Cargo.toml
+++ b/apps/dock/Cargo.toml
@@ -15,7 +15,6 @@ winresource = "0.1"
[dependencies]
anyhow.workspace = true
-base64 = "0.22"
chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] }
muelle-config.workspace = true
muelle-core.workspace = true
@@ -48,6 +47,7 @@ windows = { workspace = true, features = [
"Win32_Graphics_Gdi",
"Win32_Security",
"Win32_System_Com",
+ "Win32_System_DataExchange",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_Console",
"Win32_System_LibraryLoader",
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index 2a98caa..eea6378 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -78,10 +78,10 @@ use windows::{
PostMessageW, PostQuitMessage, RegisterClassW, RegisterShellHookWindow,
RegisterWindowMessageW, SM_CXDRAG, SM_SWAPBUTTON, SWP_HIDEWINDOW, SWP_NOACTIVATE,
SWP_SHOWWINDOW, SetTimer, SetWindowPos, WINDOW_EX_STYLE, WINEVENT_OUTOFCONTEXT,
- WINEVENT_SKIPOWNPROCESS, WM_APP, WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY,
- WM_DISPLAYCHANGE, WM_DPICHANGED, WM_INITMENUPOPUP, WM_LBUTTONDOWN, WM_LBUTTONUP,
- WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEACTIVATE, WM_MOUSEMOVE, WM_QUIT,
- WM_RBUTTONUP, WM_SETTINGCHANGE, WM_TIMER, WNDCLASSW, WS_EX_LAYERED,
+ WINEVENT_SKIPOWNPROCESS, WM_APP, WM_CAPTURECHANGED, WM_CLOSE, WM_COPYDATA,
+ WM_DESTROY, WM_DISPLAYCHANGE, WM_DPICHANGED, WM_INITMENUPOPUP, WM_LBUTTONDOWN,
+ WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEACTIVATE, WM_MOUSEMOVE,
+ WM_QUIT, WM_RBUTTONUP, WM_SETTINGCHANGE, WM_TIMER, WNDCLASSW, WS_EX_LAYERED,
WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST,
WS_EX_TRANSPARENT, WS_POPUP,
},
@@ -102,6 +102,7 @@ use crate::{
menu::{self, MenuItem},
menubar::MenuBar,
multi_window_view::{MultiWindowAction, MultiWindowView},
+ notification_banner,
scene::{Drag, Frame, Scene, SceneInput, SlotContent, Theme},
shell_work::{self, Action as ShellAction},
strings::{self, text},
@@ -361,7 +362,7 @@ fn window_of(id: &str) -> Option<isize> {
/// Work deferred until the app state is released. These calls may open a modal
/// loop (a menu, shell error dialog, or recycle bin confirmation) that dispatches
/// messages back to the dock.
-enum Outside {
+pub(crate) enum Outside {
Open(String),
OpenStart,
Activate(Vec<isize>),
@@ -395,7 +396,7 @@ enum Outside {
ShowDesktop,
}
-struct MenuRequest {
+pub(crate) struct MenuRequest {
gfx: Gfx,
target: MenuTarget,
items: Vec<MenuItem>,
@@ -616,7 +617,7 @@ struct ReorderMotion {
offsets: Vec<f32>,
}
-struct App {
+pub(crate) struct App {
visual: HWND,
input: HWND,
gfx: Gfx,
@@ -674,6 +675,7 @@ struct App {
pointed: bool,
pending_drop: Option<Outside>,
bounces: HashMap<String, Bounce>,
+ notifications: muelle_core::notifications::NotificationQueue,
/// Minimized windows, in the order they were minimized.
minimized: Vec<isize>,
thumbnails: Thumbnails,
@@ -1200,10 +1202,28 @@ impl App {
let room = px(SHADOW_ROOM);
let (room_x, room_top) = (room + side_growth, rise + px(LABEL_ROOM));
+ let notify_badges: Vec<Option<LabelBrush>> = if self.config.notification_badges {
+ self.entries
+ .iter()
+ .map(|entry| {
+ entry.id.as_ref().and_then(|id| {
+ let count = self.notifications.badge_count(id);
+ if count > 0 {
+ self.gfx.notification_badge_brush(count, scale).ok()
+ } else {
+ None
+ }
+ })
+ })
+ .collect()
+ } else {
+ (0..self.entries.len()).map(|_| None).collect()
+ };
let contents: Vec<SlotContent<'_>> = self
.entries
.iter()
- .map(|entry| {
+ .enumerate()
+ .map(|(index, entry)| {
let asset = entry.id.as_ref().and_then(|id| self.assets.get(id));
let badge = entry
.id
@@ -1212,11 +1232,13 @@ impl App {
.and_then(|hwnd| self.windows.iter().find(|window| window.hwnd == hwnd))
.and_then(|window| self.assets.get(&window.app_id))
.and_then(|asset| asset.icon.as_ref());
+ let notify_badge = notify_badges.get(index).and_then(|opt| opt.as_ref());
SlotContent {
icon: asset.and_then(|asset| asset.icon.as_ref()),
label: asset.and_then(|asset| asset.label.as_ref()),
running: entry.running && self.config.show_indicators,
badge,
+ notify_badge,
}
})
.collect();
@@ -1591,7 +1613,7 @@ impl App {
/// it flew in; otherwise it gets its system transitions back first, so it
/// returns with the system's restore animation (the next `sync` turns
/// them off again).
- fn activating(&mut self, windows: Vec<isize>) -> Option<Outside> {
+ pub(crate) fn activating(&mut self, windows: Vec<isize>) -> Option<Outside> {
if self.start_restore_flight(&windows) {
// `tick` restores the window when the genie reaches full size.
return None;
@@ -3595,11 +3617,136 @@ impl App {
return;
}
if let Some(window) = self.windows.iter().find(|window| window.hwnd == hwnd) {
+ let app_id = window.app_id.clone();
+ if self.config.muted_apps.contains(&app_id) {
+ return;
+ }
+ if self.config.notification_bounce && animations_enabled() {
+ self.start_bounce(app_id.clone(), Some(ATTENTION_HOPS * bounce::HOP_SECONDS));
+ }
+ if self.config.notification_badges {
+ let title = tracker::title(hwnd);
+ self.notifications.push(
+ app_id.clone(),
+ title.clone(),
+ title,
+ String::new(),
+ None,
+ Some(hwnd),
+ self.config.notification_duration as u64 * 1000,
+ self.config.notification_dnd || !self.config.notifications,
+ false,
+ );
+ let _ = self.render();
+ }
+ }
+ }
+
+ pub fn on_notification(&mut self, payload: muelle_shell::dock_link::NotificationPayload) {
+ if !self.config.notifications {
+ return;
+ }
+ let muted = self.config.muted_apps.contains(&payload.app_id);
+ if muted {
+ return;
+ }
+
+ let duration_ms = (payload.duration_secs.max(1) as u64) * 1000;
+ let dnd = self.config.notification_dnd;
+
+ let pushed = self.notifications.push(
+ payload.app_id.clone(),
+ payload.app_name.clone(),
+ payload.title.clone(),
+ payload.body.clone(),
+ payload.icon_path.clone(),
+ None,
+ duration_ms,
+ dnd,
+ false,
+ );
+
+ if self.config.notification_bounce && animations_enabled() {
self.start_bounce(
- window.app_id.clone(),
+ payload.app_id.clone(),
Some(ATTENTION_HOPS * bounce::HOP_SECONDS),
);
}
+
+ if self.config.notification_badges {
+ let _ = self.render();
+ }
+
+ if pushed.is_some() && !self.fullscreen {
+ let pos = match self.config.notification_position {
+ muelle_config::NotificationPosition::TopRight => {
+ muelle_core::notifications::BannerPosition::TopRight
+ }
+ muelle_config::NotificationPosition::BottomRight => {
+ muelle_core::notifications::BannerPosition::BottomRight
+ }
+ };
+ let work_area = primary_monitor().map_or(
+ Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 1920.0,
+ height: 1080.0,
+ },
+ |m| Rect {
+ x: m.screen.left as f32,
+ y: m.screen.top as f32,
+ width: (m.screen.right - m.screen.left) as f32,
+ height: (m.screen.bottom - m.screen.top) as f32,
+ },
+ );
+ let scale = self.dock_monitor().map_or(1.0, |m| m.scale);
+ let theme = Theme::for_system(uses_light_theme(), transparency_enabled());
+ let _ = notification_banner::NotificationBannerView::ensure_or_create(
+ &self.gfx, pos, work_area, scale, theme,
+ );
+ let _ = notification_banner::NotificationBannerView::sync_queue(
+ &self.gfx,
+ &self.notifications,
+ );
+ }
+ }
+
+ pub fn dismiss_notification(&mut self, id: u64) {
+ self.notifications.dismiss(id);
+ let _ =
+ notification_banner::NotificationBannerView::sync_queue(&self.gfx, &self.notifications);
+ }
+
+ pub fn tick_notifications(&mut self, delta_ms: u64) {
+ let expired = self.notifications.tick(delta_ms);
+ if !expired.is_empty() {
+ let _ = notification_banner::NotificationBannerView::sync_queue(
+ &self.gfx,
+ &self.notifications,
+ );
+ }
+ }
+
+ pub fn clear_notification_badge(&mut self, app_id: &str) {
+ if self.notifications.badge_count(app_id) > 0 {
+ self.notifications.clear_badge(app_id);
+ let _ = self.render();
+ }
+ }
+
+ pub fn toggle_dnd(&mut self) {
+ self.config.notification_dnd = !self.config.notification_dnd;
+ if self.config.notification_dnd {
+ notification_banner::NotificationBannerView::hide();
+ }
+ let mut patch = serde_json::Map::new();
+ patch.insert(
+ "notificationDnd".into(),
+ serde_json::Value::Bool(self.config.notification_dnd),
+ );
+ let _ = muelle_config::update_preferences(&muelle_config::default_path(), patch);
+ menu_bar_refresh();
}
/// Refreshes open windows and recomposes the dock if anything changed.
@@ -4060,6 +4207,10 @@ impl App {
fn on_foreground_changed(&mut self) -> Result<()> {
self.close_preview();
let foreground = tracker::foreground_window();
+ if let Some(window) = self.windows.iter().find(|w| w.hwnd == foreground) {
+ let app_id = window.app_id.clone();
+ self.clear_notification_badge(&app_id);
+ }
self.flights.retain(|flight| flight.is_current(foreground));
// The app roster can stay identical while its windows change z-order.
// Refresh their order so the next dock activation selects the actual
@@ -4100,13 +4251,13 @@ impl App {
/// Runs `action` on the app and logs failures; a transient failure must not
/// terminate the dock.
-fn with_app(what: &str, action: impl FnOnce(&mut App) -> Result<()>) {
+pub(crate) fn with_app(what: &str, action: impl FnOnce(&mut App) -> Result<()>) {
with_app_then(what, |app| action(app).map(|()| None));
}
/// Like `with_app`, but `action` can request work to perform after releasing
/// the app state (see [`Outside`]).
-fn with_app_then(what: &str, action: impl FnOnce(&mut App) -> Result<Option<Outside>>) {
+pub(crate) fn with_app_then(what: &str, action: impl FnOnce(&mut App) -> Result<Option<Outside>>) {
let outside = APP.with(|cell| {
// Modal calls run outside the borrow, so this should not happen. If it
// does, discard the message rather than terminating the dock.
@@ -4759,7 +4910,29 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
}
// A folder's submenu in the shortcuts folder's menu is about to open.
WM_INITMENUPOPUP if folder_menu::init_popup(HMENU(w.0 as *mut _)) => {}
- WM_DESTROY => unsafe { PostQuitMessage(0) },
+ WM_COPYDATA => {
+ let cds =
+ unsafe { &*(l.0 as *const windows::Win32::System::DataExchange::COPYDATASTRUCT) };
+ if cds.dwData == muelle_shell::dock_link::NOTIFY_DATA_TAG && cds.cbData > 0 {
+ let bytes = unsafe {
+ std::slice::from_raw_parts(cds.lpData as *const u8, cds.cbData as usize)
+ };
+ if let Some(payload) = std::str::from_utf8(bytes)
+ .ok()
+ .and_then(muelle_shell::dock_link::NotificationPayload::decode)
+ {
+ with_app("notificación", |app| {
+ app.on_notification(payload);
+ Ok(())
+ });
+ return LRESULT(1);
+ }
+ }
+ }
+ WM_DESTROY => {
+ notification_banner::NotificationBannerView::hide();
+ unsafe { PostQuitMessage(0) };
+ }
_ if SHELL_HOOK.get() == Some(&msg) => match w.0 {
// Changing the foreground window does not change the app list; it
// can only enter or exit full-screen mode.
@@ -4950,6 +5123,7 @@ pub fn run() -> Result<()> {
pointed: false,
pending_drop: None,
bounces: HashMap::new(),
+ notifications: muelle_core::notifications::NotificationQueue::new(),
minimized: Vec::new(),
thumbnails: Thumbnails::new(visual),
flights: Vec::new(),
diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rs
index 8f0733b..00b57b6 100644
--- a/apps/dock/src/gfx.rs
+++ b/apps/dock/src/gfx.rs
@@ -38,11 +38,12 @@ use windows::{
},
DirectWrite::{
DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL,
- DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_WEIGHT_SEMI_BOLD,
- DWRITE_MEASURING_MODE_NATURAL, DWRITE_PARAGRAPH_ALIGNMENT_CENTER,
- DWRITE_TEXT_ALIGNMENT_CENTER, DWRITE_TEXT_METRICS, DWRITE_TRIMMING,
- DWRITE_TRIMMING_GRANULARITY_CHARACTER, DWRITE_WORD_WRAPPING_NO_WRAP,
- DWriteCreateFactory, IDWriteFactory, IDWriteTextLayout,
+ DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_WEIGHT_NORMAL,
+ DWRITE_FONT_WEIGHT_SEMI_BOLD, DWRITE_MEASURING_MODE_NATURAL,
+ DWRITE_PARAGRAPH_ALIGNMENT_CENTER, DWRITE_TEXT_ALIGNMENT_CENTER,
+ DWRITE_TEXT_METRICS, DWRITE_TRIMMING, DWRITE_TRIMMING_GRANULARITY_CHARACTER,
+ DWRITE_WORD_WRAPPING_NO_WRAP, DWriteCreateFactory, IDWriteFactory,
+ IDWriteTextLayout,
},
Dxgi::{Common::DXGI_FORMAT_B8G8R8A8_UNORM, IDXGIDevice},
},
@@ -766,6 +767,189 @@ impl Gfx {
})
}
+ /// Red notification count badge (macOS style), e.g. "1", "4", "99+".
+ pub fn notification_badge_brush(&self, count: usize, scale: f32) -> Result<LabelBrush> {
+ let text = if count > 99 {
+ "99+".to_string()
+ } else {
+ count.to_string()
+ };
+ let font_size = 11.0 * scale;
+ let pad_h = 6.0 * scale;
+ let pad_v = 2.0 * scale;
+
+ let utf16: Vec<u16> = text.encode_utf16().collect();
+ let (layout, metrics) = unsafe {
+ let format = self.dwrite.CreateTextFormat(
+ text_font(),
+ None,
+ DWRITE_FONT_WEIGHT_BOLD,
+ DWRITE_FONT_STYLE_NORMAL,
+ DWRITE_FONT_STRETCH_NORMAL,
+ font_size,
+ w!(""),
+ )?;
+ let layout = self
+ .dwrite
+ .CreateTextLayout(&utf16, &format, 256.0, 128.0)?;
+ let mut metrics = DWRITE_TEXT_METRICS::default();
+ layout.GetMetrics(&mut metrics)?;
+ (layout, metrics)
+ };
+
+ let diameter = (metrics.height + 2.0 * pad_v).max(18.0 * scale).ceil();
+ let width = (metrics.width + 2.0 * pad_h).max(diameter).ceil();
+ let height = diameter;
+
+ let brush = self.draw(width as u32, height as u32, |dc| {
+ let radius = height / 2.0;
+ let body = D2D1_ROUNDED_RECT {
+ rect: D2D_RECT_F {
+ left: 0.0,
+ top: 0.0,
+ right: width,
+ bottom: height,
+ },
+ radiusX: radius,
+ radiusY: radius,
+ };
+ unsafe {
+ // macOS traffic-light red badge with slight border for separation
+ let bg_color = rgb(1.0, 0.23, 0.19, 1.0);
+ let bg_brush = dc.CreateSolidColorBrush(&bg_color, None)?;
+ dc.FillRoundedRectangle(&body, &bg_brush);
+
+ let text_color = rgb(1.0, 1.0, 1.0, 1.0);
+ let text_brush = dc.CreateSolidColorBrush(&text_color, None)?;
+ let text_origin = Vector2 {
+ X: ((width - metrics.width) / 2.0).floor(),
+ Y: ((height - metrics.height) / 2.0).floor(),
+ };
+ dc.DrawTextLayout(
+ text_origin,
+ &layout,
+ &text_brush,
+ D2D1_DRAW_TEXT_OPTIONS_NONE,
+ );
+ }
+ Ok(())
+ })?;
+
+ Ok(LabelBrush {
+ brush,
+ width,
+ height,
+ })
+ }
+
+ /// A glass notification card with title, body, and rounded corners.
+ pub fn notification_banner_brush(
+ &self,
+ title: &str,
+ body: &str,
+ width: f32,
+ height: f32,
+ scale: f32,
+ light: bool,
+ ) -> Result<CompositionSurfaceBrush> {
+ let title_utf16: Vec<u16> = title.encode_utf16().collect();
+ let body_utf16: Vec<u16> = body.encode_utf16().collect();
+ let avail_w = (width - 52.0 * scale).max(50.0);
+
+ let (title_layout, body_layout) = unsafe {
+ let t_format = self.dwrite.CreateTextFormat(
+ text_font(),
+ None,
+ DWRITE_FONT_WEIGHT_BOLD,
+ DWRITE_FONT_STYLE_NORMAL,
+ DWRITE_FONT_STRETCH_NORMAL,
+ 13.0 * scale,
+ w!(""),
+ )?;
+ let t_layout =
+ self.dwrite
+ .CreateTextLayout(&title_utf16, &t_format, avail_w, 24.0 * scale)?;
+
+ let b_format = self.dwrite.CreateTextFormat(
+ text_font(),
+ None,
+ DWRITE_FONT_WEIGHT_NORMAL,
+ DWRITE_FONT_STYLE_NORMAL,
+ DWRITE_FONT_STRETCH_NORMAL,
+ 11.5 * scale,
+ w!(""),
+ )?;
+ let b_layout =
+ self.dwrite
+ .CreateTextLayout(&body_utf16, &b_format, avail_w, 32.0 * scale)?;
+
+ (t_layout, b_layout)
+ };
+
+ self.draw(width as u32, height as u32, |dc| {
+ let rounded = D2D1_ROUNDED_RECT {
+ rect: D2D_RECT_F {
+ left: 0.0,
+ top: 0.0,
+ right: width,
+ bottom: height,
+ },
+ radiusX: 14.0 * scale,
+ radiusY: 14.0 * scale,
+ };
+ unsafe {
+ let fill_color = if light {
+ rgb(0.97, 0.97, 0.98, 0.94)
+ } else {
+ rgb(0.12, 0.12, 0.14, 0.92)
+ };
+ let brush = dc.CreateSolidColorBrush(&fill_color, None)?;
+ dc.FillRoundedRectangle(&rounded, &brush);
+
+ let border_color = if light {
+ rgb(0.0, 0.0, 0.0, 0.08)
+ } else {
+ rgb(1.0, 1.0, 1.0, 0.12)
+ };
+ let border_brush = dc.CreateSolidColorBrush(&border_color, None)?;
+ dc.DrawRoundedRectangle(&rounded, &border_brush, 1.0, None);
+
+ let title_color = if light {
+ rgb(0.08, 0.08, 0.09, 0.95)
+ } else {
+ rgb(0.95, 0.95, 0.97, 0.98)
+ };
+ let title_brush = dc.CreateSolidColorBrush(&title_color, None)?;
+ dc.DrawTextLayout(
+ Vector2 {
+ X: 16.0 * scale,
+ Y: 12.0 * scale,
+ },
+ &title_layout,
+ &title_brush,
+ D2D1_DRAW_TEXT_OPTIONS_NONE,
+ );
+
+ let body_color = if light {
+ rgb(0.35, 0.35, 0.38, 0.90)
+ } else {
+ rgb(0.72, 0.72, 0.75, 0.90)
+ };
+ let body_brush = dc.CreateSolidColorBrush(&body_color, None)?;
+ dc.DrawTextLayout(
+ Vector2 {
+ X: 16.0 * scale,
+ Y: 34.0 * scale,
+ },
+ &body_layout,
+ &body_brush,
+ D2D1_DRAW_TEXT_OPTIONS_NONE,
+ );
+ }
+ Ok(())
+ })
+ }
+
/// Start tile: a 3x3 grid of rounded squares on a blue gradient, in the
/// style of the other dock icons (no Windows logo: it is a trademark).
pub fn start_brush(&self, side: u32) -> Result<CompositionSurfaceBrush> {
diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rs
index 0bd9fdd..cdaef01 100644
--- a/apps/dock/src/main.rs
+++ b/apps/dock/src/main.rs
@@ -25,6 +25,7 @@ mod media;
mod menu;
mod menubar;
mod multi_window_view;
+mod notification_banner;
mod scene;
mod shell_work;
mod strings;
@@ -76,7 +77,65 @@ fn main() -> Result<()> {
[guard::FLAG, pid] => guard::run(pid.parse().context("pid no válido")?),
["--usage-worker"] => usage::worker_main(),
[shell_work::FLAG] => shell_work::worker_main(),
- _ => bail!("uso: muelle [--quit | --restore | --autostart on|off]"),
+ ["notify", rest @ ..] | ["--notify", rest @ ..] => handle_notify_cli(rest),
+ _ => bail!("uso: muelle [--quit | --restore | --autostart on|off | notify]"),
+ }
+}
+
+fn handle_notify_cli(args: &[&str]) -> Result<()> {
+ let mut title = String::new();
+ let mut body = String::new();
+ let mut app = "Terminal".to_string();
+ let mut icon: Option<String> = None;
+ let mut duration_secs = 5u32;
+
+ let mut i = 0;
+ while i < args.len() {
+ match args[i] {
+ "--title" if i + 1 < args.len() => {
+ title = args[i + 1].to_string();
+ i += 2;
+ }
+ "--body" if i + 1 < args.len() => {
+ body = args[i + 1].to_string();
+ i += 2;
+ }
+ "--app" if i + 1 < args.len() => {
+ app = args[i + 1].to_string();
+ i += 2;
+ }
+ "--icon" if i + 1 < args.len() => {
+ icon = Some(args[i + 1].to_string());
+ i += 2;
+ }
+ "--duration" if i + 1 < args.len() => {
+ duration_secs = args[i + 1].parse().unwrap_or(5);
+ i += 2;
+ }
+ _ => i += 1,
+ }
+ }
+
+ if title.is_empty() && body.is_empty() {
+ bail!(
+ "uso: muelle notify --title <título> --body <cuerpo> [--app <app>] [--icon <ruta>] [--duration <segundos>]"
+ );
+ }
+
+ let payload = muelle_shell::dock_link::NotificationPayload {
+ app_id: app.clone(),
+ app_name: app,
+ title,
+ body,
+ icon_path: icon,
+ duration_secs,
+ };
+
+ if muelle_shell::dock_link::post_notification(&payload) {
+ println!("Notificación enviada a Muelle.");
+ Ok(())
+ } else {
+ bail!("No se pudo entregar la notificación: Muelle no está en ejecución.");
}
}
diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rs
index 9767a3c..9997596 100644
--- a/apps/dock/src/menubar.rs
+++ b/apps/dock/src/menubar.rs
@@ -138,12 +138,14 @@ mod glyph {
pub const HIDDEN_ICONS: char = '\u{E70E}';
pub const MICROPHONE: char = '\u{E720}';
pub const CAMERA: char = '\u{E722}';
+ pub const FOCUS: char = '\u{E708}';
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Action {
QuickSettings,
Notifications,
+ ToggleDnd,
Sound,
Search,
TaskView,
@@ -1331,6 +1333,12 @@ impl MenuBar {
match hit.map(|(_, _, action)| *action) {
Some(Action::QuickSettings) => launcher::open_quick_settings(),
Some(Action::Notifications) => launcher::open_notifications(),
+ Some(Action::ToggleDnd) => {
+ crate::app::with_app("toggle dnd", |app| {
+ app.toggle_dnd();
+ Ok(())
+ });
+ }
Some(Action::Sound) => launcher::open_sound(),
Some(Action::Search) => launcher::open_search(),
Some(Action::TaskView) => launcher::open_task_view(),
@@ -1543,6 +1551,7 @@ impl MenuBar {
Action::Notifications,
),
(gfx.control_center_brush(scale, ink)?, Action::QuickSettings),
+ (symbol(&[(glyph::FOCUS, 1.0)])?, Action::ToggleDnd),
];
// Privacy indicators, as the Windows tray shows them: something is
// using the microphone or camera right now.
diff --git a/apps/dock/src/notification_banner.rs b/apps/dock/src/notification_banner.rs
new file mode 100644
index 0000000..4626e74
--- /dev/null
+++ b/apps/dock/src/notification_banner.rs
@@ -0,0 +1,485 @@
+use std::cell::RefCell;
+
+use muelle_core::{
+ layout::Rect,
+ notifications::{
+ BANNER_HEIGHT, BANNER_WIDTH, BannerPosition, NotificationQueue, banner_bounds,
+ banner_close_button_bounds,
+ },
+};
+use windows::{
+ UI::Composition::{
+ CompositionSurfaceBrush, ContainerVisual, Desktop::DesktopWindowTarget, SpriteVisual,
+ },
+ Win32::{
+ Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},
+ System::{LibraryLoader::GetModuleHandleW, WinRT::Composition::ICompositorDesktopInterop},
+ UI::{
+ Input::KeyboardAndMouse::{TME_LEAVE, TRACKMOUSEEVENT, TrackMouseEvent},
+ WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, DestroyWindow, GetCursorPos, GetWindowRect,
+ HWND_TOPMOST, IDC_ARROW, KillTimer, LoadCursorW, MA_NOACTIVATE, RegisterClassW,
+ SWP_NOACTIVATE, SWP_SHOWWINDOW, SetTimer, SetWindowPos, WM_DESTROY, WM_LBUTTONUP,
+ WM_MBUTTONUP, WM_MOUSEACTIVATE, WM_MOUSEMOVE, WM_TIMER, WNDCLASSW,
+ WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST,
+ WS_POPUP,
+ },
+ },
+ },
+ core::{Interface, Result, w},
+};
+use windows_numerics::{Vector2, Vector3};
+
+use crate::{gfx::Gfx, scene::Theme};
+
+const WM_MOUSELEAVE: u32 = 0x02A3;
+const TICK_TIMER: usize = 1;
+const TICK_INTERVAL_MS: u32 = 100;
+
+thread_local! {
+ static BANNER_VIEW: RefCell<Option<NotificationBannerView>> = const { RefCell::new(None) };
+}
+
+pub enum BannerAction {
+ Activate(Option<isize>, String),
+ Dismiss(u64),
+}
+
+struct BannerCardVisual {
+ id: u64,
+ target_hwnd: Option<isize>,
+ app_id: String,
+ root: ContainerVisual,
+ close_btn: SpriteVisual,
+ close_normal: CompositionSurfaceBrush,
+ close_hover: CompositionSurfaceBrush,
+}
+
+pub struct NotificationBannerView {
+ hwnd: HWND,
+ _target: DesktopWindowTarget,
+ root: ContainerVisual,
+ cards: Vec<BannerCardVisual>,
+ position: BannerPosition,
+ work_area: Rect,
+ scale: f32,
+ theme: Theme,
+ hovered_card: Option<usize>,
+ hovered_close: Option<usize>,
+}
+
+impl NotificationBannerView {
+ pub fn ensure_or_create(
+ gfx: &Gfx,
+ position: BannerPosition,
+ work_area: Rect,
+ scale: f32,
+ theme: Theme,
+ ) -> Result<()> {
+ BANNER_VIEW.with(|cell| {
+ let mut borrow = cell.borrow_mut();
+ if borrow.is_none() {
+ let view = Self::new(gfx, position, work_area, scale, theme)?;
+ *borrow = Some(view);
+ } else if let Some(view) = borrow.as_mut() {
+ view.position = position;
+ view.work_area = work_area;
+ view.scale = scale;
+ view.theme = theme;
+ }
+ Ok(())
+ })
+ }
+
+ fn new(
+ gfx: &Gfx,
+ position: BannerPosition,
+ work_area: Rect,
+ scale: f32,
+ theme: Theme,
+ ) -> Result<Self> {
+ let hwnd = unsafe {
+ let instance = GetModuleHandleW(None)?;
+ let class = w!("MuelleNotificationBanner");
+ RegisterClassW(&WNDCLASSW {
+ lpfnWndProc: Some(banner_window_proc),
+ hInstance: instance.into(),
+ hCursor: LoadCursorW(None, IDC_ARROW)?,
+ lpszClassName: class,
+ ..Default::default()
+ });
+
+ CreateWindowExW(
+ WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP,
+ class,
+ w!("Muelle Notification Banner"),
+ WS_POPUP,
+ 0,
+ 0,
+ 0,
+ 0,
+ None,
+ None,
+ Some(instance.into()),
+ None,
+ )?
+ };
+
+ let target = unsafe {
+ gfx.compositor
+ .cast::<ICompositorDesktopInterop>()?
+ .CreateDesktopWindowTarget(hwnd, true)?
+ };
+ let root = gfx.compositor.CreateContainerVisual()?;
+ target.SetRoot(&root)?;
+
+ unsafe {
+ SetTimer(Some(hwnd), TICK_TIMER, TICK_INTERVAL_MS, None);
+ }
+
+ Ok(Self {
+ hwnd,
+ _target: target,
+ root,
+ cards: Vec::new(),
+ position,
+ work_area,
+ scale,
+ theme,
+ hovered_card: None,
+ hovered_close: None,
+ })
+ }
+
+ pub fn sync_queue(gfx: &Gfx, queue: &NotificationQueue) -> Result<()> {
+ BANNER_VIEW.with(|cell| {
+ let mut borrow = cell.borrow_mut();
+ if let Some(view) = borrow.as_mut() {
+ view.rebuild(gfx, queue)?;
+ }
+ Ok(())
+ })
+ }
+
+ pub fn hide() {
+ BANNER_VIEW.with(|cell| {
+ let mut borrow = cell.borrow_mut();
+ if let Some(view) = borrow.take() {
+ unsafe {
+ KillTimer(Some(view.hwnd), TICK_TIMER).ok();
+ DestroyWindow(view.hwnd).ok();
+ }
+ }
+ });
+ }
+
+ fn rebuild(&mut self, gfx: &Gfx, queue: &NotificationQueue) -> Result<()> {
+ let items = queue.visible_items();
+ if items.is_empty() {
+ self.root.Children()?.RemoveAll()?;
+ self.cards.clear();
+ unsafe {
+ SetWindowPos(self.hwnd, Some(HWND_TOPMOST), 0, 0, 0, 0, SWP_NOACTIVATE).ok();
+ }
+ return Ok(());
+ }
+
+ let first_rect = banner_bounds(0, self.position, self.work_area, self.scale);
+ let last_rect = banner_bounds(items.len() - 1, self.position, self.work_area, self.scale);
+
+ let min_x = first_rect.x.min(last_rect.x) as i32;
+ let min_y = first_rect.y.min(last_rect.y) as i32;
+ let max_x = (first_rect.x + first_rect.width).max(last_rect.x + last_rect.width) as i32;
+ let max_y = (first_rect.y + first_rect.height).max(last_rect.y + last_rect.height) as i32;
+
+ unsafe {
+ SetWindowPos(
+ self.hwnd,
+ Some(HWND_TOPMOST),
+ min_x,
+ min_y,
+ max_x - min_x,
+ max_y - min_y,
+ SWP_NOACTIVATE | SWP_SHOWWINDOW,
+ )?;
+ }
+
+ self.root.Children()?.RemoveAll()?;
+ self.cards.clear();
+
+ let c = &gfx.compositor;
+
+ for (index, item) in items.iter().enumerate() {
+ let rect = banner_bounds(index, self.position, self.work_area, self.scale);
+ let local_x = rect.x - (min_x as f32);
+ let local_y = rect.y - (min_y as f32);
+
+ let card = c.CreateContainerVisual()?;
+ card.SetOffset(Vector3 {
+ X: local_x,
+ Y: local_y,
+ Z: 0.0,
+ })?;
+ card.SetSize(Vector2 {
+ X: rect.width,
+ Y: rect.height,
+ })?;
+
+ // Render glass card brush with title and body
+ let banner_brush = gfx
+ .notification_banner_brush(
+ &item.title,
+ &item.body,
+ rect.width,
+ rect.height,
+ self.scale,
+ self.theme.light,
+ )
+ .map_err(|e| {
+ windows::core::Error::new(windows::core::HRESULT(-1), e.to_string())
+ })?;
+
+ let bg_visual = c.CreateSpriteVisual()?;
+ bg_visual.SetSize(Vector2 {
+ X: rect.width,
+ Y: rect.height,
+ })?;
+ bg_visual.SetBrush(&banner_brush)?;
+ card.Children()?.InsertAtBottom(&bg_visual)?;
+
+ // Close button ("✕") in top-right corner
+ let btn_bounds = banner_close_button_bounds(rect, self.scale);
+ let btn_side = btn_bounds.width as u32;
+ let close_normal = gfx
+ .close_button_brush(btn_side, false, self.theme.light)
+ .map_err(|e| {
+ windows::core::Error::new(windows::core::HRESULT(-1), e.to_string())
+ })?;
+ let close_hover = gfx
+ .close_button_brush(btn_side, true, self.theme.light)
+ .map_err(|e| {
+ windows::core::Error::new(windows::core::HRESULT(-1), e.to_string())
+ })?;
+
+ let close_btn = c.CreateSpriteVisual()?;
+ close_btn.SetBrush(&close_normal)?;
+ close_btn.SetSize(Vector2 {
+ X: btn_bounds.width,
+ Y: btn_bounds.height,
+ })?;
+ close_btn.SetOffset(Vector3 {
+ X: btn_bounds.x,
+ Y: btn_bounds.y,
+ Z: 0.0,
+ })?;
+ card.Children()?.InsertAtTop(&close_btn)?;
+
+ self.root.Children()?.InsertAtTop(&card)?;
+
+ self.cards.push(BannerCardVisual {
+ id: item.id,
+ target_hwnd: item.target_hwnd,
+ app_id: item.app_id.clone(),
+ root: card,
+ close_btn,
+ close_normal,
+ close_hover,
+ });
+ }
+
+ Ok(())
+ }
+
+ fn hit_test(&self, point: POINT) -> (Option<usize>, Option<usize>) {
+ let width = BANNER_WIDTH * self.scale;
+ let height = BANNER_HEIGHT * self.scale;
+
+ for (index, card) in self.cards.iter().enumerate() {
+ let offset = card.root.Offset().unwrap_or(Vector3::default());
+ let card_rect = Rect {
+ x: offset.X,
+ y: offset.Y,
+ width,
+ height,
+ };
+
+ let pt_x = point.x as f32;
+ let pt_y = point.y as f32;
+
+ if pt_x >= card_rect.x
+ && pt_x <= card_rect.x + card_rect.width
+ && pt_y >= card_rect.y
+ && pt_y <= card_rect.y + card_rect.height
+ {
+ let btn_rect = banner_close_button_bounds(card_rect, self.scale);
+ let btn_local_x = pt_x - card_rect.x;
+ let btn_local_y = pt_y - card_rect.y;
+
+ if btn_local_x >= btn_rect.x
+ && btn_local_x <= btn_rect.x + btn_rect.width
+ && btn_local_y >= btn_rect.y
+ && btn_local_y <= btn_rect.y + btn_rect.height
+ {
+ return (Some(index), Some(index));
+ }
+ return (Some(index), None);
+ }
+ }
+ (None, None)
+ }
+
+ fn on_mouse_move(&mut self, point: POINT) -> Option<u64> {
+ let (card_idx, close_idx) = self.hit_test(point);
+
+ if self.hovered_close != close_idx {
+ if let Some(card) = self.hovered_close.and_then(|prev| self.cards.get(prev)) {
+ let _ = card.close_btn.SetBrush(&card.close_normal);
+ }
+ if let Some(card) = close_idx.and_then(|curr| self.cards.get(curr)) {
+ let _ = card.close_btn.SetBrush(&card.close_hover);
+ }
+ self.hovered_close = close_idx;
+ }
+
+ self.hovered_card = card_idx;
+ card_idx.and_then(|idx| self.cards.get(idx).map(|c| c.id))
+ }
+
+ fn on_click(&mut self, point: POINT) -> Option<BannerAction> {
+ let (card_idx, close_idx) = self.hit_test(point);
+ if let Some(card) = close_idx.and_then(|close| self.cards.get(close)) {
+ Some(BannerAction::Dismiss(card.id))
+ } else {
+ card_idx
+ .and_then(|card| self.cards.get(card))
+ .map(|card_visual| {
+ BannerAction::Activate(card_visual.target_hwnd, card_visual.app_id.clone())
+ })
+ }
+ }
+}
+
+pub fn handle_mouse_move(point: POINT) -> Option<u64> {
+ BANNER_VIEW.with(|cell| {
+ let mut borrow = cell.borrow_mut();
+ borrow.as_mut().and_then(|v| v.on_mouse_move(point))
+ })
+}
+
+pub fn handle_click(point: POINT) -> Option<BannerAction> {
+ BANNER_VIEW.with(|cell| {
+ let mut borrow = cell.borrow_mut();
+ borrow.as_mut().and_then(|v| v.on_click(point))
+ })
+}
+
+unsafe extern "system" fn banner_window_proc(
+ hwnd: HWND,
+ msg: u32,
+ w: WPARAM,
+ l: LPARAM,
+) -> LRESULT {
+ match msg {
+ WM_MOUSEACTIVATE => LRESULT(MA_NOACTIVATE as isize),
+ WM_MOUSEMOVE => {
+ unsafe {
+ let _ = TrackMouseEvent(&mut TRACKMOUSEEVENT {
+ cbSize: size_of::<TRACKMOUSEEVENT>() as u32,
+ dwFlags: TME_LEAVE,
+ hwndTrack: hwnd,
+ dwHoverTime: 0,
+ });
+ }
+ let mut pt = POINT::default();
+ unsafe {
+ let _ = GetCursorPos(&mut pt);
+ };
+ let mut rect = RECT::default();
+ unsafe {
+ let _ = GetWindowRect(hwnd, &mut rect);
+ };
+ let local_pt = POINT {
+ x: pt.x - rect.left,
+ y: pt.y - rect.top,
+ };
+ handle_mouse_move(local_pt);
+ LRESULT(0)
+ }
+ WM_MOUSELEAVE => {
+ handle_mouse_move(POINT { x: -999, y: -999 });
+ LRESULT(0)
+ }
+ WM_LBUTTONUP => {
+ let mut pt = POINT::default();
+ unsafe {
+ let _ = GetCursorPos(&mut pt);
+ };
+ let mut rect = RECT::default();
+ unsafe {
+ let _ = GetWindowRect(hwnd, &mut rect);
+ };
+ let local_pt = POINT {
+ x: pt.x - rect.left,
+ y: pt.y - rect.top,
+ };
+ if let Some(action) = handle_click(local_pt) {
+ match action {
+ BannerAction::Dismiss(id) => {
+ crate::app::with_app("dismiss banner", |app| {
+ app.dismiss_notification(id);
+ Ok(())
+ });
+ }
+ BannerAction::Activate(target_hwnd, app_id) => {
+ crate::app::with_app_then("activate notification", |app| {
+ let outside = if let Some(h) = target_hwnd {
+ app.activating(vec![h])
+ } else {
+ None
+ };
+ app.clear_notification_badge(&app_id);
+ Ok(outside)
+ });
+ }
+ }
+ }
+ LRESULT(0)
+ }
+ WM_MBUTTONUP => {
+ let mut pt = POINT::default();
+ unsafe {
+ let _ = GetCursorPos(&mut pt);
+ };
+ let mut rect = RECT::default();
+ unsafe {
+ let _ = GetWindowRect(hwnd, &mut rect);
+ };
+ let local_pt = POINT {
+ x: pt.x - rect.left,
+ y: pt.y - rect.top,
+ };
+ if let Some(action) = handle_click(local_pt) {
+ let id = match action {
+ BannerAction::Dismiss(id) => id,
+ BannerAction::Activate(_, _) => 0,
+ };
+ if id != 0 {
+ crate::app::with_app("middle click dismiss banner", |app| {
+ app.dismiss_notification(id);
+ Ok(())
+ });
+ }
+ }
+ LRESULT(0)
+ }
+ WM_TIMER if w.0 == TICK_TIMER => {
+ crate::app::with_app("tick notifications", |app| {
+ app.tick_notifications(TICK_INTERVAL_MS as u64);
+ Ok(())
+ });
+ LRESULT(0)
+ }
+ WM_DESTROY => LRESULT(0),
+ _ => unsafe { DefWindowProcW(hwnd, msg, w, l) },
+ }
+}
diff --git a/apps/dock/src/scene.rs b/apps/dock/src/scene.rs
index 775a338..d6ac158 100644
--- a/apps/dock/src/scene.rs
+++ b/apps/dock/src/scene.rs
@@ -204,6 +204,8 @@ pub struct SlotContent<'a> {
pub running: bool,
/// App icon shown in the corner of a minimized-window thumbnail.
pub badge: Option<&'a CompositionSurfaceBrush>,
+ /// Red notification count badge in the top-right corner.
+ pub notify_badge: Option<&'a LabelBrush>,
}
pub struct SceneInput<'a> {
@@ -290,6 +292,7 @@ pub struct Scene {
raised: Cell<Option<usize>>,
slots: Vec<SpriteVisual>,
badges: Vec<Option<SpriteVisual>>,
+ notify_badges: Vec<Option<Label>>,
indicators: Vec<Option<ShapeVisual>>,
labels: Vec<Option<Label>>,
remove_label: Option<Label>,
@@ -361,6 +364,7 @@ impl Scene {
let mut slots = Vec::with_capacity(layout.slots.len());
let mut badges = Vec::with_capacity(layout.slots.len());
+ let mut notify_badges = Vec::with_capacity(layout.slots.len());
let mut indicators = Vec::with_capacity(layout.slots.len());
let mut labels = Vec::with_capacity(layout.slots.len());
for (slot, item) in layout.slots.iter().zip(input.contents) {
@@ -384,6 +388,8 @@ impl Scene {
None => None,
});
+ notify_badges.push(item.notify_badge.map(|b| Label::new(c, b)).transpose()?);
+
indicators.push(if item.running {
let shape = c.CreateSpriteShapeWithGeometry(&dot)?;
shape.SetFillBrush(&dot_brush)?;
@@ -403,6 +409,9 @@ impl Scene {
.remove_label
.map(|label| Label::new(c, label))
.transpose()?;
+ for nb in notify_badges.iter().flatten() {
+ children.InsertAtTop(&nb.visual)?;
+ }
for label in labels.iter().flatten().chain(&remove_label) {
children.InsertAtTop(&label.visual)?;
}
@@ -426,6 +435,7 @@ impl Scene {
raised: Cell::new(None),
slots,
badges,
+ notify_badges,
indicators,
labels,
remove_label,
@@ -496,6 +506,13 @@ impl Scene {
fit(y + height - side * BADGE_INSIDE),
))?;
}
+ if let Some(Some(nb)) = self.notify_badges.get(index) {
+ nb.visual.SetIsVisible(dragged.is_none())?;
+ nb.visual.SetOffset(v3(
+ fit(x + width - nb.width * 0.7),
+ fit(y - nb.height * 0.25),
+ ))?;
+ }
if let Some(Some(indicator)) = self.indicators.get(index) {
indicator.SetIsVisible(dragged.is_none())?;
indicator.SetOffset(v3(
diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsx
index 14bd0dc..5c6e33f 100644
--- a/apps/settings/src/App.tsx
+++ b/apps/settings/src/App.tsx
@@ -418,6 +418,62 @@ export function App() {
/>
</SubRow>
</Card>
+ ) : section === "notifications" ? (
+ <>
+ <Card>
+ <Row label={t.notificationsEnabled} hint={t.notificationsHint}>
+ <Toggle
+ label={t.notificationsEnabled}
+ checked={config.notifications}
+ onChange={(notifications) => update({ notifications })}
+ />
+ </Row>
+ <SubRow label={t.notificationPosition} open={config.notifications}>
+ <Segmented
+ label={t.notificationPosition}
+ value={config.notificationPosition}
+ options={[
+ { value: "top-right", label: t.notificationPositionTopRight },
+ { value: "bottom-right", label: t.notificationPositionBottomRight },
+ ]}
+ onChange={(notificationPosition) => update({ notificationPosition })}
+ />
+ </SubRow>
+ <SubRow label={t.notificationDuration} open={config.notifications}>
+ <Slider
+ label={t.notificationDuration}
+ min={2}
+ max={15}
+ value={config.notificationDuration}
+ after={`${config.notificationDuration}s`}
+ onChange={(notificationDuration) => update({ notificationDuration })}
+ />
+ </SubRow>
+ </Card>
+ <Card>
+ <Row label={t.notificationBadges} hint={t.notificationBadgesHint}>
+ <Toggle
+ label={t.notificationBadges}
+ checked={config.notificationBadges}
+ onChange={(notificationBadges) => update({ notificationBadges })}
+ />
+ </Row>
+ <Row label={t.notificationBounce} hint={t.notificationBounceHint}>
+ <Toggle
+ label={t.notificationBounce}
+ checked={config.notificationBounce}
+ onChange={(notificationBounce) => update({ notificationBounce })}
+ />
+ </Row>
+ <Row label={t.notificationDnd} hint={t.notificationDndHint}>
+ <Toggle
+ label={t.notificationDnd}
+ checked={config.notificationDnd}
+ onChange={(notificationDnd) => update({ notificationDnd })}
+ />
+ </Row>
+ </Card>
+ </>
) : (
<>
<Card>
@@ -513,7 +569,7 @@ function updateHint(t: Texts, state: UpdateState, version: string): string {
}
}
-const SECTIONS: readonly SectionId[] = ["dock", "windows", "menubar", "system"];
+const SECTIONS: readonly SectionId[] = ["dock", "windows", "menubar", "notifications", "system"];
function sectionTitle(t: Texts, section: SectionId): string {
switch (section) {
@@ -523,6 +579,8 @@ function sectionTitle(t: Texts, section: SectionId): string {
return t.windows;
case "menubar":
return t.menuBar;
+ case "notifications":
+ return t.notifications;
case "system":
return t.system;
}
diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.json
index f9e3e66..1e03eab 100644
--- a/apps/settings/src/i18n/en.json
+++ b/apps/settings/src/i18n/en.json
@@ -73,5 +73,18 @@
"shortcutsFolder": "Shortcuts folder",
"shortcutsFolderHint": "A folder at the right of the Dock: its contents open as a menu, with a submenu for each folder inside.",
"shortcutsFolderChoose": "Choose…",
- "shortcutsFolderRemove": "Remove"
+ "shortcutsFolderRemove": "Remove",
+ "notifications": "Notifications",
+ "notificationsEnabled": "Show notifications",
+ "notificationsHint": "Displays macOS-style glass notification banners for apps and alerts.",
+ "notificationPosition": "Position",
+ "notificationPositionTopRight": "Top right",
+ "notificationPositionBottomRight": "Bottom right",
+ "notificationDuration": "Banner duration",
+ "notificationBadges": "Badge app icons",
+ "notificationBadgesHint": "Show unread notification count badge on the Dock icon.",
+ "notificationBounce": "Bounce icon on alert",
+ "notificationBounceHint": "Bounces the Dock icon when an app requests attention.",
+ "notificationDnd": "Do Not Disturb",
+ "notificationDndHint": "Silences notification banners while keeping Dock badges."
}
diff --git a/apps/settings/src/i18n/es.json b/apps/settings/src/i18n/es.json
index 3d8a264..5f1110a 100644
--- a/apps/settings/src/i18n/es.json
+++ b/apps/settings/src/i18n/es.json
@@ -73,5 +73,18 @@
"shortcutsFolder": "Carpeta de accesos directos",
"shortcutsFolderHint": "Una carpeta a la derecha del Dock: su contenido se abre como un menú, con un submenú por cada carpeta que contiene.",
"shortcutsFolderChoose": "Elegir…",
- "shortcutsFolderRemove": "Quitar"
+ "shortcutsFolderRemove": "Quitar",
+ "notifications": "Notificaciones",
+ "notificationsEnabled": "Mostrar notificaciones",
+ "notificationsHint": "Muestra alertas en banners de cristal estilo macOS para aplicaciones.",
+ "notificationPosition": "Posición",
+ "notificationPositionTopRight": "Superior derecha",
+ "notificationPositionBottomRight": "Inferior derecha",
+ "notificationDuration": "Duración del banner",
+ "notificationBadges": "Insignias en los iconos",
+ "notificationBadgesHint": "Muestra el contador de notificaciones pendientes en el icono del Dock.",
+ "notificationBounce": "Animar icono al recibir alerta",
+ "notificationBounceHint": "Hace rebotar el icono en el Dock cuando la app solicita atención.",
+ "notificationDnd": "No molestar",
+ "notificationDndHint": "Silencia los banners de notificación manteniendo las insignias en el Dock."
}
diff --git a/apps/settings/src/i18n/fr.json b/apps/settings/src/i18n/fr.json
index 3aed5d4..ee995ba 100644
--- a/apps/settings/src/i18n/fr.json
+++ b/apps/settings/src/i18n/fr.json
@@ -73,5 +73,18 @@
"shortcutsFolder": "Dossier de raccourcis",
"shortcutsFolderHint": "Un dossier à droite du Dock : son contenu s'ouvre en menu, avec un sous-menu pour chaque dossier qu'il contient.",
"shortcutsFolderChoose": "Choisir…",
- "shortcutsFolderRemove": "Retirer"
+ "shortcutsFolderRemove": "Retirer",
+ "notifications": "Notifications",
+ "notificationsEnabled": "Afficher les notifications",
+ "notificationsHint": "Affiche des bannières de notification de style macOS pour les applications.",
+ "notificationPosition": "Position",
+ "notificationPositionTopRight": "En haut à droite",
+ "notificationPositionBottomRight": "En bas à droite",
+ "notificationDuration": "Durée de la bannière",
+ "notificationBadges": "Badges sur les icônes",
+ "notificationBadgesHint": "Affiche un badge de notifications non lues sur l'icône du Dock.",
+ "notificationBounce": "Animer l'icône lors d'une alerte",
+ "notificationBounceHint": "Fait rebondir l'icône dans le Dock lorsqu'une application demande de l'attention.",
+ "notificationDnd": "Ne pas déranger",
+ "notificationDndHint": "Désactive les bannières de notification tout en conservant les badges du Dock."
}
diff --git a/apps/settings/src/icons.tsx b/apps/settings/src/icons.tsx
index 8b10062..ec1a9d9 100644
--- a/apps/settings/src/icons.tsx
+++ b/apps/settings/src/icons.tsx
@@ -6,12 +6,13 @@
import type { ReactNode } from "react";
-export type SectionId = "dock" | "windows" | "menubar" | "system";
+export type SectionId = "dock" | "windows" | "menubar" | "notifications" | "system";
const TILES: Record<SectionId, [string, string]> = {
dock: ["#4aa3ff", "#0a6cf0"],
windows: ["#b57bff", "#7d3ff0"],
menubar: ["#ff9f45", "#f0640a"],
+ notifications: ["#ff453a", "#d70015"],
system: ["#a1a1a6", "#6e6e73"],
};
@@ -41,6 +42,14 @@ const GLYPHS: Record<SectionId, ReactNode> = {
<circle cx="16.8" cy="6.8" r="0.9" fill="#f0640a" />
</>
),
+ // A notification banner card.
+ notifications: (
+ <>
+ <rect x="4" y="6" width="16" height="12" rx="2" fill="#fff" opacity="0.55" />
+ <rect x="4" y="6" width="16" height="4" rx="1.6" fill="#fff" />
+ <circle cx="17" cy="8" r="1.5" fill="#d70015" />
+ </>
+ ),
// A gear.
system: (
<path
diff --git a/crates/muelle-core/src/lib.rs b/crates/muelle-core/src/lib.rs
index d7ce24c..705d973 100644
--- a/crates/muelle-core/src/lib.rs
+++ b/crates/muelle-core/src/lib.rs
@@ -4,6 +4,7 @@ pub mod bounce;
pub mod genie;
pub mod layout;
pub mod magnify;
+pub mod notifications;
pub mod preview;
pub mod roster;
pub mod spring;
diff --git a/crates/muelle-core/src/notifications.rs b/crates/muelle-core/src/notifications.rs
new file mode 100644
index 0000000..0af944d
--- /dev/null
+++ b/crates/muelle-core/src/notifications.rs
@@ -0,0 +1,374 @@
+use std::collections::HashMap;
+
+use crate::layout::Rect;
+
+/// Position of notification banners on the screen.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum BannerPosition {
+ #[default]
+ TopRight,
+ BottomRight,
+}
+
+/// A single notification message. Content remains strictly in-memory.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct NotificationItem {
+ pub id: u64,
+ pub app_id: String,
+ pub app_name: String,
+ pub title: String,
+ pub body: String,
+ pub icon_path: Option<String>,
+ pub target_hwnd: Option<isize>,
+ pub duration_ms: u64,
+ pub elapsed_ms: u64,
+ pub paused: bool,
+}
+
+impl NotificationItem {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ id: u64,
+ app_id: String,
+ app_name: String,
+ title: String,
+ body: String,
+ icon_path: Option<String>,
+ target_hwnd: Option<isize>,
+ duration_ms: u64,
+ ) -> Self {
+ Self {
+ id,
+ app_id,
+ app_name,
+ title,
+ body,
+ icon_path,
+ target_hwnd,
+ duration_ms: duration_ms.max(1000),
+ elapsed_ms: 0,
+ paused: false,
+ }
+ }
+}
+
+/// Maximum number of banners shown simultaneously.
+pub const MAX_VISIBLE_BANNERS: usize = 3;
+
+/// Manages active notifications, stacking, auto-dismiss timers, and dock badges.
+#[derive(Debug, Default)]
+pub struct NotificationQueue {
+ next_id: u64,
+ items: Vec<NotificationItem>,
+ hovered_id: Option<u64>,
+ badges: HashMap<String, usize>,
+}
+
+impl NotificationQueue {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Allocates an ID and enqueues a notification.
+ /// If `dnd` is active or the app is `muted`, banners are suppressed,
+ /// but the app badge count is still incremented (unless muted).
+ #[allow(clippy::too_many_arguments)]
+ pub fn push(
+ &mut self,
+ app_id: String,
+ app_name: String,
+ title: String,
+ body: String,
+ icon_path: Option<String>,
+ target_hwnd: Option<isize>,
+ duration_ms: u64,
+ dnd: bool,
+ muted: bool,
+ ) -> Option<u64> {
+ if muted {
+ return None;
+ }
+
+ // Increment dock badge count for the source app
+ *self.badges.entry(app_id.clone()).or_insert(0) += 1;
+
+ if dnd {
+ return None;
+ }
+
+ self.next_id = self.next_id.wrapping_add(1);
+ let id = self.next_id;
+ let item = NotificationItem::new(
+ id,
+ app_id,
+ app_name,
+ title,
+ body,
+ icon_path,
+ target_hwnd,
+ duration_ms,
+ );
+ self.items.push(item);
+ Some(id)
+ }
+
+ /// Advances timers for active notifications and returns IDs of expired ones.
+ pub fn tick(&mut self, delta_ms: u64) -> Vec<u64> {
+ let mut expired = Vec::new();
+ for item in &mut self.items {
+ if !item.paused {
+ item.elapsed_ms = item.elapsed_ms.saturating_add(delta_ms);
+ if item.elapsed_ms >= item.duration_ms {
+ expired.push(item.id);
+ }
+ }
+ }
+ for id in &expired {
+ self.dismiss(*id);
+ }
+ expired
+ }
+
+ /// Pauses timer while cursor is hovered over a banner.
+ pub fn set_hovered(&mut self, id: Option<u64>) {
+ self.hovered_id = id;
+ for item in &mut self.items {
+ item.paused = Some(item.id) == id;
+ }
+ }
+
+ /// Dismisses a notification by ID.
+ pub fn dismiss(&mut self, id: u64) -> Option<NotificationItem> {
+ if let Some(pos) = self.items.iter().position(|it| it.id == id) {
+ let item = self.items.remove(pos);
+ if self.hovered_id == Some(id) {
+ self.hovered_id = None;
+ }
+ Some(item)
+ } else {
+ None
+ }
+ }
+
+ /// Dismisses all notifications originating from a specific app.
+ pub fn dismiss_for_app(&mut self, app_id: &str) -> Vec<NotificationItem> {
+ let mut removed = Vec::new();
+ self.items.retain(|it| {
+ if it.app_id == app_id {
+ removed.push(it.clone());
+ false
+ } else {
+ true
+ }
+ });
+ if self
+ .hovered_id
+ .is_some_and(|h| removed.iter().any(|it| it.id == h))
+ {
+ self.hovered_id = None;
+ }
+ removed
+ }
+
+ /// Clears badge count when an app is focused or dismissed.
+ pub fn clear_badge(&mut self, app_id: &str) {
+ self.badges.remove(app_id);
+ }
+
+ /// Returns the badge count for an app.
+ pub fn badge_count(&self, app_id: &str) -> usize {
+ self.badges.get(app_id).copied().unwrap_or(0)
+ }
+
+ /// Returns all badge counts.
+ pub fn all_badges(&self) -> &HashMap<String, usize> {
+ &self.badges
+ }
+
+ /// Up to `MAX_VISIBLE_BANNERS` currently visible notifications.
+ pub fn visible_items(&self) -> &[NotificationItem] {
+ let count = self.items.len().min(MAX_VISIBLE_BANNERS);
+ &self.items[..count]
+ }
+
+ /// Total number of active queued notifications.
+ pub fn total_count(&self) -> usize {
+ self.items.len()
+ }
+
+ /// Clears all notifications and badges.
+ pub fn clear_all(&mut self) {
+ self.items.clear();
+ self.hovered_id = None;
+ self.badges.clear();
+ }
+}
+
+/// Standard layout parameters for notification cards.
+pub const BANNER_WIDTH: f32 = 340.0;
+pub const BANNER_HEIGHT: f32 = 72.0;
+pub const BANNER_GAP: f32 = 10.0;
+pub const BANNER_MARGIN: f32 = 16.0;
+
+/// Calculates the screen bounds for a visible banner at `index` (0-based, top-to-bottom or bottom-to-top).
+pub fn banner_bounds(index: usize, position: BannerPosition, work_area: Rect, scale: f32) -> Rect {
+ let width = (BANNER_WIDTH * scale).round();
+ let height = (BANNER_HEIGHT * scale).round();
+ let gap = (BANNER_GAP * scale).round();
+ let margin = (BANNER_MARGIN * scale).round();
+
+ let x = work_area.x + work_area.width - width - margin;
+ let y = match position {
+ BannerPosition::TopRight => work_area.y + margin + (index as f32) * (height + gap),
+ BannerPosition::BottomRight => {
+ work_area.y + work_area.height - margin - height - (index as f32) * (height + gap)
+ }
+ };
+
+ Rect {
+ x,
+ y,
+ width,
+ height,
+ }
+}
+
+/// Close button ("✕") hit area on a notification banner (top-right corner of the banner).
+pub fn banner_close_button_bounds(banner_rect: Rect, scale: f32) -> Rect {
+ let size = (20.0 * scale).round().max(20.0);
+ let padding = (8.0 * scale).round();
+ Rect {
+ x: banner_rect.width - size - padding,
+ y: padding,
+ width: size,
+ height: size,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_push_and_expiration() {
+ let mut queue = NotificationQueue::new();
+ let id1 = queue
+ .push(
+ "slack".into(),
+ "Slack".into(),
+ "New message".into(),
+ "Hello!".into(),
+ None,
+ None,
+ 5000,
+ false,
+ false,
+ )
+ .unwrap();
+
+ assert_eq!(queue.visible_items().len(), 1);
+ assert_eq!(queue.badge_count("slack"), 1);
+
+ // Advance 3000ms -> not expired
+ let expired = queue.tick(3000);
+ assert!(expired.is_empty());
+ assert_eq!(queue.visible_items().len(), 1);
+
+ // Advance another 2000ms -> expired
+ let expired = queue.tick(2000);
+ assert_eq!(expired, vec![id1]);
+ assert_eq!(queue.visible_items().len(), 0);
+ // Badge stays until focused/cleared
+ assert_eq!(queue.badge_count("slack"), 1);
+ }
+
+ #[test]
+ fn test_hover_pauses_timer() {
+ let mut queue = NotificationQueue::new();
+ let id = queue
+ .push(
+ "teams".into(),
+ "Teams".into(),
+ "Meeting".into(),
+ "Starting now".into(),
+ None,
+ None,
+ 5000,
+ false,
+ false,
+ )
+ .unwrap();
+
+ // Hover pauses
+ queue.set_hovered(Some(id));
+ let expired = queue.tick(6000);
+ assert!(expired.is_empty());
+ assert_eq!(queue.visible_items().len(), 1);
+
+ // Hover end resumes
+ queue.set_hovered(None);
+ let expired = queue.tick(5000);
+ assert_eq!(expired, vec![id]);
+ assert_eq!(queue.visible_items().len(), 0);
+ }
+
+ #[test]
+ fn test_dnd_and_mute() {
+ let mut queue = NotificationQueue::new();
+
+ // Muted app: completely ignored, no badge, no banner
+ let id_muted = queue.push(
+ "noisy".into(),
+ "Noisy".into(),
+ "Spam".into(),
+ "Buy now".into(),
+ None,
+ None,
+ 5000,
+ false,
+ true,
+ );
+ assert!(id_muted.is_none());
+ assert_eq!(queue.badge_count("noisy"), 0);
+
+ // DND mode: banner suppressed, badge still increments
+ let id_dnd = queue.push(
+ "mail".into(),
+ "Mail".into(),
+ "Urgent".into(),
+ "Invoice".into(),
+ None,
+ None,
+ 5000,
+ true, // dnd
+ false,
+ );
+ assert!(id_dnd.is_none());
+ assert_eq!(queue.badge_count("mail"), 1);
+ assert_eq!(queue.visible_items().len(), 0);
+ }
+
+ #[test]
+ fn test_banner_bounds_layout() {
+ let work_area = Rect {
+ x: 0.0,
+ y: 32.0, // under menu bar
+ width: 1920.0,
+ height: 1048.0,
+ };
+
+ // Top right
+ let b0 = banner_bounds(0, BannerPosition::TopRight, work_area, 1.0);
+ let b1 = banner_bounds(1, BannerPosition::TopRight, work_area, 1.0);
+ assert_eq!(b0.x, 1920.0 - BANNER_WIDTH - BANNER_MARGIN);
+ assert_eq!(b0.y, 32.0 + BANNER_MARGIN);
+ assert_eq!(b1.y, b0.y + BANNER_HEIGHT + BANNER_GAP);
+
+ // Bottom right
+ let br0 = banner_bounds(0, BannerPosition::BottomRight, work_area, 1.0);
+ let br1 = banner_bounds(1, BannerPosition::BottomRight, work_area, 1.0);
+ assert_eq!(br0.x, 1920.0 - BANNER_WIDTH - BANNER_MARGIN);
+ assert_eq!(br0.y, 32.0 + 1048.0 - BANNER_MARGIN - BANNER_HEIGHT);
+ assert_eq!(br1.y, br0.y - BANNER_HEIGHT - BANNER_GAP);
+ }
+}
diff --git a/crates/muelle-shell/Cargo.toml b/crates/muelle-shell/Cargo.toml
index 0f255bc..e6a7eec 100644
--- a/crates/muelle-shell/Cargo.toml
+++ b/crates/muelle-shell/Cargo.toml
@@ -25,6 +25,7 @@ windows = { workspace = true, features = [
"Win32_Storage_Packaging_Appx",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
+ "Win32_System_DataExchange",
"Win32_System_Power",
"Win32_System_ProcessStatus",
"Win32_System_Registry",
diff --git a/crates/muelle-shell/src/dock_link.rs b/crates/muelle-shell/src/dock_link.rs
index 0ec64a4..d3d8daf 100644
--- a/crates/muelle-shell/src/dock_link.rs
+++ b/crates/muelle-shell/src/dock_link.rs
@@ -3,7 +3,11 @@
use windows::{
Win32::{
Foundation::{LPARAM, WPARAM},
- UI::WindowsAndMessaging::{FindWindowW, PostMessageW, RegisterWindowMessageW},
+ System::DataExchange::COPYDATASTRUCT,
+ UI::WindowsAndMessaging::{
+ FindWindowW, PostMessageW, RegisterWindowMessageW, SMTO_ABORTIFHUNG,
+ SendMessageTimeoutW, WM_COPYDATA,
+ },
},
core::{PCWSTR, w},
};
@@ -11,6 +15,51 @@ use windows::{
pub const DOCK_WINDOW_CLASS: PCWSTR = w!("MuelleWindow");
/// Name of the registered window message meaning "the configuration file changed".
pub const CONFIG_CHANGED: PCWSTR = w!("Muelle.ConfigChanged");
+/// Tag for notification payloads sent via WM_COPYDATA.
+pub const NOTIFY_DATA_TAG: usize = 0x4D55_4E46; // "MUNF"
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct NotificationPayload {
+ pub app_id: String,
+ pub app_name: String,
+ pub title: String,
+ pub body: String,
+ pub icon_path: Option<String>,
+ pub duration_secs: u32,
+}
+
+impl NotificationPayload {
+ pub fn encode(&self) -> String {
+ format!(
+ "{}\t{}\t{}\t{}\t{}\t{}",
+ self.app_id.replace('\t', " "),
+ self.app_name.replace('\t', " "),
+ self.title.replace('\t', " "),
+ self.body.replace('\t', " "),
+ self.icon_path.as_deref().unwrap_or("").replace('\t', " "),
+ self.duration_secs
+ )
+ }
+
+ pub fn decode(s: &str) -> Option<Self> {
+ let parts: Vec<&str> = s.split('\t').collect();
+ if parts.len() < 6 {
+ return None;
+ }
+ Some(Self {
+ app_id: parts[0].to_string(),
+ app_name: parts[1].to_string(),
+ title: parts[2].to_string(),
+ body: parts[3].to_string(),
+ icon_path: if parts[4].is_empty() {
+ None
+ } else {
+ Some(parts[4].to_string())
+ },
+ duration_secs: parts[5].parse().unwrap_or(5),
+ })
+ }
+}
/// `true` if a dock is running in this session.
#[must_use]
@@ -30,3 +79,35 @@ pub fn notify_config_changed() {
}
}
}
+
+/// Sends a notification payload to the running dock process via WM_COPYDATA.
+/// Returns `true` if delivered successfully.
+pub fn post_notification(payload: &NotificationPayload) -> bool {
+ let raw = payload.encode();
+ let bytes = raw.as_bytes();
+
+ unsafe {
+ let dock = match FindWindowW(DOCK_WINDOW_CLASS, None) {
+ Ok(hwnd) => hwnd,
+ Err(_) => return false,
+ };
+
+ let cds = COPYDATASTRUCT {
+ dwData: NOTIFY_DATA_TAG,
+ cbData: bytes.len() as u32,
+ lpData: bytes.as_ptr() as *mut _,
+ };
+
+ let mut result = 0;
+ let ok = SendMessageTimeoutW(
+ dock,
+ WM_COPYDATA,
+ WPARAM(0),
+ LPARAM(&cds as *const _ as isize),
+ SMTO_ABORTIFHUNG,
+ 2000,
+ Some(&mut result),
+ );
+ ok.0 != 0
+ }
+}