Skip to content

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

feat: implement transparency effects and enhance UI responsiveness; add support for glass effects in dock and menu bar

CristianOlivera1f137e251272f
diff --git a/.gitignore b/.gitignore
index c95ae22..bec9617 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,5 +5,4 @@ dist/
/.cargo/config.toml
*.log
ejemplos/**
-plan.md
-Muelle_landing.html
\ No newline at end of file
+plan.md
\ No newline at end of file
diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rs
index 95fc447..f482ff4 100644
--- a/apps/dock/src/app.rs
+++ b/apps/dock/src/app.rs
@@ -41,7 +41,7 @@ use muelle_shell::{
recycle_bin::{self, BinWatch},
system::{
animations_enabled, downloads_folder, primary_monitor, set_window_transitions,
- uses_light_theme,
+ transparency_enabled, uses_light_theme,
},
taskbar,
tracker::{self, TrackedWindow, WindowTracker, normalize_id},
@@ -106,6 +106,9 @@ const HSHELL_FLASH: usize = 0x8006;
const SPI_SETWORKAREA: usize = 0x002F;
const WM_POWERBROADCAST: u32 = 0x0218;
const PBT_APMRESUMEAUTOMATIC: usize = 0x0012;
+/// Sent when the charger is plugged in or out, and when energy saver turns
+/// on or off.
+const PBT_APMPOWERSTATUSCHANGE: usize = 0x000A;
const WINDOW_CLASS: PCWSTR = muelle_shell::dock_link::DOCK_WINDOW_CLASS;
const APPBAR_CALLBACK: u32 = WM_APP + 1;
@@ -317,6 +320,7 @@ struct StageKey {
screen: RECT,
scale: f32,
light: bool,
+ glass: bool,
bin_full: bool,
auto_hide: bool,
icon_size: u32,
@@ -622,6 +626,9 @@ impl App {
screen: monitor.screen,
scale: monitor.scale,
light: uses_light_theme(),
+ // A backdrop brush made while Windows had transparency off stays
+ // black after it comes back, so this rebuilds the dock both ways.
+ glass: transparency_enabled(),
bin_full: self.bin_full,
auto_hide: self.config.auto_hide,
icon_size: self.config.icon_size,
@@ -640,7 +647,7 @@ impl App {
..Metrics::DEFAULT
}
.scaled(scale);
- let theme = Theme::for_system(key.light);
+ let theme = Theme::for_system(key.light, key.glass);
let px = |logical: f32| (logical * scale).round();
self.entries = key.entries.clone();
@@ -2081,6 +2088,10 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) ->
// SAFETY: `hwnd` is our window; scheduling the same timer resets it.
unsafe { SetTimer(Some(hwnd), REFRESH_TIMER, REFRESH_DELAY_MS, None) };
}
+ WM_POWERBROADCAST if w.0 == PBT_APMPOWERSTATUSCHANGE => {
+ // SAFETY: `hwnd` is our window; scheduling the same timer resets it.
+ unsafe { SetTimer(Some(hwnd), REFRESH_TIMER, REFRESH_DELAY_MS, None) };
+ }
WM_TIMER if w.0 == BIN_TIMER => {
// SAFETY: `hwnd` is this live window on its owning UI thread.
unsafe {
diff --git a/apps/dock/src/flight.rs b/apps/dock/src/flight.rs
index ae4a79b..bf15a30 100644
--- a/apps/dock/src/flight.rs
+++ b/apps/dock/src/flight.rs
@@ -7,20 +7,24 @@
//!
//! 1. one live DWM thumbnail is shown exactly where the window was (nothing
//! changes on screen);
-//! 2. a frame later that rectangle is copied from the screen: a snapshot, as
-//! macOS also uses for its genie;
-//! 3. the strips cut from it go up, still, under the stand-in, which stays for
-//! two more frames: composition commits asynchronously while DWM drops a
-//! thumbnail on the very next frame, and removing it at once left a frame
-//! with neither, a visible flash;
-//! 4. the snapshot is one composition surface shared by thin horizontal
+//! 2. at the same moment a worker thread copies that rectangle from the
+//! screen: a snapshot, as macOS also uses for its genie;
+//! 3. the snapshot becomes one composition surface shared by thin horizontal
//! strips (plain composition visuals) that follow the genie curves
-//! (`muelle_core::genie`).
+//! (`muelle_core::genie`), and they start flying at once;
+//! 4. the stand-in stays under them for two more frames: composition commits
+//! asynchronously while DWM drops a thumbnail on the very next frame, and
+//! removing it at once left a frame with neither, a visible flash.
//!
//! The stand-in goes up before the dock even knows where the window will land
//! (`Flight::start`, then `Flight::aim`): the window has already vanished, and
//! every millisecond until the stand-in shows is a flash of the desktop.
//!
+//! Until the strips move, the window just sits there, and that pause reads as
+//! lag. It is the screen copy, 30-80 ms that GDI takes whatever the size, so
+//! nothing else waits on it: no frames are counted before it, and none after.
+//! Waiting two frames on each side used to add up to about 200 ms.
+//!
//! The dock does not move the strips itself. Each strip gets two expression
//! animations (offset and scale) that read two shared values, `bend` and
//! `shift`, and those two are keyframe animations: the system compositor runs
@@ -42,7 +46,11 @@
//! hears about the minimize and cannot be cancelled afterwards.
use std::{
- sync::OnceLock,
+ sync::{
+ OnceLock,
+ mpsc::{Receiver, TryRecvError, channel},
+ },
+ thread,
time::{Duration, Instant},
};
@@ -65,7 +73,8 @@ use windows::{
System::{LibraryLoader::GetModuleHandleW, WinRT::Composition::ICompositorDesktopInterop},
UI::WindowsAndMessaging::{
CreateWindowExW, DefWindowProcW, DestroyWindow, RegisterClassW, SW_SHOWNOACTIVATE,
- ShowWindow, WNDCLASSW, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP,
+ SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_SHOWWINDOW, SetWindowPos, ShowWindow,
+ WNDCLASSW, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP,
WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP,
},
},
@@ -86,10 +95,9 @@ const KEYFRAMES: u32 = 30;
/// positions while they fly; overlapping the next one (same pixels) leaves no
/// seam between their antialiased edges.
const OVERLAP_ROWS: f32 = 1.0;
-/// Frames the thumbnail stays up before the screen is copied, so DWM has
-/// certainly presented it.
-const FRAMES_BEFORE_SNAPSHOT: u32 = 2;
-/// Frames the still strips and the stand-in overlap before the stand-in goes.
+/// Frames a minimize waits to learn its dock slot before giving up.
+const FRAMES_TO_AIM: u32 = 2;
+/// Frames the strips and the stand-in overlap before the stand-in goes.
const HANDOVER_FRAMES: u32 = 2;
/// The dock's own thumbnail fades in over the last part of the animation.
const LANDING_START: f32 = 0.8;
@@ -122,19 +130,19 @@ struct Piece {
}
enum Phase {
- /// The stand-in thumbnail is on screen; counting frames until the snapshot.
- Standing { thumbnail: isize, frames: u32 },
- /// The strips are up and still under the stand-in, until they are
- /// certainly on screen.
- Handover {
+ /// The stand-in thumbnail is on screen while a worker copies the screen.
+ Standing {
thumbnail: isize,
frames: u32,
- drive: CompositionPropertySet,
+ shot: Receiver<Option<IconImage>>,
},
Flying {
start: Instant,
/// Kept alive: the strips' animations read it.
_drive: CompositionPropertySet,
+ /// The stand-in of a minimize and the frames it has overlapped the
+ /// strips, until they are certainly on screen.
+ stand_in: Option<(isize, u32)>,
},
/// A restore has reached full size and waits for the real window.
Settling { until: Instant },
@@ -144,6 +152,8 @@ pub struct Flight {
/// The window being minimized or restored.
pub hwnd: isize,
overlay: HWND,
+ /// The window under the overlay that holds a minimize's stand-in.
+ stand: Option<HWND>,
/// Kept alive: it owns the overlay's visual tree.
_target: DesktopWindowTarget,
root: ContainerVisual,
@@ -208,8 +218,8 @@ fn halved(image: &IconImage) -> IconImage {
}
}
-/// The transparent, click-through window that covers `screen` during a flight.
-fn create_overlay(gfx: &Gfx, screen: RECT) -> Option<(HWND, DesktopWindowTarget, ContainerVisual)> {
+/// A transparent, click-through window that covers `screen` during a flight.
+fn create_window(screen: RECT) -> Option<HWND> {
static CLASS: OnceLock<bool> = OnceLock::new();
let class = w!("MuelleFlight");
// SAFETY: Standard class registration and window creation on the UI
@@ -224,7 +234,7 @@ fn create_overlay(gfx: &Gfx, screen: RECT) -> Option<(HWND, DesktopWindowTarget,
..Default::default()
}) != 0
});
- let overlay = CreateWindowExW(
+ CreateWindowExW(
WS_EX_LAYERED
| WS_EX_TRANSPARENT
| WS_EX_NOREDIRECTIONBITMAP
@@ -243,8 +253,16 @@ fn create_overlay(gfx: &Gfx, screen: RECT) -> Option<(HWND, DesktopWindowTarget,
Some(instance.into()),
None,
)
- .ok()?;
+ .ok()
+ }
+}
+/// The window the strips are drawn on, with the root of its visual tree.
+fn create_overlay(gfx: &Gfx, screen: RECT) -> Option<(HWND, DesktopWindowTarget, ContainerVisual)> {
+ let overlay = create_window(screen)?;
+ // SAFETY: `overlay` is the live window created above; it is destroyed
+ // here on failure, or by `Flight::drop`.
+ unsafe {
let tree = || -> Result<(DesktopWindowTarget, ContainerVisual)> {
let target = gfx
.compositor
@@ -431,11 +449,22 @@ impl Flight {
if is_empty(visible) {
return None;
}
- let (overlay, target, root) = create_overlay(gfx, screen)?;
- // SAFETY: `overlay` is the live window created above; it is destroyed
+ // The stand-in has a window of its own, under the strips: DWM draws a
+ // thumbnail over everything else in its window, and there it would
+ // hide the first frames of the flight.
+ let stand = create_window(screen)?;
+ let Some((overlay, target, root)) = create_overlay(gfx, screen) else {
+ // SAFETY: Our own window, destroyed once.
+ unsafe {
+ let _ = DestroyWindow(stand);
+ }
+ return None;
+ };
+ // SAFETY: Both are the live windows created above; they are destroyed
// here on failure, or by `Drop`.
let thumbnail = unsafe {
- let Ok(thumbnail) = DwmRegisterThumbnail(overlay, HWND(hwnd as *mut _)) else {
+ let Ok(thumbnail) = DwmRegisterThumbnail(stand, HWND(hwnd as *mut _)) else {
+ let _ = DestroyWindow(stand);
let _ = DestroyWindow(overlay);
return None;
};
@@ -458,12 +487,29 @@ impl Flight {
};
let _ = DwmUpdateThumbnailProperties(thumbnail, &properties);
let _ = ShowWindow(overlay, SW_SHOWNOACTIVATE);
+ let _ = SetWindowPos(
+ stand,
+ Some(overlay),
+ 0,
+ 0,
+ 0,
+ 0,
+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW,
+ );
thumbnail
};
+ // Copying the screen takes 30-80 ms however small the rectangle, so it
+ // runs on a worker from the first moment instead of holding the dock.
+ // GDI reads what DWM composes next, and that includes the stand-in.
+ let (sender, shot) = channel();
+ thread::spawn(move || {
+ let _ = sender.send(screen::capture(visible));
+ });
let window = local(visible, screen);
Some(Self {
hwnd,
overlay,
+ stand: Some(stand),
_target: target,
root,
screen,
@@ -476,6 +522,7 @@ impl Flight {
phase: Phase::Standing {
thumbnail,
frames: 0,
+ shot,
},
restoring: false,
restore_pending: false,
@@ -519,6 +566,7 @@ impl Flight {
let flight = Self {
hwnd,
overlay,
+ stand: None,
_target: target,
root,
screen,
@@ -527,6 +575,7 @@ impl Flight {
phase: Phase::Flying {
start: Instant::now(),
_drive: drive,
+ stand_in: None,
},
restoring: true,
restore_pending: true,
@@ -542,54 +591,49 @@ impl Flight {
/// Advances the animation; returns `false` once it has finished (or cannot go on).
pub fn step(&mut self, gfx: &Gfx, now: Instant) -> bool {
match &mut self.phase {
- Phase::Standing { thumbnail, frames } => {
+ Phase::Standing {
+ thumbnail,
+ frames,
+ shot,
+ } => {
*frames += 1;
- if *frames <= FRAMES_BEFORE_SNAPSHOT {
- return true;
- }
// No slot to fly to: the window just stays minimized.
if !self.aimed {
- return false;
+ return *frames <= FRAMES_TO_AIM;
}
+ let image = match shot.try_recv() {
+ Ok(Some(image)) => image,
+ Err(TryRecvError::Empty) => return true,
+ Ok(None) | Err(TryRecvError::Disconnected) => return false,
+ };
let thumbnail = *thumbnail;
- let Ok(drive) = self.take_off(gfx) else {
+ let Ok(drive) = self.take_off(gfx, image) else {
return false;
};
- self.phase = Phase::Handover {
- thumbnail,
- frames: 0,
- drive,
- };
- true
- }
- Phase::Handover {
- thumbnail,
- frames,
- drive,
- } => {
- *frames += 1;
- if *frames <= HANDOVER_FRAMES {
- return true;
- }
- let (thumbnail, drive) = (*thumbnail, drive.clone());
- if launch(gfx, &self.genie, &drive, false).is_err() {
- return false;
- }
- // The strips have been on screen for a while, showing the same
- // image: the stand-in can go. The clock starts now, so copying
- // the screen does not eat the animation.
- // SAFETY: `thumbnail` came from DwmRegisterThumbnail and is released once.
- unsafe {
- let _ = DwmUnregisterThumbnail(thumbnail);
- }
+ // The clock starts now, so copying the screen does not eat
+ // the animation.
self.phase = Phase::Flying {
start: Instant::now(),
_drive: drive,
+ stand_in: Some((thumbnail, 0)),
};
true
}
// The compositor is flying the strips; only the end is ours.
- Phase::Flying { start, .. } => {
+ Phase::Flying {
+ start, stand_in, ..
+ } => {
+ if let Some((thumbnail, frames)) = stand_in {
+ *frames += 1;
+ if *frames > HANDOVER_FRAMES {
+ // The strips are on screen by now: the stand-in can go.
+ // SAFETY: `thumbnail` came from DwmRegisterThumbnail and is released once.
+ unsafe {
+ let _ = DwmUnregisterThumbnail(*thumbnail);
+ }
+ *stand_in = None;
+ }
+ }
let t = now.saturating_duration_since(*start).as_secs_f32() / DURATION_SECONDS;
if t < 1.0 {
return true;
@@ -658,9 +702,9 @@ impl Flight {
(((t - LANDING_START) / (1.0 - LANDING_START)).clamp(0.0, 1.0) * 255.0) as u8
}
- /// Copies the window's rectangle from the screen, cuts it into strips and
- /// ties them to the genie, still at the window's place.
- fn take_off(&mut self, gfx: &Gfx) -> Result<CompositionPropertySet> {
+ /// Cuts the copy of the window (`image`) into strips, ties them to the
+ /// genie and starts it.
+ fn take_off(&mut self, gfx: &Gfx, image: IconImage) -> Result<CompositionPropertySet> {
let edges = self.genie.window;
let window = RECT {
left: edges.left as i32 + self.screen.left,
@@ -668,11 +712,10 @@ impl Flight {
right: edges.right as i32 + self.screen.left,
bottom: edges.bottom as i32 + self.screen.top,
};
- let image =
- screen::capture(window).ok_or_else(|| anyhow::anyhow!("screen capture failed"))?;
let pieces = cut(gfx, &self.root, &image, image.height)?;
let size = (image.width as f32, image.height as f32);
let drive = bind(gfx, &self.genie, &pieces, size, false)?;
+ launch(gfx, &self.genie, &drive, false)?;
self.captured = Some((image, window));
Ok(drive)
}
@@ -683,11 +726,18 @@ impl Drop for Flight {
// SAFETY: The handles were created in `start` or `restore` and are
// released once.
unsafe {
- if let Phase::Standing { thumbnail, .. } | Phase::Handover { thumbnail, .. } =
- self.phase
+ if let Phase::Standing { thumbnail, .. }
+ | Phase::Flying {
+ stand_in: Some((thumbnail, _)),
+ ..
+ } = &self.phase
{
+ let thumbnail = *thumbnail;
let _ = DwmUnregisterThumbnail(thumbnail);
}
+ if let Some(stand) = self.stand {
+ let _ = DestroyWindow(stand);
+ }
let _ = DestroyWindow(self.overlay);
}
}
diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rs
index 422761c..bcd4870 100644
--- a/apps/dock/src/gfx.rs
+++ b/apps/dock/src/gfx.rs
@@ -24,7 +24,8 @@ use windows::{
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,
+ D2D1_PRIMITIVE_BLEND_COPY, D2D1_PRIMITIVE_BLEND_SOURCE_OVER, D2D1_ROUNDED_RECT,
+ D2D1CreateDevice, ID2D1Device, ID2D1DeviceContext,
},
Direct3D::D3D_DRIVER_TYPE_WARP,
Direct3D11::{
@@ -587,6 +588,37 @@ impl Gfx {
},
&fill,
);
+ if charging {
+ // A bolt over the middle of the body, as on a Mac, with a
+ // clear gap cut around it so it reads over the level.
+ let bolt = dc.GetFactory()?.CreatePathGeometry()?;
+ let sink = bolt.Open()?;
+ let (bolt_width, bolt_height) = (height * 0.62, height * 1.04);
+ let left = (body_right - bolt_width) / 2.0;
+ let top = (height - bolt_height) / 2.0;
+ let at = |x: f32, y: f32| Vector2 {
+ X: left + x * bolt_width,
+ Y: top + y * bolt_height,
+ };
+ sink.BeginFigure(at(0.62, 0.0), D2D1_FIGURE_BEGIN_FILLED);
+ for (x, y) in [
+ (0.08, 0.58),
+ (0.46, 0.58),
+ (0.36, 1.0),
+ (0.92, 0.40),
+ (0.54, 0.40),
+ ] {
+ sink.AddLine(at(x, y));
+ }
+ sink.EndFigure(D2D1_FIGURE_END_CLOSED);
+ sink.Close()?;
+ let clear = dc.CreateSolidColorBrush(&TRANSPARENT, None)?;
+ dc.SetPrimitiveBlend(D2D1_PRIMITIVE_BLEND_COPY);
+ dc.DrawGeometry(&bolt, &clear, 2.0 * stroke, None);
+ dc.SetPrimitiveBlend(D2D1_PRIMITIVE_BLEND_SOURCE_OVER);
+ let ink = dc.CreateSolidColorBrush(&ink.color(), None)?;
+ dc.FillGeometry(&bolt, &ink, None);
+ }
}
Ok(())
})?;
diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rs
index 4e91737..958d014 100644
--- a/apps/dock/src/menubar.rs
+++ b/apps/dock/src/menubar.rs
@@ -107,6 +107,8 @@ struct Look {
screen: RECT,
scale: f32,
light: bool,
+ /// See `system::transparency_enabled`.
+ glass: bool,
app_name: String,
clock: String,
battery: Option<Battery>,
@@ -376,6 +378,7 @@ impl MenuBar {
screen: monitor.screen,
scale: monitor.scale,
light: system::uses_light_theme(),
+ glass: system::transparency_enabled(),
app_name: self.app_name.clone(),
clock: system::clock_text(),
battery: system::battery(),
@@ -403,17 +406,22 @@ impl MenuBar {
Y: height,
})?;
let layers = root.Children()?;
- let tint = if look.light {
- rgba(255, 255, 255, 110)
+ // Without transparency the bar is solid, as macOS draws it with
+ // "Reduce transparency".
+ let tint = match (look.light, look.glass) {
+ (true, true) => rgba(255, 255, 255, 110),
+ (false, true) => rgba(24, 24, 26, 120),
+ (true, false) => rgba(236, 236, 238, 255),
+ (false, false) => rgba(36, 36, 38, 255),
+ };
+ let backdrop = if look.glass {
+ Some(c.CreateHostBackdropBrush()?.cast()?)
} else {
- rgba(24, 24, 26, 120)
+ None
};
- let fills = [
- c.CreateHostBackdropBrush()?
- .cast::<windows::UI::Composition::CompositionBrush>()?,
- c.CreateColorBrushWithColor(tint)?.cast()?,
- ];
- for brush in &fills {
+ let fills: [windows::UI::Composition::CompositionBrush; 1] =
+ [c.CreateColorBrushWithColor(tint)?.cast()?];
+ for brush in backdrop.iter().chain(&fills) {
let fill = c.CreateSpriteVisual()?;
fill.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;
fill.SetBrush(brush)?;
diff --git a/apps/dock/src/scene.rs b/apps/dock/src/scene.rs
index 103ada4..0fbc499 100644
--- a/apps/dock/src/scene.rs
+++ b/apps/dock/src/scene.rs
@@ -23,6 +23,8 @@ use crate::gfx::{Gfx, LabelBrush};
#[derive(Clone, Copy)]
pub struct Theme {
pub light: bool,
+ /// Blur what is behind the dock; without it the tint is drawn opaque.
+ glass: bool,
tint: Color,
separator: Color,
shadow: Color,
@@ -30,11 +32,19 @@ pub struct Theme {
}
impl Theme {
- pub fn for_system(light: bool) -> Self {
+ /// `glass` is false while Windows has transparency off (or energy saver
+ /// on): the dock is then solid gray, as macOS draws it with "Reduce
+ /// transparency".
+ pub fn for_system(light: bool, glass: bool) -> Self {
if light {
Self {
light,
- tint: rgba(255, 255, 255, 46),
+ glass,
+ tint: if glass {
+ rgba(255, 255, 255, 46)
+ } else {
+ rgba(226, 226, 228, 255)
+ },
separator: rgba(0, 0, 0, 56),
shadow: rgba(0, 0, 0, 56),
indicator: rgba(0, 0, 0, 170),
@@ -42,7 +52,12 @@ impl Theme {
} else {
Self {
light,
- tint: rgba(28, 28, 30, 82),
+ glass,
+ tint: if glass {
+ rgba(28, 28, 30, 82)
+ } else {
+ rgba(44, 44, 46, 255)
+ },
separator: rgba(255, 255, 255, 64),
shadow: rgba(0, 0, 0, 96),
indicator: rgba(255, 255, 255, 215),
@@ -194,12 +209,16 @@ impl Scene {
stops
.Append(&c.CreateColorGradientStopWithOffsetAndColor(0.55, rgba(255, 255, 255, 0))?)?;
- let fills: [CompositionBrush; 3] = [
- c.CreateHostBackdropBrush()?.cast()?,
+ let backdrop: Option<CompositionBrush> = if theme.glass {
+ Some(c.CreateHostBackdropBrush()?.cast()?)
+ } else {
+ None
+ };
+ let fills = [
c.CreateColorBrushWithColor(theme.tint)?.cast()?,
sheen.cast()?,
];
- for brush in &fills {
+ for brush in backdrop.iter().chain(&fills) {
let fill = c.CreateSpriteVisual()?;
fill.SetRelativeSizeAdjustment(v2(1.0, 1.0))?;
fill.SetBrush(brush)?;
diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsx
index 6cdb1ea..a15471b 100644
--- a/apps/settings/src/App.tsx
+++ b/apps/settings/src/App.tsx
@@ -18,7 +18,7 @@ import {
saveConfig,
setAutostart,
} from "./config";
-import { Card, Row, Segmented, Slider, Toggle } from "./controls";
+import { Card, Row, Segmented, Slider, SubRow, Toggle } from "./controls";
import { UpdateBanner } from "./UpdateBanner";
import en from "./i18n/en.json";
import es from "./i18n/es.json";
@@ -240,7 +240,7 @@ export function App() {
onChange={(magnification) => update({ magnification })}
/>
</Row>
- <Row label={t.magnifiedSize} nested>
+ <SubRow label={t.magnifiedSize} open={config.magnification}>
<Slider
label={t.magnifiedSize}
value={config.magnifiedSize}
@@ -248,10 +248,9 @@ export function App() {
max={MAX_MAGNIFIED_SIZE}
before={t.small}
after={t.large}
- disabled={!config.magnification}
onChange={(magnifiedSize) => update({ magnifiedSize })}
/>
- </Row>
+ </SubRow>
</Card>
<Card>
<Row label={t.autoHide} hint={t.autoHideHint}>
@@ -268,15 +267,17 @@ export function App() {
onChange={(menuBar) => update({ menuBar })}
/>
</Row>
- {config.menuBar ? (
- <Row label={t.menuBarAutoHide} hint={t.menuBarAutoHideHint} nested>
- <Toggle
- label={t.menuBarAutoHide}
- checked={config.menuBarAutoHide}
- onChange={(menuBarAutoHide) => update({ menuBarAutoHide })}
- />
- </Row>
- ) : null}
+ <SubRow
+ label={t.menuBarAutoHide}
+ hint={t.menuBarAutoHideHint}
+ open={config.menuBar}
+ >
+ <Toggle
+ label={t.menuBarAutoHide}
+ checked={config.menuBarAutoHide}
+ onChange={(menuBarAutoHide) => update({ menuBarAutoHide })}
+ />
+ </SubRow>
<Row label={t.genie} hint={t.genieHint}>
<Toggle
label={t.genie}
diff --git a/apps/settings/src/controls.tsx b/apps/settings/src/controls.tsx
index 833cde1..7736a43 100644
--- a/apps/settings/src/controls.tsx
+++ b/apps/settings/src/controls.tsx
@@ -7,13 +7,12 @@ export function Card({ children }: { children: ReactNode }) {
interface RowProps {
label: string;
hint?: string;
- nested?: boolean;
children: ReactNode;
}
-export function Row({ label, hint, nested = false, children }: RowProps) {
+export function Row({ label, hint, children }: RowProps) {
return (
- <div className={nested ? "row row-nested" : "row"}>
+ <div className="row">
<div className="row-text">
<span className="row-label">{label}</span>
{hint ? <span className="row-hint">{hint}</span> : null}
@@ -23,6 +22,26 @@ export function Row({ label, hint, nested = false, children }: RowProps) {
);
}
+interface SubRowProps extends RowProps {
+ /** Whether the option it depends on is on; the row folds away while it is off. */
+ open: boolean;
+}
+
+/**
+ * An option that only makes sense while the row above it is on. It stays
+ * mounted so it can fold open and shut, and is `inert` while folded so the
+ * keyboard and screen readers skip it.
+ */
+export function SubRow({ open, ...row }: SubRowProps) {
+ return (
+ <div className="row-sub" data-open={open} inert={!open}>
+ <div className="row-sub-clip">
+ <Row {...row} />
+ </div>
+ </div>
+ );
+}
+
interface ToggleProps {
checked: boolean;
label: string;
diff --git a/apps/settings/src/styles.css b/apps/settings/src/styles.css
index aa5ae2f..d69508c 100644
--- a/apps/settings/src/styles.css
+++ b/apps/settings/src/styles.css
@@ -276,35 +276,44 @@ input:focus-visible {
padding: 8px 14px;
}
-.row + .row {
+.row + .row,
+.row-sub + .row {
border-top: 1px solid var(--line);
}
-.row-nested {
- position: relative;
- padding-left: 34px;
- background: var(--hover);
+/* An option that depends on the row above: indented under it, with a divider
+ that starts at the indent, and folded away while that row is off. */
+.row-sub {
+ display: grid;
+ grid-template-rows: 1fr;
+ transition:
+ grid-template-rows 0.24s cubic-bezier(0.3, 0.7, 0.2, 1),
+ opacity 0.2s ease;
}
-.row-nested::before,
-.row-nested::after {
- position: absolute;
- content: "";
- border-color: var(--line);
+.row-sub[data-open="false"] {
+ grid-template-rows: 0fr;
+ opacity: 0;
}
-.row-nested::before {
- top: 0;
- bottom: 50%;
- left: 21px;
- border-left: 1px solid;
+.row-sub-clip {
+ min-height: 0;
+ overflow: hidden;
+}
+
+.row-sub .row {
+ position: relative;
+ padding-left: 30px;
}
-.row-nested::after {
- top: 50%;
- left: 21px;
- width: 10px;
- border-top: 1px solid;
+.row-sub .row::before {
+ position: absolute;
+ top: 0;
+ right: 0;
+ left: 30px;
+ height: 1px;
+ content: "";
+ background: var(--line);
}
.row-text {
@@ -433,6 +442,7 @@ input:focus-visible {
@media (prefers-reduced-motion: reduce) {
.toggle,
.toggle-knob,
+ .row-sub,
.update-progress span {
transition: none;
}
diff --git a/crates/muelle-shell/src/system.rs b/crates/muelle-shell/src/system.rs
index a02591c..faca8bd 100644
--- a/crates/muelle-shell/src/system.rs
+++ b/crates/muelle-shell/src/system.rs
@@ -12,7 +12,7 @@ use windows::{
WindowsAndMessaging::{SPI_GETCLIENTAREAANIMATION, SystemParametersInfoW},
},
},
- core::{BOOL, w},
+ core::{BOOL, PCWSTR, w},
};
/// Returns `true` if Windows uses the light theme for the taskbar and shell.
@@ -20,21 +20,43 @@ use windows::{
/// Assumes the dark theme on read failure (the Windows 11 shell default).
#[must_use]
pub fn uses_light_theme() -> bool {
+ personalize(w!("SystemUsesLightTheme")).is_some_and(|value| value != 0)
+}
+
+/// Returns `true` while Windows draws see-through surfaces: "Transparency
+/// effects" is on and energy saver is off (it turns them off). Otherwise the
+/// system backdrop brush stops blurring and shows up black, so glass has to
+/// be drawn solid.
+#[must_use]
+pub fn transparency_enabled() -> bool {
+ use windows::Win32::System::Power::{GetSystemPowerStatus, SYSTEM_POWER_STATUS};
+ const SAVER_ON: u8 = 1;
+ let mut status = SYSTEM_POWER_STATUS::default();
+ // SAFETY: `status` is a valid structure the call fills in.
+ let saver = unsafe { GetSystemPowerStatus(&mut status) }.is_ok()
+ && status.SystemStatusFlag & SAVER_ON != 0;
+ // Missing means never changed, and the default is on.
+ !saver && personalize(w!("EnableTransparency")) != Some(0)
+}
+
+/// A DWORD from the user's personalization settings.
+fn personalize(name: PCWSTR) -> Option<u32> {
let mut value = 0u32;
let mut size = size_of::<u32>() as u32;
// SAFETY: `value` and `size` describe a valid 4-byte buffer.
- let status = unsafe {
+ unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
w!("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"),
- w!("SystemUsesLightTheme"),
+ name,
RRF_RT_REG_DWORD,
None,
Some((&raw mut value).cast()),
Some(&mut size),
)
- };
- status.is_ok() && value != 0
+ }
+ .is_ok()
+ .then_some(value)
}
/// Monitor bounds, work area, and scale in physical pixels.
diff --git a/spikes/src/bin/spike_capture.rs b/spikes/src/bin/spike_capture.rs
new file mode 100644
index 0000000..0c3a531
--- /dev/null
+++ b/spikes/src/bin/spike_capture.rs
@@ -0,0 +1,51 @@
+//! Times copying a window-sized rectangle of the screen, the step that delays
+//! the genie's take-off.
+
+use std::time::Instant;
+
+use muelle_shell::screen;
+use windows::Win32::{
+ Foundation::RECT,
+ Graphics::Gdi::{
+ BitBlt, CAPTUREBLT, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject,
+ GetDC, ReleaseDC, SRCCOPY, SelectObject,
+ },
+};
+
+fn main() {
+ let rect = RECT {
+ left: 200,
+ top: 100,
+ right: 1500,
+ bottom: 900,
+ };
+ for round in 0..6 {
+ let start = Instant::now();
+ let image = screen::capture(rect);
+ println!(
+ "round {round}: screen::capture {:.1} ms ({})",
+ start.elapsed().as_secs_f32() * 1000.0,
+ image.is_some()
+ );
+ // SAFETY: Every GDI object is released before the block ends.
+ unsafe {
+ let screen_dc = GetDC(None);
+ let memory = CreateCompatibleDC(Some(screen_dc));
+ let bitmap = CreateCompatibleBitmap(screen_dc, 1300, 800);
+ let previous = SelectObject(memory, bitmap.into());
+ for (name, rop) in [("plain", SRCCOPY), ("captureblt", SRCCOPY | CAPTUREBLT)] {
+ let start = Instant::now();
+ let _ = BitBlt(memory, 0, 0, 1300, 800, Some(screen_dc), 200, 100, rop);
+ println!(
+ " BitBlt {name}: {:.1} ms",
+ start.elapsed().as_secs_f32() * 1000.0
+ );
+ }
+ SelectObject(memory, previous);
+ let _ = DeleteObject(bitmap.into());
+ let _ = DeleteDC(memory);
+ ReleaseDC(None, screen_dc);
+ }
+ std::thread::sleep(std::time::Duration::from_millis(300));
+ }
+}
diff --git a/spikes/src/bin/spike_genie.rs b/spikes/src/bin/spike_genie.rs
new file mode 100644
index 0000000..fb58e23
--- /dev/null
+++ b/spikes/src/bin/spike_genie.rs
@@ -0,0 +1,135 @@
+//! A plain magenta window that minimizes itself, to time the genie's take-off
+//! and see what is on screen while it flies.
+//!
+//! Usage: `spike_genie [cycles] [probe_ms]`. After each minimize it waits
+//! `probe_ms` and reports how much of the window's rectangle is still magenta
+//! in the top and bottom rows of the screen copy.
+
+use std::{thread::sleep, time::Duration};
+
+use muelle_shell::screen;
+use windows::{
+ Win32::{
+ Foundation::{COLORREF, HWND, LPARAM, LRESULT, RECT, WPARAM},
+ Graphics::Gdi::CreateSolidBrush,
+ System::LibraryLoader::GetModuleHandleW,
+ UI::WindowsAndMessaging::{
+ CreateWindowExW, DefWindowProcW, DispatchMessageW, MSG, PM_REMOVE, PeekMessageW,
+ RegisterClassW, SW_MINIMIZE, SW_RESTORE, SW_SHOWNOACTIVATE, ShowWindow, WNDCLASSW,
+ WS_OVERLAPPEDWINDOW,
+ },
+ },
+ core::w,
+};
+
+unsafe extern "system" fn proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {
+ // SAFETY: Default handling of our own window's messages.
+ unsafe { DefWindowProcW(hwnd, msg, w, l) }
+}
+
+fn pump(ms: u64) {
+ let mut msg = MSG::default();
+ for _ in 0..ms / 5 {
+ // SAFETY: Standard message pump on the thread that owns the window.
+ unsafe {
+ while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
+ DispatchMessageW(&msg);
+ }
+ }
+ sleep(Duration::from_millis(5));
+ }
+}
+
+/// Share of magenta pixels in row `y` of the rectangle.
+fn magenta(rect: RECT, y: i32) -> f32 {
+ let row = RECT {
+ left: rect.left,
+ top: y,
+ right: rect.right,
+ bottom: y + 1,
+ };
+ screen::capture(row).map_or(-1.0, |image| {
+ let pixels = image.bgra.as_chunks::<4>().0;
+ let hits = pixels
+ .iter()
+ .filter(|pixel| pixel[0] > 240 && pixel[1] < 15 && pixel[2] > 240)
+ .count();
+ hits as f32 / pixels.len().max(1) as f32
+ })
+}
+
+fn main() {
+ let mut args = std::env::args().skip(1);
+ let cycles: u32 = args
+ .next()
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(3);
+ let probe: u64 = args
+ .next()
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(250);
+ let rect = RECT {
+ left: 300,
+ top: 150,
+ right: 1300,
+ bottom: 750,
+ };
+ // SAFETY: Standard class registration and window creation.
+ let hwnd = unsafe {
+ let Ok(instance) = GetModuleHandleW(None) else {
+ return;
+ };
+ let class = w!("MuelleSpikeGenie");
+ RegisterClassW(&WNDCLASSW {
+ lpfnWndProc: Some(proc),
+ hInstance: instance.into(),
+ lpszClassName: class,
+ hbrBackground: CreateSolidBrush(COLORREF(0x00FF_00FF)),
+ ..Default::default()
+ });
+ let Ok(hwnd) = CreateWindowExW(
+ Default::default(),
+ class,
+ w!("Genie spike"),
+ WS_OVERLAPPEDWINDOW,
+ rect.left,
+ rect.top,
+ rect.right - rect.left,
+ rect.bottom - rect.top,
+ None,
+ None,
+ Some(instance.into()),
+ None,
+ ) else {
+ return;
+ };
+ let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);
+ hwnd
+ };
+ pump(2500);
+ // Rows well inside the client area, near its top and its bottom.
+ let (top, bottom) = (rect.top + 80, rect.bottom - 40);
+ println!(
+ "before: top {:.2} bottom {:.2}",
+ magenta(rect, top),
+ magenta(rect, bottom)
+ );
+ for cycle in 0..cycles {
+ // SAFETY: Our own live window.
+ unsafe {
+ let _ = ShowWindow(hwnd, SW_MINIMIZE);
+ }
+ pump(probe);
+ println!(
+ "cycle {cycle}: +{probe} ms top {:.2} bottom {:.2}",
+ magenta(rect, top),
+ magenta(rect, bottom)
+ );
+ pump(1500);
+ // SAFETY: Our own live window.
+ unsafe {
+ let _ = ShowWindow(hwnd, SW_RESTORE);
+ }
+ pump(1500);
+ }
+}