Skip to content

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

feat(dock): add optional macOS-style menu bar

CristianOlivera1e00d6919599e
diff --git a/Cargo.lock b/Cargo.lock
index 455e8c6..5524d93 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1846,6 +1846,7 @@ dependencies = [
"windows",
"windows-core",
"windows-numerics",
+ "winresource",
]
[[package]]
@@ -4328,6 +4329,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "winresource"
+version = "0.1.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
+dependencies = [
+ "toml 1.2.1+spec-1.1.0",
+ "version_check",
+]
+
[[package]]
name = "wit-bindgen"
version = "0.57.1"
diff --git a/apps/dock/Cargo.toml b/apps/dock/Cargo.toml
index 1a15f9e..fbf797b 100644
--- a/apps/dock/Cargo.toml
+++ b/apps/dock/Cargo.toml
@@ -7,6 +7,9 @@ license.workspace = true
[lints]
workspace = true
+[build-dependencies]
+winresource = "0.1"
+
[dependencies]
anyhow.workspace = true
muelle-config.workspace = true
@@ -40,6 +43,7 @@ windows = { workspace = true, features = [
"Win32_System_WinRT",
"Win32_System_WinRT_Composition",
"Win32_System_Ole",
+ "Win32_System_SystemInformation",
"Win32_System_SystemServices",
"Win32_UI_Shell",
"Win32_UI_Accessibility",
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index e13e840..8b17c8b 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -31,7 +31,7 @@ use muelle_core::{
spring::Spring,
};
use muelle_shell::{
- appbar::{ABN_FULLSCREENAPP, AppBar},
+ appbar::{ABN_FULLSCREENAPP, AppBar, Edge},
files,
icon_cache::IconCache,
launcher,
@@ -89,6 +89,7 @@ use crate::{
flight::Flight,
gfx::{Gfx, LabelBrush},
menu::{self, MenuItem},
+ menubar::MenuBar,
scene::{Drag, Frame, Scene, SceneInput, SlotContent, Theme},
strings::{self, text},
thumbnails::Thumbnails,
@@ -370,6 +371,9 @@ struct App {
thumbnails: Thumbnails,
/// Minimize animations in progress.
flights: Vec<Flight>,
+ menubar: Option<MenuBar>,
+ /// Display names already looked up, by app id.
+ names: HashMap<String, String>,
/// Windows whose system transitions are turned off (see `calm_windows`).
calmed: Vec<isize>,
/// Windows already minimized when the dock starts get no animation.
@@ -601,6 +605,9 @@ impl App {
/// nothing if the scene inputs are unchanged, since many Windows notifications
/// do not affect the dock.
fn refresh(&mut self) -> Result<()> {
+ if let Some(bar) = &mut self.menubar {
+ bar.refresh(&self.gfx)?;
+ }
let monitor = primary_monitor().context("no se pudo consultar el monitor principal")?;
let key = StageKey {
screen: monitor.screen,
@@ -658,7 +665,7 @@ impl App {
} else {
(dock.height + 2.0 * px(FLOAT_MARGIN)) as i32
};
- appbar.reserve_bottom(screen, strip);
+ appbar.reserve(Edge::Bottom, screen, strip);
}
let (dock_right, dock_bottom) = (dock_x + dock.width, dock_y + dock.height);
let zone = move |left: f32, top: f32, right: f32, bottom: f32| RECT {
@@ -1551,6 +1558,8 @@ impl App {
self.last_frame = Instant::now();
}
self.config = config;
+ self.apply_menu_bar_setting();
+ self.update_menu_bar_app()?;
self.calm_windows();
self.refresh()
}
@@ -1679,13 +1688,56 @@ impl App {
taskbar::take_over();
self.appbar = None;
self.appbar = AppBar::register(self.visual, APPBAR_CALLBACK);
+ // The menu bar's reservation is gone as well: rebuild it.
+ self.menubar = None;
+ self.apply_menu_bar_setting();
self.stage = None;
self.refresh()
}
/// Hides the dock while the foreground window covers the entire screen and
/// shows it again when it no longer does.
+ /// Creates or removes the menu bar to match the settings.
+ fn apply_menu_bar_setting(&mut self) {
+ if !self.config.menu_bar {
+ self.menubar = None;
+ } else if self.menubar.is_none() {
+ self.menubar = MenuBar::create(&self.gfx)
+ .inspect_err(|error| eprintln!("muelle: barra superior: {error:#}"))
+ .ok();
+ if let Some(bar) = &mut self.menubar {
+ bar.set_visible(!self.fullscreen);
+ }
+ }
+ }
+
+ /// Shows the name of the app in front, as the macOS menu bar does.
+ fn update_menu_bar_app(&mut self) -> Result<()> {
+ if self.menubar.is_none() {
+ return Ok(());
+ }
+ let front = tracker::foreground_window();
+ let id = self
+ .windows
+ .iter()
+ .find(|window| window.hwnd == front)
+ .map_or_else(explorer_id, |window| window.app_id.clone());
+ if !self.names.contains_key(&id) {
+ let name = self
+ .icons
+ .get(&id, ICON_SOURCE_SIZE)
+ .map_or_else(|_| display_name(&id), |visual| visual.name);
+ self.names.insert(id.clone(), name);
+ }
+ let name = self.names.get(&id).map_or("", String::as_str);
+ match &mut self.menubar {
+ Some(bar) => bar.set_app_name(&self.gfx, name),
+ None => Ok(()),
+ }
+ }
+
fn update_fullscreen(&mut self) -> Result<()> {
+ self.update_menu_bar_app()?;
let Some(monitor) = primary_monitor() else {
return Ok(());
};
@@ -1694,6 +1746,9 @@ impl App {
return Ok(());
}
self.fullscreen = fullscreen;
+ if let Some(bar) = &mut self.menubar {
+ bar.set_visible(!fullscreen);
+ }
if fullscreen {
self.hovering = false;
self.amount = Spring::at(0.0, HOVER_OMEGA);
@@ -1776,6 +1831,22 @@ fn with_app_value<T: Default>(what: &str, action: impl FnOnce(&mut App) -> Resul
value
}
+pub fn menu_bar_clicked(x: f32) {
+ with_app("barra superior", |app| {
+ if let Some(bar) = &app.menubar {
+ bar.click(x);
+ }
+ Ok(())
+ });
+}
+
+pub fn menu_bar_tick() {
+ with_app("barra superior", |app| match &mut app.menubar {
+ Some(bar) => bar.tick(&app.gfx),
+ None => Ok(()),
+ });
+}
+
pub fn drag_enter(files: Vec<String>, x: i32, _y: i32) -> DROPEFFECT {
with_app_value("arrastre de archivos", |app| app.on_drag_enter(files, x))
}
@@ -2093,6 +2164,8 @@ pub fn run() -> Result<()> {
minimized: Vec::new(),
thumbnails: Thumbnails::new(visual),
flights: Vec::new(),
+ menubar: None,
+ names: HashMap::new(),
calmed: Vec::new(),
started: false,
stage: None,
@@ -2112,6 +2185,7 @@ pub fn run() -> Result<()> {
let _ = SetConsoleCtrlHandler(None, false);
let _ = SetConsoleCtrlHandler(Some(on_console_ctrl), true);
+ app.apply_menu_bar_setting();
app.sync()?;
// `sync` recomposes only when the list changes; run it unconditionally at startup.
if app.stage.is_none() {
diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rs
index ce3d022..5dd133f 100644
--- a/apps/dock/src/gfx.rs
+++ b/apps/dock/src/gfx.rs
@@ -20,8 +20,9 @@ use windows::{
},
D2D1_BITMAP_OPTIONS_NONE, D2D1_BITMAP_PROPERTIES1,
D2D1_BUFFER_PRECISION_8BPC_UNORM, D2D1_COLOR_INTERPOLATION_MODE_PREMULTIPLIED,
- D2D1_COLOR_SPACE_SRGB, D2D1_DRAW_TEXT_OPTIONS_NONE, D2D1_EXTEND_MODE_CLAMP,
- D2D1_INTERPOLATION_MODE, D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC,
+ D2D1_COLOR_SPACE_SRGB, D2D1_DRAW_TEXT_OPTIONS_NONE, D2D1_ELLIPSE,
+ D2D1_EXTEND_MODE_CLAMP, D2D1_INTERPOLATION_MODE,
+ D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC,
D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR, D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES,
D2D1_ROUNDED_RECT, D2D1CreateDevice, ID2D1Device, ID2D1DeviceContext,
},
@@ -32,8 +33,8 @@ use windows::{
},
DirectWrite::{
DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL,
- DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_TEXT_METRICS, DWriteCreateFactory,
- IDWriteFactory,
+ DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_WEIGHT_SEMI_BOLD,
+ DWRITE_TEXT_METRICS, DWriteCreateFactory, IDWriteFactory,
},
Dxgi::{Common::DXGI_FORMAT_B8G8R8A8_UNORM, IDXGIDevice},
},
@@ -368,6 +369,178 @@ impl Gfx {
Ok(())
})
}
+
+ /// Plain text on a transparent background (menu bar).
+ pub fn text_brush(&self, text: &str, scale: f32, bold: bool, ink: Ink) -> Result<LabelBrush> {
+ let utf16: Vec<u16> = text.encode_utf16().collect();
+ let weight = if bold {
+ DWRITE_FONT_WEIGHT_SEMI_BOLD
+ } else {
+ DWRITE_FONT_WEIGHT_NORMAL
+ };
+ // SAFETY: Strings and structures passed to each call remain alive for its duration.
+ let (layout, metrics) = unsafe {
+ let format = self.dwrite.CreateTextFormat(
+ w!("Segoe UI Variable Text"),
+ None,
+ weight,
+ DWRITE_FONT_STYLE_NORMAL,
+ DWRITE_FONT_STRETCH_NORMAL,
+ 13.0 * scale,
+ w!(""),
+ )?;
+ let layout = self
+ .dwrite
+ .CreateTextLayout(&utf16, &format, 4096.0, 256.0)?;
+ let mut metrics = DWRITE_TEXT_METRICS::default();
+ layout.GetMetrics(&mut metrics)?;
+ (layout, metrics)
+ };
+ let (width, height) = (
+ metrics.width.ceil().max(1.0),
+ metrics.height.ceil().max(1.0),
+ );
+ let brush = self.draw(width as u32, height as u32, |dc| {
+ // SAFETY: The brush and layout live for the drawing call.
+ unsafe {
+ let ink = dc.CreateSolidColorBrush(&ink.color(), None)?;
+ dc.DrawTextLayout(
+ Vector2 { X: 0.0, Y: 0.0 },
+ &layout,
+ &ink,
+ D2D1_DRAW_TEXT_OPTIONS_NONE,
+ );
+ }
+ Ok(())
+ })?;
+ Ok(LabelBrush {
+ brush,
+ width,
+ height,
+ })
+ }
+
+ /// Two switches, one on and one off: the control center glyph.
+ pub fn control_center_brush(&self, scale: f32, ink: Ink) -> Result<LabelBrush> {
+ let (width, height) = ((19.0 * scale).round(), (16.0 * scale).round());
+ let brush = self.draw(width as u32, height as u32, |dc| {
+ let pill_height = height * 0.44;
+ let radius = pill_height / 2.0;
+ let stroke = (1.2 * scale).max(1.0);
+ // SAFETY: The brush lives for the drawing calls.
+ unsafe {
+ let ink = dc.CreateSolidColorBrush(&ink.color(), None)?;
+ for (row, knob_right) in [(0.0, true), (height - pill_height, false)] {
+ let pill = D2D1_ROUNDED_RECT {
+ rect: D2D_RECT_F {
+ left: stroke / 2.0,
+ top: row + stroke / 2.0,
+ right: width - stroke / 2.0,
+ bottom: row + pill_height - stroke / 2.0,
+ },
+ radiusX: radius,
+ radiusY: radius,
+ };
+ dc.DrawRoundedRectangle(&pill, &ink, stroke, None);
+ let center = if knob_right { width - radius } else { radius };
+ dc.FillEllipse(
+ &D2D1_ELLIPSE {
+ point: Vector2 {
+ X: center,
+ Y: row + radius,
+ },
+ radiusX: radius - stroke * 0.3,
+ radiusY: radius - stroke * 0.3,
+ },
+ &ink,
+ );
+ }
+ }
+ Ok(())
+ })?;
+ Ok(LabelBrush {
+ brush,
+ width,
+ height,
+ })
+ }
+
+ /// Battery outline filled to `percent`, green while charging.
+ pub fn battery_brush(
+ &self,
+ percent: u8,
+ charging: bool,
+ scale: f32,
+ ink: Ink,
+ ) -> Result<LabelBrush> {
+ let (width, height) = ((26.0 * scale).round(), (12.0 * scale).round());
+ let brush = self.draw(width as u32, height as u32, |dc| {
+ let stroke = (1.0 * scale).max(1.0);
+ let cap = 2.0 * scale;
+ let body_right = width - cap - stroke;
+ let level = if charging {
+ rgb(0.20, 0.78, 0.35, 1.0)
+ } else if percent <= 20 {
+ rgb(1.0, 0.27, 0.23, 1.0)
+ } else {
+ ink.color()
+ };
+ // SAFETY: The brushes live for the drawing calls.
+ unsafe {
+ let outline = dc.CreateSolidColorBrush(&ink.faded(), None)?;
+ let fill = dc.CreateSolidColorBrush(&level, None)?;
+ dc.DrawRoundedRectangle(
+ &D2D1_ROUNDED_RECT {
+ rect: D2D_RECT_F {
+ left: stroke / 2.0,
+ top: stroke / 2.0,
+ right: body_right,
+ bottom: height - stroke / 2.0,
+ },
+ radiusX: 3.0 * scale,
+ radiusY: 3.0 * scale,
+ },
+ &outline,
+ stroke,
+ None,
+ );
+ dc.FillRoundedRectangle(
+ &D2D1_ROUNDED_RECT {
+ rect: D2D_RECT_F {
+ left: body_right + stroke,
+ top: height * 0.32,
+ right: width,
+ bottom: height * 0.68,
+ },
+ radiusX: scale,
+ radiusY: scale,
+ },
+ &outline,
+ );
+ let inset = stroke * 2.0;
+ let room = body_right - 2.0 * inset;
+ dc.FillRoundedRectangle(
+ &D2D1_ROUNDED_RECT {
+ rect: D2D_RECT_F {
+ left: inset,
+ top: inset,
+ right: inset + room * f32::from(percent.min(100)) / 100.0,
+ bottom: height - inset,
+ },
+ radiusX: 1.5 * scale,
+ radiusY: 1.5 * scale,
+ },
+ &fill,
+ );
+ }
+ Ok(())
+ })?;
+ Ok(LabelBrush {
+ brush,
+ width,
+ height,
+ })
+ }
}
fn draw_image(
@@ -412,3 +585,28 @@ fn draw_image(
const fn rgb(r: f32, g: f32, b: f32, a: f32) -> D2D1_COLOR_F {
D2D1_COLOR_F { r, g, b, a }
}
+
+/// Foreground color of menu bar content, by theme.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum Ink {
+ /// Dark content for a light bar.
+ Dark,
+ /// Light content for a dark bar.
+ Light,
+}
+
+impl Ink {
+ fn color(self) -> D2D1_COLOR_F {
+ match self {
+ Self::Dark => rgb(0.0, 0.0, 0.0, 0.86),
+ Self::Light => rgb(1.0, 1.0, 1.0, 0.94),
+ }
+ }
+
+ fn faded(self) -> D2D1_COLOR_F {
+ match self {
+ Self::Dark => rgb(0.0, 0.0, 0.0, 0.5),
+ Self::Light => rgb(1.0, 1.0, 1.0, 0.55),
+ }
+ }
+}
diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rs
index 2d1fa06..741b663 100644
--- a/apps/dock/src/main.rs
+++ b/apps/dock/src/main.rs
@@ -15,6 +15,7 @@ mod flight;
mod gfx;
mod guard;
mod menu;
+mod menubar;
mod scene;
mod strings;
mod thumbnails;
diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rs
new file mode 100644
index 0000000..800f220
--- /dev/null
+++ b/apps/dock/src/menubar.rs
@@ -0,0 +1,369 @@
+//! Minimal macOS-style menu bar across the top of the screen.
+//!
+//! Hiding the Windows taskbar also hides its clock and status area; this bar
+//! brings them back: the name of the app in front, the battery, a control
+//! center button (opens the Windows quick settings: network, volume,
+//! brightness) and the date and time (opens the notification center).
+//!
+//! Cost while idle: one timer that fires once a minute, on the minute, to
+//! redraw the clock. Everything else is event-driven.
+
+use anyhow::Result;
+use muelle_shell::{
+ appbar::{AppBar, Edge},
+ launcher,
+ system::{self, Battery, Monitor},
+};
+use windows::{
+ UI::{
+ Color,
+ Composition::{Desktop::DesktopWindowTarget, SpriteVisual},
+ },
+ Win32::{
+ Foundation::{HWND, LPARAM, LRESULT, RECT, SYSTEMTIME, WPARAM},
+ Graphics::Dwm::{DWMWA_USE_HOSTBACKDROPBRUSH, DwmSetWindowAttribute},
+ System::{
+ LibraryLoader::GetModuleHandleW, SystemInformation::GetLocalTime,
+ WinRT::Composition::ICompositorDesktopInterop,
+ },
+ UI::WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, DestroyWindow, HWND_TOPMOST, IDC_ARROW, LoadCursorW,
+ RegisterClassW, SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW, SetTimer, SetWindowPos,
+ WM_APP, WM_LBUTTONUP, WM_TIMER, WNDCLASSW, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP,
+ WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
+ },
+ },
+ core::{BOOL, Interface, w},
+};
+use windows_numerics::{Vector2, Vector3};
+
+use crate::{
+ app,
+ gfx::{Gfx, Ink, LabelBrush},
+};
+
+// Logical pixels.
+const HEIGHT: f32 = 28.0;
+const SIDE_MARGIN: f32 = 14.0;
+const ITEM_GAP: f32 = 16.0;
+/// Extra clickable room around an item.
+const HIT_SLOP: f32 = 7.0;
+
+const CLOCK_TIMER: usize = 1;
+const WM_POWERBROADCAST: u32 = 0x0218;
+/// AppBar notifications need a message id; the bar ignores them.
+const APPBAR_CALLBACK: u32 = WM_APP + 20;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Action {
+ QuickSettings,
+ Notifications,
+}
+
+/// What the bar was last drawn for.
+#[derive(Clone, PartialEq)]
+struct Look {
+ screen: RECT,
+ scale: f32,
+ light: bool,
+ app_name: String,
+ clock: String,
+ battery: Option<Battery>,
+}
+
+pub struct MenuBar {
+ hwnd: HWND,
+ target: DesktopWindowTarget,
+ appbar: Option<AppBar>,
+ app_name: String,
+ look: Option<Look>,
+ /// Clickable spans, in window pixels.
+ zones: Vec<(f32, f32, Action)>,
+ visible: bool,
+}
+
+unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {
+ match msg {
+ WM_LBUTTONUP => {
+ let x = (l.0 & 0xFFFF) as i16;
+ app::menu_bar_clicked(f32::from(x));
+ }
+ // The minute changed, or the charger was plugged or unplugged.
+ WM_TIMER | WM_POWERBROADCAST => app::menu_bar_tick(),
+ // SAFETY: Standard forwarding of unhandled messages.
+ _ => return unsafe { DefWindowProcW(hwnd, msg, w, l) },
+ }
+ LRESULT(0)
+}
+
+fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
+ Color {
+ A: a,
+ R: r,
+ G: g,
+ B: b,
+ }
+}
+
+impl MenuBar {
+ pub fn create(gfx: &Gfx) -> Result<Self> {
+ let class = w!("MuelleMenuBar");
+ // SAFETY: Standard class registration and window creation on the UI
+ // thread; the window is destroyed in `Drop`.
+ let hwnd = unsafe {
+ let instance = GetModuleHandleW(None)?;
+ // Registering an existing class fails harmlessly.
+ RegisterClassW(&WNDCLASSW {
+ lpfnWndProc: Some(bar_proc),
+ hInstance: instance.into(),
+ hCursor: LoadCursorW(None, IDC_ARROW)?,
+ lpszClassName: class,
+ ..Default::default()
+ });
+ let hwnd = CreateWindowExW(
+ WS_EX_NOREDIRECTIONBITMAP | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,
+ class,
+ w!("Muelle"),
+ WS_POPUP,
+ 0,
+ 0,
+ 0,
+ 0,
+ None,
+ None,
+ Some(instance.into()),
+ None,
+ )?;
+ // Without this, the system backdrop brush appears black.
+ let enable = BOOL::from(true);
+ let _ = DwmSetWindowAttribute(
+ hwnd,
+ DWMWA_USE_HOSTBACKDROPBRUSH,
+ (&raw const enable).cast(),
+ size_of::<BOOL>() as u32,
+ );
+ hwnd
+ };
+ let target = unsafe {
+ // SAFETY: `hwnd` is the live window created above.
+ gfx.compositor
+ .cast::<ICompositorDesktopInterop>()?
+ .CreateDesktopWindowTarget(hwnd, true)?
+ };
+ let mut bar = Self {
+ hwnd,
+ target,
+ appbar: AppBar::register(hwnd, APPBAR_CALLBACK),
+ app_name: String::new(),
+ look: None,
+ zones: Vec::new(),
+ visible: true,
+ };
+ bar.refresh(gfx)?;
+ bar.schedule_next_minute();
+ Ok(bar)
+ }
+
+ pub fn set_app_name(&mut self, gfx: &Gfx, name: &str) -> Result<()> {
+ if self.app_name == name {
+ return Ok(());
+ }
+ name.clone_into(&mut self.app_name);
+ self.refresh(gfx)
+ }
+
+ /// Hidden while an app is full screen.
+ pub fn set_visible(&mut self, visible: bool) {
+ if self.visible == visible {
+ return;
+ }
+ self.visible = visible;
+ let show = if visible {
+ SWP_SHOWWINDOW
+ } else {
+ SWP_HIDEWINDOW
+ };
+ // SAFETY: Our own live window; only its visibility changes.
+ unsafe {
+ let _ = SetWindowPos(
+ self.hwnd,
+ Some(HWND_TOPMOST),
+ 0,
+ 0,
+ 0,
+ 0,
+ SWP_NOACTIVATE
+ | show
+ | windows::Win32::UI::WindowsAndMessaging::SWP_NOMOVE
+ | windows::Win32::UI::WindowsAndMessaging::SWP_NOSIZE,
+ );
+ }
+ }
+
+ /// The minute changed or the power state did: redraw what differs.
+ pub fn tick(&mut self, gfx: &Gfx) -> Result<()> {
+ self.schedule_next_minute();
+ self.refresh(gfx)
+ }
+
+ /// One wake-up per minute, aligned to the minute, instead of polling.
+ fn schedule_next_minute(&self) {
+ // SAFETY: Read-only query, then a timer on our own window (setting an
+ // existing timer id replaces it).
+ unsafe {
+ let now: SYSTEMTIME = GetLocalTime();
+ let elapsed = u32::from(now.wSecond) * 1000 + u32::from(now.wMilliseconds);
+ SetTimer(
+ Some(self.hwnd),
+ CLOCK_TIMER,
+ 60_000 - elapsed.min(59_900) + 50,
+ None,
+ );
+ }
+ }
+
+ pub fn click(&self, x: f32) {
+ let hit = self
+ .zones
+ .iter()
+ .find(|(left, right, _)| x >= *left && x < *right);
+ match hit.map(|(_, _, action)| *action) {
+ Some(Action::QuickSettings) => launcher::open_quick_settings(),
+ Some(Action::Notifications) => launcher::open_notifications(),
+ None => {}
+ }
+ }
+
+ /// Redraws the bar if anything it shows has changed.
+ pub fn refresh(&mut self, gfx: &Gfx) -> Result<()> {
+ let Some(monitor) = system::primary_monitor() else {
+ return Ok(());
+ };
+ let look = Look {
+ screen: monitor.screen,
+ scale: monitor.scale,
+ light: system::uses_light_theme(),
+ app_name: self.app_name.clone(),
+ clock: system::clock_text(),
+ battery: system::battery(),
+ };
+ if self.look.as_ref() == Some(&look) {
+ return Ok(());
+ }
+ self.build(gfx, &monitor, &look)?;
+ self.look = Some(look);
+ Ok(())
+ }
+
+ fn build(&mut self, gfx: &Gfx, monitor: &Monitor, look: &Look) -> Result<()> {
+ let c = &gfx.compositor;
+ let scale = look.scale;
+ let px = |logical: f32| (logical * scale).round();
+ let screen = monitor.screen;
+ let (width, height) = ((screen.right - screen.left) as f32, px(HEIGHT));
+ let ink = if look.light { Ink::Dark } else { Ink::Light };
+
+ let root = c.CreateContainerVisual()?;
+ root.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;
+ let layers = root.Children()?;
+ let tint = if look.light {
+ rgba(255, 255, 255, 110)
+ } else {
+ rgba(24, 24, 26, 120)
+ };
+ let fills = [
+ c.CreateHostBackdropBrush()?
+ .cast::<windows::UI::Composition::CompositionBrush>()?,
+ c.CreateColorBrushWithColor(tint)?.cast()?,
+ ];
+ for brush in &fills {
+ let fill = c.CreateSpriteVisual()?;
+ fill.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;
+ fill.SetBrush(brush)?;
+ layers.InsertAtTop(&fill)?;
+ }
+
+ let place = |layers: &windows::UI::Composition::VisualCollection,
+ item: &LabelBrush,
+ left: f32|
+ -> Result<SpriteVisual> {
+ let visual = c.CreateSpriteVisual()?;
+ visual.SetSize(Vector2 {
+ X: item.width,
+ Y: item.height,
+ })?;
+ visual.SetOffset(Vector3 {
+ X: left.round(),
+ Y: ((height - item.height) / 2.0).round(),
+ Z: 0.0,
+ })?;
+ visual.SetBrush(&item.brush)?;
+ layers.InsertAtTop(&visual)?;
+ Ok(visual)
+ };
+
+ self.zones.clear();
+ if !look.app_name.is_empty() {
+ let name = gfx.text_brush(&look.app_name, scale, true, ink)?;
+ place(&layers, &name, px(SIDE_MARGIN))?;
+ }
+
+ // Right side, from the edge inward: clock, control center, battery.
+ let slop = px(HIT_SLOP);
+ let mut right = width - px(SIDE_MARGIN);
+ let mut items: Vec<(LabelBrush, Action)> = vec![
+ (
+ gfx.text_brush(&look.clock, scale, false, ink)?,
+ Action::Notifications,
+ ),
+ (gfx.control_center_brush(scale, ink)?, Action::QuickSettings),
+ ];
+ if let Some(battery) = look.battery {
+ items.push((
+ gfx.battery_brush(battery.percent, battery.charging, scale, ink)?,
+ Action::QuickSettings,
+ ));
+ }
+ for (item, action) in &items {
+ let left = right - item.width;
+ place(&layers, item, left)?;
+ self.zones.push((left - slop, right + slop, *action));
+ right = left - px(ITEM_GAP);
+ }
+
+ self.target.SetRoot(&root)?;
+
+ if let Some(appbar) = &mut self.appbar {
+ appbar.reserve(Edge::Top, screen, height as i32);
+ }
+ let show = if self.visible {
+ SWP_SHOWWINDOW
+ } else {
+ SWP_HIDEWINDOW
+ };
+ // SAFETY: Our own live window.
+ unsafe {
+ SetWindowPos(
+ self.hwnd,
+ Some(HWND_TOPMOST),
+ screen.left,
+ screen.top,
+ width as i32,
+ height as i32,
+ SWP_NOACTIVATE | show,
+ )?;
+ }
+ Ok(())
+ }
+}
+
+impl Drop for MenuBar {
+ fn drop(&mut self) {
+ // Give the reserved strip back before the window goes away.
+ self.appbar = None;
+ // SAFETY: Our own window, destroyed once.
+ unsafe {
+ let _ = DestroyWindow(self.hwnd);
+ }
+ }
+}
diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsx
index d7ce9eb..04a4292 100644
--- a/apps/settings/src/App.tsx
+++ b/apps/settings/src/App.tsx
@@ -159,6 +159,13 @@ export function App() {
onChange={(autoHide) => update({ autoHide })}
/>
</Row>
+ <Row label={t.menuBar} hint={t.menuBarHint}>
+ <Toggle
+ label={t.menuBar}
+ checked={config.menuBar}
+ onChange={(menuBar) => update({ menuBar })}
+ />
+ </Row>
<Row label={t.genie} hint={t.genieHint}>
<Toggle
label={t.genie}
diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.ts
index 897435b..17c738e 100644
--- a/apps/settings/src/config.ts
+++ b/apps/settings/src/config.ts
@@ -12,6 +12,7 @@ export interface Config {
magnification: boolean;
magnifiedSize: number;
genie: boolean;
+ menuBar: boolean;
language: Language;
}
diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.json
index 04e2c61..e0b7a14 100644
--- a/apps/settings/src/i18n/en.json
+++ b/apps/settings/src/i18n/en.json
@@ -11,6 +11,8 @@
"autoHideHint": "It reappears when you touch the bottom edge of the screen.",
"genie": "Genie effect when minimizing",
"genieHint": "While it is on, windows do not use the Windows animations for maximizing or closing.",
+ "menuBar": "Menu bar",
+ "menuBarHint": "Time, battery, and access to the Windows quick settings and notifications.",
"autostart": "Open Muelle at login",
"language": "Language",
"languageAuto": "Automatic",
diff --git a/apps/settings/src/i18n/es.json b/apps/settings/src/i18n/es.json
index 4d58e94..64652da 100644
--- a/apps/settings/src/i18n/es.json
+++ b/apps/settings/src/i18n/es.json
@@ -11,6 +11,8 @@
"autoHideHint": "Reaparece al tocar el borde inferior de la pantalla.",
"genie": "Efecto genio al minimizar",
"genieHint": "Mientras está activo, las ventanas no usan las animaciones de Windows al maximizar ni al cerrar.",
+ "menuBar": "Barra superior",
+ "menuBarHint": "Hora, batería y acceso a los ajustes rápidos y las notificaciones de Windows.",
"autostart": "Abrir Muelle al iniciar sesión",
"language": "Idioma",
"languageAuto": "Automático",
diff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rs
index 451ad80..1468da8 100644
--- a/crates/muelle-config/src/lib.rs
+++ b/crates/muelle-config/src/lib.rs
@@ -48,6 +48,8 @@ pub struct Config {
/// Genie effect when minimizing. Off by default: while it is on, the dock
/// turns off the system's own window transitions (see plan, "Efecto genio").
pub genie: bool,
+ /// macOS-style bar across the top with the clock and status items.
+ pub menu_bar: bool,
pub language: Language,
}
@@ -97,6 +99,7 @@ impl Default for Config {
magnification: true,
magnified_size: 77,
genie: false,
+ menu_bar: true,
language: Language::Auto,
}
}
diff --git a/crates/muelle-shell/Cargo.toml b/crates/muelle-shell/Cargo.toml
index b2d786b..31a50ec 100644
--- a/crates/muelle-shell/Cargo.toml
+++ b/crates/muelle-shell/Cargo.toml
@@ -19,6 +19,7 @@ windows = { workspace = true, features = [
"Win32_Storage_Packaging_Appx",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
+ "Win32_System_Power",
"Win32_System_ProcessStatus",
"Win32_System_Registry",
"Win32_System_Threading",
diff --git a/crates/muelle-shell/src/appbar.rs b/crates/muelle-shell/src/appbar.rs
index f42c11b..193e1ad 100644
--- a/crates/muelle-shell/src/appbar.rs
+++ b/crates/muelle-shell/src/appbar.rs
@@ -7,12 +7,19 @@ use std::mem::size_of;
use windows::Win32::{
Foundation::{HWND, RECT},
UI::Shell::{
- ABE_BOTTOM, ABM_NEW, ABM_QUERYPOS, ABM_REMOVE, ABM_SETPOS, APPBARDATA, SHAppBarMessage,
+ ABE_BOTTOM, ABE_TOP, ABM_NEW, ABM_QUERYPOS, ABM_REMOVE, ABM_SETPOS, APPBARDATA,
+ SHAppBarMessage,
},
};
pub const ABN_FULLSCREENAPP: usize = 2;
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Edge {
+ Top,
+ Bottom,
+}
+
pub struct AppBar {
hwnd: HWND,
reserved: Option<RECT>,
@@ -37,13 +44,20 @@ impl AppBar {
})
}
- /// Reserves a `height`-pixel strip at the bottom of monitor `screen`.
- /// Calls the system only when the strip changes because each reservation
- /// triggers a settings-change notification; repeating it would create a loop.
- pub fn reserve_bottom(&mut self, screen: RECT, height: i32) {
- let wanted = RECT {
- top: screen.bottom - height,
- ..screen
+ /// Reserves a strip `thickness` pixels deep along `edge` of monitor
+ /// `screen`. Calls the system only when the strip changes because each
+ /// reservation triggers a settings-change notification; repeating it would
+ /// create a loop.
+ pub fn reserve(&mut self, edge: Edge, screen: RECT, thickness: i32) {
+ let wanted = match edge {
+ Edge::Top => RECT {
+ bottom: screen.top + thickness,
+ ..screen
+ },
+ Edge::Bottom => RECT {
+ top: screen.bottom - thickness,
+ ..screen
+ },
};
if self.reserved == Some(wanted) {
return;
@@ -52,7 +66,10 @@ impl AppBar {
let mut data = APPBARDATA {
cbSize: size_of::<APPBARDATA>() as u32,
hWnd: self.hwnd,
- uEdge: ABE_BOTTOM,
+ uEdge: match edge {
+ Edge::Top => ABE_TOP,
+ Edge::Bottom => ABE_BOTTOM,
+ },
rc: wanted,
..Default::default()
};
@@ -60,8 +77,11 @@ impl AppBar {
unsafe {
SHAppBarMessage(ABM_QUERYPOS, &mut data);
// Another bar on the same edge (the Windows taskbar, before it is
- // hidden) shifts the strip upward, so preserve its height.
- data.rc.top = data.rc.bottom - height;
+ // hidden) pushes the strip inward, so preserve its thickness.
+ match edge {
+ Edge::Top => data.rc.bottom = data.rc.top + thickness,
+ Edge::Bottom => data.rc.top = data.rc.bottom - thickness,
+ }
SHAppBarMessage(ABM_SETPOS, &mut data);
}
// Treat the reservation as complete only if the system granted the
diff --git a/crates/muelle-shell/src/launcher.rs b/crates/muelle-shell/src/launcher.rs
index 35ab465..2643cf9 100644
--- a/crates/muelle-shell/src/launcher.rs
+++ b/crates/muelle-shell/src/launcher.rs
@@ -5,7 +5,7 @@ use windows::{
UI::{
Input::KeyboardAndMouse::{
INPUT, INPUT_0, INPUT_KEYBOARD, KEYBD_EVENT_FLAGS, KEYBDINPUT, KEYEVENTF_KEYUP,
- SendInput, VK_LWIN,
+ SendInput, VIRTUAL_KEY, VK_A, VK_LWIN, VK_N,
},
Shell::ShellExecuteW,
WindowsAndMessaging::{
@@ -73,25 +73,44 @@ pub fn open_with(app: &str, files: &[String]) -> Result<(), LaunchError> {
}
}
-/// Opens the Windows Start menu, exactly as the Windows key does.
-pub fn open_start_menu() {
- let key = |flags: KEYBD_EVENT_FLAGS| INPUT {
+/// Presses the given keys together and releases them.
+fn tap(keys: &[VIRTUAL_KEY]) {
+ let key = |vk: VIRTUAL_KEY, flags: KEYBD_EVENT_FLAGS| INPUT {
r#type: INPUT_KEYBOARD,
Anonymous: INPUT_0 {
ki: KEYBDINPUT {
- wVk: VK_LWIN,
+ wVk: vk,
dwFlags: flags,
..Default::default()
},
},
};
- let inputs = [key(KEYBD_EVENT_FLAGS(0)), key(KEYEVENTF_KEYUP)];
+ let inputs: Vec<INPUT> = keys
+ .iter()
+ .map(|&vk| key(vk, KEYBD_EVENT_FLAGS(0)))
+ .chain(keys.iter().rev().map(|&vk| key(vk, KEYEVENTF_KEYUP)))
+ .collect();
// SAFETY: The array lives for the duration of the call.
unsafe {
SendInput(&inputs, size_of::<INPUT>() as i32);
}
}
+/// Opens the Windows Start menu, exactly as the Windows key does.
+pub fn open_start_menu() {
+ tap(&[VK_LWIN]);
+}
+
+/// Opens the Windows 11 quick settings panel (network, volume, battery): Win+A.
+pub fn open_quick_settings() {
+ tap(&[VK_LWIN, VK_A]);
+}
+
+/// Opens the Windows 11 notification center and calendar: Win+N.
+pub fn open_notifications() {
+ tap(&[VK_LWIN, VK_N]);
+}
+
pub fn reveal(path: &str) -> Result<(), LaunchError> {
let arguments = HSTRING::from(format!("/select,\"{path}\""));
// SAFETY: The strings live for the duration of the call.
diff --git a/crates/muelle-shell/src/system.rs b/crates/muelle-shell/src/system.rs
index 51a9f3e..a02591c 100644
--- a/crates/muelle-shell/src/system.rs
+++ b/crates/muelle-shell/src/system.rs
@@ -127,3 +127,54 @@ pub fn set_window_transitions(hwnd: isize, enabled: bool) {
);
}
}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Battery {
+ /// 0..=100.
+ pub percent: u8,
+ pub charging: bool,
+}
+
+/// Battery state, or `None` on a computer without a battery.
+#[must_use]
+pub fn battery() -> Option<Battery> {
+ use windows::Win32::System::Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS};
+ const NO_BATTERY: u8 = 128;
+ const UNKNOWN: u8 = 255;
+ let mut status = SYSTEM_POWER_STATUS::default();
+ // SAFETY: `status` is a valid structure the call fills in.
+ unsafe { GetSystemPowerStatus(&mut status) }.ok()?;
+ (status.BatteryFlag & NO_BATTERY == 0
+ && status.BatteryFlag != UNKNOWN
+ && status.BatteryLifePercent <= 100)
+ .then_some(Battery {
+ percent: status.BatteryLifePercent,
+ charging: status.ACLineStatus == 1,
+ })
+}
+
+/// Current date and time in the regional format of the user, e.g. "vie 13 nov 19:42".
+#[must_use]
+pub fn clock_text() -> String {
+ use windows::Win32::Globalization::{GetDateFormatEx, GetTimeFormatEx, TIME_NOSECONDS};
+ let mut date = [0u16; 64];
+ let mut time = [0u16; 32];
+ // SAFETY: The buffers live for the calls, which return the length written
+ // including the terminator (0 on failure).
+ let (date_len, time_len) = unsafe {
+ (
+ GetDateFormatEx(
+ None,
+ Default::default(),
+ None,
+ w!("ddd d MMM"),
+ Some(&mut date),
+ None,
+ ),
+ GetTimeFormatEx(None, TIME_NOSECONDS, None, None, Some(&mut time)),
+ )
+ };
+ let text =
+ |buffer: &[u16], len: i32| String::from_utf16_lossy(&buffer[..(len - 1).max(0) as usize]);
+ format!("{} {}", text(&date, date_len), text(&time, time_len))
+}
diff --git a/crates/muelle-shell/src/tracker.rs b/crates/muelle-shell/src/tracker.rs
index 871244a..911a0c1 100644
--- a/crates/muelle-shell/src/tracker.rs
+++ b/crates/muelle-shell/src/tracker.rs
@@ -123,7 +123,21 @@ pub fn normal_rect(hwnd: isize) -> Option<RECT> {
};
// SAFETY: The structure has its size initialized and lives for the call.
unsafe { GetWindowPlacement(HWND(hwnd as *mut _), &mut placement) }.ok()?;
- let rect = placement.rcNormalPosition;
+ // Placement uses workspace coordinates, whose origin is the top-left
+ // corner of the work area: below the menu bar when it is shown.
+ let (dx, dy) = crate::system::primary_monitor().map_or((0, 0), |monitor| {
+ (
+ monitor.work_left - monitor.screen.left,
+ monitor.work_top - monitor.screen.top,
+ )
+ });
+ let local = placement.rcNormalPosition;
+ let rect = RECT {
+ left: local.left + dx,
+ top: local.top + dy,
+ right: local.right + dx,
+ bottom: local.bottom + dy,
+ };
(rect.right > rect.left && rect.bottom > rect.top).then_some(rect)
}