use windows::Win32::Foundation::{COLORREF, RECT};
use windows::Win32::Graphics::Gdi::{
CreateCompatibleBitmap, CreateCompatibleDC, CreateDIBSection, CreateFontIndirectW,
CreateSolidBrush, DeleteDC, DeleteObject, DrawTextW, Ellipse, FillRect, GdiFlush, GetDC,
GetStockObject, GetTextFaceW, ReleaseDC, RoundRect, SelectObject, SetBkMode, SetBrushOrgEx,
SetStretchBltMode, SetTextColor, StretchBlt, ANTIALIASED_QUALITY, BITMAPINFO, BITMAPINFOHEADER,
BI_RGB, DEFAULT_CHARSET, DIB_RGB_COLORS, DT_CENTER, DT_NOPREFIX, DT_SINGLELINE, DT_VCENTER,
HALFTONE, HBITMAP, HDC, HFONT, LOGFONTW, NULL_PEN, SRCCOPY, TRANSPARENT,
};
use windows::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_CXSMICON};
const SCALE: i32 = 4;
pub const fn rgb(c: u32) -> COLORREF {
COLORREF(((c & 0xFF) << 16) | (c & 0xFF00) | ((c >> 16) & 0xFF))
}
pub const BACKGROUND: u32 = 0xF3F3F3;
pub const CARD: u32 = 0xFBFBFB;
pub const CARD_EDGE: u32 = 0xE5E5E5;
pub const FIELD: u32 = 0xFFFFFF;
pub const FIELD_UNDERLINE: u32 = 0x8A8A8A;
pub const SELECTED: u32 = 0xE9E9E9;
pub const TEXT: u32 = 0x1B1B1B;
pub const TEXT_SECONDARY: u32 = 0x5F5F5F;
pub const TEXT_DISABLED: u32 = 0xA0A0A0;
pub enum Shape {
Rounded {
rect: RECT,
radius: i32,
fill: u32,
edge: Option<u32>,
},
Circle {
x: i32,
y: i32,
diameter: i32,
fill: u32,
},
Bar { rect: RECT, fill: u32 },
}
pub unsafe fn smooth(hdc: HDC, area: RECT, background: u32, shapes: &[Shape]) {
let (w, h) = (area.right - area.left, area.bottom - area.top);
if w <= 0 || h <= 0 {
return;
}
let big = CreateCompatibleDC(Some(hdc));
let bitmap = CreateCompatibleBitmap(hdc, w * SCALE, h * SCALE);
let old_bitmap = SelectObject(big, bitmap.into());
let old_pen = SelectObject(big, GetStockObject(NULL_PEN));
fill(big, scaled(rect(0, 0, w, h), 0, 0), background);
let local = |r: RECT| scaled(r, area.left, area.top);
for shape in shapes {
match *shape {
Shape::Rounded {
rect: r,
radius,
fill: colour,
edge,
} => {
let r = local(r);
let round = radius * 2 * SCALE;
if let Some(edge) = edge {
rounded(big, r, round, edge);
let inner = RECT {
left: r.left + SCALE,
top: r.top + SCALE,
right: r.right - SCALE,
bottom: r.bottom - SCALE,
};
rounded(big, inner, (round - 2 * SCALE).max(0), colour);
} else {
rounded(big, r, round, colour);
}
}
Shape::Circle {
x,
y,
diameter,
fill: colour,
} => {
let r = local(rect(x, y, x + diameter, y + diameter));
let brush = CreateSolidBrush(rgb(colour));
let old = SelectObject(big, brush.into());
let _ = Ellipse(big, r.left, r.top, r.right + 1, r.bottom + 1);
SelectObject(big, old);
let _ = DeleteObject(brush.into());
}
Shape::Bar { rect: r, fill: c } => fill(big, local(r), c),
}
}
SetStretchBltMode(hdc, HALFTONE);
let _ = SetBrushOrgEx(hdc, 0, 0, None);
let _ = StretchBlt(
hdc,
area.left,
area.top,
w,
h,
Some(big),
0,
0,
w * SCALE,
h * SCALE,
SRCCOPY,
);
SelectObject(big, old_pen);
SelectObject(big, old_bitmap);
let _ = DeleteObject(bitmap.into());
let _ = DeleteDC(big);
}
pub const fn rect(left: i32, top: i32, right: i32, bottom: i32) -> RECT {
RECT {
left,
top,
right,
bottom,
}
}
fn scaled(r: RECT, dx: i32, dy: i32) -> RECT {
rect(
(r.left - dx) * SCALE,
(r.top - dy) * SCALE,
(r.right - dx) * SCALE,
(r.bottom - dy) * SCALE,
)
}
unsafe fn fill(hdc: HDC, r: RECT, colour: u32) {
let brush = CreateSolidBrush(rgb(colour));
FillRect(hdc, &r, brush);
let _ = DeleteObject(brush.into());
}
unsafe fn rounded(hdc: HDC, r: RECT, round: i32, colour: u32) {
let brush = CreateSolidBrush(rgb(colour));
let old = SelectObject(hdc, brush.into());
let _ = RoundRect(hdc, r.left, r.top, r.right + 1, r.bottom + 1, round, round);
SelectObject(hdc, old);
let _ = DeleteObject(brush.into());
}
pub const SWITCH_W: i32 = 40;
pub const SWITCH_H: i32 = 20;
#[derive(Clone, Copy, Default)]
pub struct Look {
pub enabled: bool,
pub hot: bool,
pub pressed: bool,
pub focus: bool,
}
pub fn switch(x: i32, y: i32, on: bool, look: Look, accent: u32) -> Vec<Shape> {
let track = rect(x, y, x + SWITCH_W, y + SWITCH_H);
let mut shapes = Vec::new();
if look.focus {
shapes.push(Shape::Rounded {
rect: rect(x - 3, y - 3, x + SWITCH_W + 3, y + SWITCH_H + 3),
radius: SWITCH_H / 2 + 3,
fill: CARD,
edge: Some(TEXT),
});
}
let knob = if look.hot || look.pressed { 14 } else { 12 };
let (track_fill, edge, knob_fill) = match (on, look.enabled) {
(true, true) => (
if look.hot { lighten(accent) } else { accent },
None,
0xFFFFFF,
),
(true, false) => (0xC5C5C5, None, 0xFFFFFF),
(false, true) => (
if look.hot { 0xEDEDED } else { CARD },
Some(0x8A8A8A),
0x5D5D5D,
),
(false, false) => (CARD, Some(0xC5C5C5), 0xC5C5C5),
};
shapes.push(Shape::Rounded {
rect: track,
radius: SWITCH_H / 2,
fill: track_fill,
edge,
});
let centre = if on { x + SWITCH_W - 10 } else { x + 10 };
shapes.push(Shape::Circle {
x: centre - knob / 2,
y: y + (SWITCH_H - knob) / 2,
diameter: knob,
fill: knob_fill,
});
shapes
}
pub fn button(area: RECT, primary: bool, look: Look, accent: u32) -> Vec<Shape> {
let (fill, edge) = match (primary, look.enabled) {
(true, true) if look.pressed => (darken(accent), None),
(true, true) if look.hot => (lighten(accent), None),
(true, true) => (accent, None),
(true, false) => (0xBFBFBF, None),
(false, _) if look.pressed => (0xF5F5F5, Some(CARD_EDGE)),
(false, _) if look.hot => (0xF6F6F6, Some(CARD_EDGE)),
(false, _) => (CARD, Some(CARD_EDGE)),
};
let mut shapes = Vec::new();
let inner = if look.focus {
shapes.push(Shape::Rounded {
rect: area,
radius: 6,
fill: BACKGROUND,
edge: Some(TEXT),
});
rect(area.left + 3, area.top + 3, area.right - 3, area.bottom - 3)
} else {
area
};
shapes.push(Shape::Rounded {
rect: inner,
radius: 4,
fill,
edge,
});
shapes
}
pub fn text_box(area: RECT, focused: bool, enabled: bool, accent: u32) -> Vec<Shape> {
let underline = match (focused, enabled) {
(true, _) => accent,
(false, true) => FIELD_UNDERLINE,
(false, false) => CARD_EDGE,
};
let thick = if focused { 2 } else { 1 };
vec![
Shape::Rounded {
rect: area,
radius: 4,
fill: if enabled { FIELD } else { CARD },
edge: Some(CARD_EDGE),
},
Shape::Bar {
rect: rect(
area.left + 3,
area.bottom - thick,
area.right - 3,
area.bottom,
),
fill: underline,
},
]
}
fn channel(c: u32, shift: u32, f: impl Fn(u32) -> u32) -> u32 {
f((c >> shift) & 0xFF).min(255) << shift
}
fn lighten(c: u32) -> u32 {
let up = |v: u32| v + (255 - v) / 8;
channel(c, 16, up) | channel(c, 8, up) | channel(c, 0, up)
}
fn darken(c: u32) -> u32 {
let down = |v: u32| v * 7 / 8;
channel(c, 16, down) | channel(c, 8, down) | channel(c, 0, down)
}
pub fn accent() -> u32 {
const DEFAULT: u32 = 0x005FB8;
const DARK_1: usize = 4;
let palette = crate::os::registry::Key::open_read(
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Accent",
)
.and_then(|key| key.get_binary("AccentPalette"));
match palette
.as_deref()
.and_then(|p| p.get(DARK_1 * 4..DARK_1 * 4 + 3))
{
Some([r, g, b]) => (u32::from(*r) << 16) | (u32::from(*g) << 8) | u32::from(*b),
_ => DEFAULT,
}
}
pub unsafe fn icon_font(base: &LOGFONTW) -> HFONT {
for face in ["Segoe Fluent Icons", "Segoe MDL2 Assets", "Segoe UI Symbol"] {
let mut lf = *base;
set_face(&mut lf, face);
let font = CreateFontIndirectW(&lf);
if font_is(font, face) {
return font;
}
let _ = DeleteObject(font.into());
}
CreateFontIndirectW(base)
}
pub unsafe fn font_is(font: HFONT, face: &str) -> bool {
let hdc = GetDC(None);
if hdc.is_invalid() {
return false;
}
let old = SelectObject(hdc, font.into());
let mut name = [0u16; 32];
let n = GetTextFaceW(hdc, Some(&mut name));
SelectObject(hdc, old);
ReleaseDC(None, hdc);
n > 1 && String::from_utf16_lossy(&name[..n as usize - 1]) == face
}
pub fn set_face(lf: &mut LOGFONTW, name: &str) {
lf.lfFaceName = [0; 32];
for (slot, ch) in lf.lfFaceName.iter_mut().zip(name.encode_utf16()) {
*slot = ch;
}
}
pub fn glyph_bitmap(glyph: &str, colour: u32) -> HBITMAP {
use std::collections::HashMap;
use std::sync::Mutex;
static CACHE: Mutex<Option<HashMap<(String, u32), isize>>> = Mutex::new(None);
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
let cache = cache.get_or_insert_with(HashMap::new);
let key = (glyph.to_string(), colour);
if let Some(&raw) = cache.get(&key) {
return HBITMAP(raw as *mut _);
}
let raw = unsafe { draw_glyph(glyph, colour) };
if raw != 0 {
cache.insert(key, raw);
}
HBITMAP(raw as *mut _)
}
const GLYPH_CONTRAST: f32 = 1.5;
unsafe fn draw_glyph(glyph: &str, colour: u32) -> isize {
let size = GetSystemMetrics(SM_CXSMICON).max(16);
let big = size * SCALE;
let Some((large, large_bits)) = dib(big) else {
return 0;
};
let Some((bitmap, bits)) = dib(size) else {
let _ = DeleteObject(large.into());
return 0;
};
let dc = CreateCompatibleDC(None);
let old_bitmap = SelectObject(dc, large.into());
let base = LOGFONTW {
lfHeight: -big,
lfWeight: 400,
lfCharSet: DEFAULT_CHARSET,
lfQuality: ANTIALIASED_QUALITY,
..Default::default()
};
let font = icon_font(&base);
let old_font = SelectObject(dc, font.into());
SetBkMode(dc, TRANSPARENT);
SetTextColor(dc, rgb(0xFFFFFF));
let mut text: Vec<u16> = glyph.encode_utf16().collect();
let mut area = rect(0, 0, big, big);
DrawTextW(
dc,
&mut text,
&mut area,
DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX,
);
let _ = GdiFlush();
let source = std::slice::from_raw_parts(large_bits, (big * big) as usize);
let pixels = std::slice::from_raw_parts_mut(bits, (size * size) as usize);
let (r, g, b) = ((colour >> 16) & 0xFF, (colour >> 8) & 0xFF, colour & 0xFF);
let (size, scale) = (size as usize, SCALE as usize);
for (index, p) in pixels.iter_mut().enumerate() {
let (x, y) = (index % size * scale, index / size * scale);
let total: u32 = (0..scale)
.flat_map(|dy| (0..scale).map(move |dx| (dx, dy)))
.map(|(dx, dy)| brightness(source[(y + dy) * size * scale + x + dx]))
.sum();
let coverage = total as f32 / (scale * scale * 255) as f32;
let a = (coverage.powf(1.0 / GLYPH_CONTRAST) * 255.0).round() as u32;
*p = (a << 24) | ((r * a / 255) << 16) | ((g * a / 255) << 8) | (b * a / 255);
}
SelectObject(dc, old_font);
let _ = DeleteObject(font.into());
SelectObject(dc, old_bitmap);
let _ = DeleteDC(dc);
let _ = DeleteObject(large.into());
bitmap.0 as isize
}
fn brightness(pixel: u32) -> u32 {
(pixel & 0xFF)
.max((pixel >> 8) & 0xFF)
.max((pixel >> 16) & 0xFF)
}
unsafe fn dib(size: i32) -> Option<(HBITMAP, *mut u32)> {
let info = BITMAPINFO {
bmiHeader: BITMAPINFOHEADER {
biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
biWidth: size,
biHeight: -size,
biPlanes: 1,
biBitCount: 32,
biCompression: BI_RGB.0,
..Default::default()
},
..Default::default()
};
let screen = GetDC(None);
let mut bits = std::ptr::null_mut();
let bitmap = CreateDIBSection(Some(screen), &info, DIB_RGB_COLORS, &mut bits, None, 0);
ReleaseDC(None, screen);
bitmap.ok().map(|b| (b, bits as *mut u32))
}