A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! Porte de src\comum\app2d.h: a base dos apps desenhados com Direct2D (Lembretes, Calendário, Relógio, Time
//! Machine, Contatos, Clima, Fotos, Música, QuickTime, TextEdit, Forçar Encerrar).
//!
//! Diferença do C++ no modo --foto: a janela NÃO aparece na tela (é criada escondida e desenhada direto num
//! bitmap WIC), para o teste não piscar nada no PC.
use std::ffi::c_void;
use windows::core::*;
use windows::Win32::Foundation::*;
use windows::Win32::Graphics::Direct2D::Common::*;
use windows::Win32::Graphics::Direct2D::*;
use windows::Win32::Graphics::DirectWrite::*;
use windows::Win32::Graphics::Dwm::*;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
use windows::Win32::Graphics::Gdi::*;
use windows::Win32::Graphics::Imaging::*;
use windows::Win32::System::Com::*;
use windows::Win32::System::DataExchange::COPYDATASTRUCT;
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::System::Registry::*;
use windows::Win32::System::SystemInformation::GetLocalTime;
use windows::Win32::System::Time::*;
use windows::Win32::UI::HiDpi::*;
use windows::Win32::UI::Shell::*;
use windows::Win32::UI::WindowsAndMessaging::*;
use windows::Win32::Storage::FileSystem::FILE_FLAGS_AND_ATTRIBUTES;
use crate::*;
pub struct Field {
pub h: HWND,
old: isize,
font: HFONT,
done: Option<Box<dyn FnMut(String, i32)>>,
ending: bool,
}
pub struct Estado {
pub d2d: Option<ID2D1Factory>,
pub dw: Option<IDWriteFactory>,
pub family: String,
pub wnd: HWND,
pub rt: Option<ID2D1RenderTarget>,
pub hrt: Option<ID2D1HwndRenderTarget>,
pub hbr: Option<ID2D1SolidColorBrush>,
pub br: Option<ID2D1SolidColorBrush>,
pub bar: f32,
pub bar_wanted: f32,
pub bar_buttons: Vec<RectF>,
foto_rt: Option<ID2D1RenderTarget>,
foto_br: Option<ID2D1SolidColorBrush>,
foto_bmp: Option<IWICBitmap>,
foto_path: Option<Option<String>>,
tema_teste: Option<i32>,
pub field: Field,
field_brush: HBRUSH,
tint: Option<Option<(f32, f32, f32)>>,
icon_family: Option<String>,
}
static S: Global<Estado> = Global::new(Estado {
d2d: None,
dw: None,
family: String::new(),
wnd: HWND(std::ptr::null_mut()),
rt: None,
hrt: None,
hbr: None,
br: None,
bar: 0.0,
bar_wanted: 0.0,
bar_buttons: Vec::new(),
foto_rt: None,
foto_br: None,
foto_bmp: None,
foto_path: None,
tema_teste: None,
field: Field { h: HWND(std::ptr::null_mut()), old: 0, font: HFONT(std::ptr::null_mut()), done: None, ending: false },
field_brush: HBRUSH(std::ptr::null_mut()),
tint: None,
icon_family: None,
});
#[inline]
pub fn s() -> &'static mut Estado {
S.get()
}
#[inline]
pub fn wnd() -> HWND {
s().wnd
}
#[inline]
pub fn rt() -> &'static ID2D1RenderTarget {
s().rt.as_ref().expect("rt fora da pintura")
}
#[inline]
pub fn br() -> &'static ID2D1SolidColorBrush {
s().br.as_ref().expect("br fora da pintura")
}
#[inline]
pub fn dw() -> &'static IDWriteFactory {
s().dw.as_ref().unwrap()
}
#[inline]
pub fn d2d() -> &'static ID2D1Factory {
s().d2d.as_ref().unwrap()
}
pub fn family() -> String {
s().family.clone()
}
pub fn has_font(nome: &str) -> bool {
unsafe {
let mut c: Option<IDWriteFontCollection> = None;
if dw().GetSystemFontCollection(&mut c, false).is_err() {
return false;
}
let Some(c) = c else { return false };
let (mut i, mut ex) = (0u32, BOOL(0));
let n = wz(nome);
let _ = c.FindFamilyName(pc(&n), &mut i, &mut ex);
ex.as_bool()
}
}
pub fn init() -> bool {
unsafe {
let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
s().d2d = D2D1CreateFactory::<ID2D1Factory>(D2D1_FACTORY_TYPE_SINGLE_THREADED, None).ok();
s().dw = DWriteCreateFactory::<IDWriteFactory>(DWRITE_FACTORY_TYPE_SHARED).ok();
if s().d2d.is_none() || s().dw.is_none() {
return false;
}
// issue #283: no tema Mac OS X (Leopard) o texto é em Lucida, não a SF do macOS novo
s().family = if crate::semaforo::leopard() && has_font("Lucida Sans Unicode") {
"Lucida Sans Unicode"
} else if has_font("SF Pro Text") {
"SF Pro Text"
} else if has_font("Inter") {
"Inter"
} else {
"Segoe UI"
}
.into();
true
}
}
/// --tema claro|escuro (teste)
pub fn tema_teste() -> i32 {
*s().tema_teste.get_or_insert_with(|| match arg_valor("--tema").as_deref() {
Some("escuro") => 1,
Some("claro") => 0,
_ => -1,
})
}
pub fn dark() -> bool {
let t = tema_teste();
if t >= 0 {
return t == 1;
}
let mut v: u32 = 1;
let mut cb = 4u32;
unsafe {
let _ = RegGetValueW(
HKEY_CURRENT_USER,
w!("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"),
w!("AppsUseLightTheme"),
RRF_RT_REG_DWORD,
None,
Some(&mut v as *mut u32 as *mut c_void),
Some(&mut cb),
);
}
v == 0
}
pub fn sc() -> f32 {
let d = unsafe { GetDpiForWindow(wnd()) } as f32;
if d <= 0.0 {
1.0
} else {
d / 96.0
}
}
pub fn fmt_full(size: f32, peso: DWRITE_FONT_WEIGHT, align: DWRITE_TEXT_ALIGNMENT, wrap: bool, fam: Option<&str>) -> IDWriteTextFormat {
let fam = fam.map(str::to_string).unwrap_or_else(family);
let f = cjk::format(dw(), &fam, peso, DWRITE_FONT_STYLE_NORMAL, size, "").expect("CreateTextFormat");
unsafe {
let _ = f.SetTextAlignment(align);
let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
let _ = f.SetWordWrapping(if wrap { DWRITE_WORD_WRAPPING_WRAP } else { DWRITE_WORD_WRAPPING_NO_WRAP });
if !wrap {
let t = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
let e = dw().CreateEllipsisTrimmingSign(&f).ok();
let _ = f.SetTrimming(&t, e.as_ref());
}
}
f
}
/// Fmt(size) com peso normal, alinhado à esquerda
pub fn fmt(size: f32) -> IDWriteTextFormat {
fmt_full(size, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_TEXT_ALIGNMENT_LEADING, false, None)
}
pub fn fmt_w(size: f32, peso: DWRITE_FONT_WEIGHT) -> IDWriteTextFormat {
fmt_full(size, peso, DWRITE_TEXT_ALIGNMENT_LEADING, false, None)
}
pub fn fmt_wa(size: f32, peso: DWRITE_FONT_WEIGHT, align: DWRITE_TEXT_ALIGNMENT) -> IDWriteTextFormat {
fmt_full(size, peso, align, false, None)
}
pub fn icon_family() -> String {
if let Some(f) = &s().icon_family {
return f.clone();
}
let f = if has_font("Segoe Fluent Icons") { "Segoe Fluent Icons" } else { "Segoe MDL2 Assets" }.to_string();
s().icon_family = Some(f.clone());
f
}
pub fn text_w(f: &IDWriteTextFormat, t: &str) -> f32 {
unsafe {
let v = w(t);
let Ok(l) = dw().CreateTextLayout(&v, f, 10000.0, 100.0) else { return 0.0 };
let mut m = DWRITE_TEXT_METRICS::default();
if l.GetMetrics(&mut m).is_ok() {
m.widthIncludingTrailingWhitespace
} else {
0.0
}
}
}
pub fn text(t: &str, f: &IDWriteTextFormat, r: RectF, c: Cor) {
if t.is_empty() {
return;
}
unsafe {
br().SetColor(&c);
// CLIP | ENABLE_COLOR_FONT (emojis em cor)
rt().DrawText(&w(t), f, &r, br(), D2D1_DRAW_TEXT_OPTIONS_CLIP | D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT, DWRITE_MEASURING_MODE_NATURAL);
}
}
pub fn fill(r: RectF, c: Cor, rad: f32) {
unsafe {
br().SetColor(&c);
if rad > 0.0 {
rt().FillRoundedRectangle(&rr(r, rad, rad), br());
} else {
rt().FillRectangle(&r, br());
}
}
}
pub fn circle(c: Ponto, r: f32, cor: Cor, cheio: bool, stroke: f32) {
unsafe {
br().SetColor(&cor);
if cheio {
rt().FillEllipse(&ell(c, r, r), br());
} else {
rt().DrawEllipse(&ell(c, r, r), br(), stroke, None);
}
}
}
pub fn line(a: Ponto, b: Ponto, c: Cor, larg: f32) {
unsafe {
br().SetColor(&c);
rt().DrawLine(a, b, br(), larg, None);
}
}
pub fn stroke_rect(r: RectF, c: Cor, rad: f32, larg: f32) {
unsafe {
br().SetColor(&c);
if rad > 0.0 {
rt().DrawRoundedRectangle(&rr(r, rad, rad), br(), larg, None);
} else {
rt().DrawRectangle(&r, br(), larg, None);
}
}
}
// ---- macOS 27: barra de ferramentas unificada
pub fn bar() -> f32 {
s().bar
}
pub fn set_bar_wanted(v: f32) {
s().bar_wanted = v;
}
pub fn bar_button(r: RectF) {
s().bar_buttons.push(r);
}
pub extern "system" fn unified_sub(h: HWND, m: u32, w: WPARAM, l: LPARAM, _: usize, _: usize) -> LRESULT {
unsafe {
if m == WM_NCCALCSIZE && w.0 != 0 {
let p = &mut *(l.0 as *mut NCCALCSIZE_PARAMS);
let top = p.rgrc[0].top;
let r = DefSubclassProc(h, m, w, l);
let p = &mut *(l.0 as *mut NCCALCSIZE_PARAMS);
p.rgrc[0].top = top;
if IsZoomed(h).as_bool() {
let dpi = GetDpiForWindow(h);
p.rgrc[0].top += GetSystemMetricsForDpi(SM_CYFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
}
return r;
}
if m == WM_NCHITTEST {
let r = DefSubclassProc(h, m, w, l);
if r.0 != HTCLIENT as isize {
return r;
}
let mut p = POINT { x: get_x_lparam(l), y: get_y_lparam(l) };
let _ = ScreenToClient(h, &mut p);
let s_ = GetDpiForWindow(h) as f32 / 96.0;
let (x, y) = (p.x as f32 / s_, p.y as f32 / s_);
if !IsZoomed(h).as_bool() && p.y < (5.0 * s_) as i32 {
return LRESULT(HTTOP as isize);
}
let bar = s().bar;
if y >= bar || x < (if bar > 40.0 { 84.0 } else { 72.0 }) {
return LRESULT(HTCLIENT as isize);
}
for b in &s().bar_buttons {
if in_rect(b, x, y) {
return LRESULT(HTCLIENT as isize);
}
}
return LRESULT(HTCAPTION as isize);
}
DefSubclassProc(h, m, w, l)
}
}
/// botão redondo de vidro da barra do macOS 27
pub fn glass_button(r: RectF, dark: bool, hot: bool) {
unsafe {
let rad = (r.bottom - r.top) / 2.0;
for k in (1..=3).rev() {
let k = k as f32;
br().SetColor(&col(0.0, 0.0, 0.0, if dark { 0.10 } else { 0.035 }));
rt().FillRoundedRectangle(&rr(rf(r.left - k * 0.5, r.top + k * 0.6, r.right + k * 0.5, r.bottom + k * 1.1), rad + k, rad + k), br());
}
let v = if hot { 0.95 } else { 0.985 };
let mut c = if dark { col(0.24, 0.24, 0.245, 1.0) } else { col(v, v, v, 1.0) };
if dark && hot {
c = col(0.29, 0.29, 0.295, 1.0);
}
br().SetColor(&c);
rt().FillRoundedRectangle(&rr(r, rad, rad), br());
br().SetColor(&if dark { col(1.0, 1.0, 1.0, 0.13) } else { col(0.0, 0.0, 0.0, 0.09) });
rt().DrawRoundedRectangle(&rr(rf(r.left + 0.25, r.top + 0.25, r.right - 0.25, r.bottom - 0.25), rad - 0.25, rad - 0.25), br(), 0.5, None);
}
}
pub fn glass_field(r: RectF, dark: bool) {
unsafe {
let rad = (r.bottom - r.top) / 2.0;
br().SetColor(&col(0.0, 0.0, 0.0, if dark { 0.12 } else { 0.03 }));
rt().FillRoundedRectangle(&rr(rf(r.left, r.top + 1.0, r.right, r.bottom + 1.5), rad, rad), br());
br().SetColor(&if dark { col(1.0, 1.0, 1.0, 0.08) } else { col(0.975, 0.98, 0.985, 1.0) });
rt().FillRoundedRectangle(&rr(r, rad, rad), br());
br().SetColor(&if dark { col(1.0, 1.0, 1.0, 0.12) } else { col(0.0, 0.0, 0.0, 0.08) });
rt().DrawRoundedRectangle(&rr(rf(r.left + 0.25, r.top + 0.25, r.right - 0.25, r.bottom - 0.25), rad - 0.25, rad - 0.25), br(), 0.5, None);
}
}
pub fn icon_sidebar(c: Ponto, cor: Cor) {
unsafe {
br().SetColor(&cor);
let b: ID2D1Brush = br().cast().unwrap();
if simbolo::draw(rt(), "sidebar.left", rf(c.x - 9.0, c.y - 7.0, c.x + 9.0, c.y + 7.0), &b) {
return;
}
let s_ = sc();
let px = |v: f32| (v * s_).round() / s_;
let stroke = |p: f32| (p * s_).round().max(1.0) / s_;
let mid = |w_: f32| if ((w_ * s_).round() % 2.0) == 1.0 { 0.5 / s_ } else { 0.0 };
let wd = stroke(1.2);
let h = mid(wd);
let wt = stroke(1.0);
let ht = mid(wt);
let (cx, cy) = (px(c.x), px(c.y));
let r = rf(px(cx - 9.5) + h, px(cy - 7.5) + h, px(cx + 9.5) - h, px(cy + 7.5) - h);
rt().DrawRoundedRectangle(&rr(r, 3.0, 3.0), br(), wd, None);
let dx = px(cx - 3.0) + h;
rt().DrawLine(pt(dx, r.top), pt(dx, r.bottom), br(), wd, None);
let step = (2.5 * s_).round().max(2.0) / s_;
for i in 0..3 {
let y = px(cy - 3.5) + i as f32 * step + ht;
rt().DrawLine(pt(px(cx - 7.25), y), pt(px(cx - 4.75), y), br(), wt, None);
}
}
}
pub fn icon_plus(c: Ponto, cor: Cor, s_: f32) {
unsafe {
br().SetColor(&cor);
rt().DrawLine(pt(c.x - s_, c.y), pt(c.x + s_, c.y), br(), 1.6, None);
rt().DrawLine(pt(c.x, c.y - s_), pt(c.x, c.y + s_), br(), 1.6, None);
}
}
pub fn icon_search(c: Ponto, cor: Cor, s_: f32) {
unsafe {
br().SetColor(&cor);
rt().DrawEllipse(&ell(pt(c.x - 1.5 * s_, c.y - 1.5 * s_), 5.0 * s_, 5.0 * s_), br(), 1.5, None);
rt().DrawLine(pt(c.x + 2.2 * s_, c.y + 2.2 * s_), pt(c.x + 6.0 * s_, c.y + 6.0 * s_), br(), 1.6, None);
}
}
// ---- --foto
pub fn foto_path() -> Option<String> {
s().foto_path.get_or_insert_with(|| arg_valor("--foto")).clone()
}
pub fn modo_foto() -> bool {
foto_path().is_some()
}
fn wic() -> Option<IWICImagingFactory> {
unsafe { CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok() }
}
fn foto_target() {
let st = s();
if st.foto_rt.is_some() || foto_path().is_none() || st.wnd.0.is_null() {
return;
}
unsafe {
let mut r = RECT::default();
let _ = GetClientRect(st.wnd, &mut r);
if r.right <= 0 || r.bottom <= 0 {
return;
}
let dpi = GetDpiForWindow(st.wnd) as f32;
let Some(w_) = wic() else { return };
let Ok(bmp) = w_.CreateBitmap(r.right as u32, r.bottom as u32, &GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad) else { return };
let props = D2D1_RENDER_TARGET_PROPERTIES {
r#type: D2D1_RENDER_TARGET_TYPE_SOFTWARE,
pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED },
dpiX: dpi,
dpiY: dpi,
..Default::default()
};
if let Ok(frt) = d2d().CreateWicBitmapRenderTarget(&bmp, &props) {
st.foto_br = frt.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None).ok();
st.rt = Some(frt.clone());
st.br = st.foto_br.clone();
st.foto_rt = Some(frt);
st.foto_bmp = Some(bmp);
}
}
}
pub fn begin_paint() -> bool {
foto_target();
let st = s();
unsafe {
if let Some(f) = &st.foto_rt {
st.rt = Some(f.clone());
st.br = st.foto_br.clone();
f.BeginDraw();
st.bar_buttons.clear();
return true;
}
if st.hrt.is_none() {
let mut r = RECT::default();
let _ = GetClientRect(st.wnd, &mut r);
let dpi = GetDpiForWindow(st.wnd) as f32;
let props = D2D1_RENDER_TARGET_PROPERTIES { dpiX: dpi, dpiY: dpi, ..Default::default() };
let hp = D2D1_HWND_RENDER_TARGET_PROPERTIES {
hwnd: st.wnd,
pixelSize: D2D_SIZE_U { width: r.right.max(1) as u32, height: r.bottom.max(1) as u32 },
presentOptions: D2D1_PRESENT_OPTIONS_NONE,
};
if let Ok(h) = d2d().CreateHwndRenderTarget(&props, &hp) {
st.hbr = h.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 1.0), None).ok();
st.hrt = Some(h);
}
}
let Some(h) = &st.hrt else { return false };
st.rt = Some(h.cast().unwrap());
st.br = st.hbr.clone();
h.BeginDraw();
st.bar_buttons.clear();
true
}
}
pub fn end_paint() {
let st = s();
unsafe {
let Some(r) = &st.rt else { return };
let res = r.EndDraw(None, None);
let eh_janela = st.foto_rt.is_none();
if let Err(e) = res {
if e.code() == D2DERR_RECREATE_TARGET && eh_janela {
st.hbr = None;
st.hrt = None;
st.rt = None;
st.br = None;
let _ = InvalidateRect(st.wnd, None, FALSE);
}
}
}
}
pub fn on_size(l: LPARAM) {
unsafe {
if let Some(h) = &s().hrt {
let _ = h.Resize(&D2D_SIZE_U { width: loword(l.0 as usize), height: hiword(l.0 as usize) });
}
let _ = InvalidateRect(wnd(), None, FALSE);
}
}
pub fn on_dpi(w_: WPARAM, l: LPARAM) {
unsafe {
let r = &*(l.0 as *const RECT);
let _ = SetWindowPos(wnd(), None, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_NOACTIVATE);
if let Some(h) = &s().hrt {
let d = hiword(w_.0) as f32;
h.SetDpi(d, d);
}
}
}
pub fn salvar_png(bmp: &IWICBitmap, caminho: &str) -> windows::core::Result<()> {
unsafe {
let w_ = wic().ok_or_else(|| Error::from(E_FAIL))?;
let (mut wd, mut ht) = (0u32, 0u32);
bmp.GetSize(&mut wd, &mut ht)?;
let st = w_.CreateStream()?;
let p = wz(caminho);
st.InitializeFromFilename(pc(&p), GENERIC_WRITE.0)?;
let enc = w_.CreateEncoder(&GUID_ContainerFormatPng, std::ptr::null())?;
enc.Initialize(&st, WICBitmapEncoderNoCache)?;
let mut fr: Option<IWICBitmapFrameEncode> = None;
enc.CreateNewFrame(&mut fr, std::ptr::null_mut())?;
let fr = fr.ok_or_else(|| Error::from(E_FAIL))?;
fr.Initialize(None)?;
fr.SetSize(wd, ht)?;
let mut f = GUID_WICPixelFormat32bppPBGRA;
fr.SetPixelFormat(&mut f)?;
fr.WriteSource(bmp, std::ptr::null())?;
fr.Commit()?;
enc.Commit()?;
Ok(())
}
}
extern "system" fn foto_pre(_: HWND, _: u32, id: usize, _: u32) {
unsafe {
let _ = KillTimer(None, id);
SendMessageW(wnd(), WM_PAINT, WPARAM(0), LPARAM(0));
}
}
extern "system" fn foto_tick(_: HWND, _: u32, id: usize, _: u32) {
unsafe {
let _ = KillTimer(None, id);
foto_target();
let path = foto_path().unwrap_or_default();
if s().foto_rt.is_some() {
SendMessageW(wnd(), WM_PAINT, WPARAM(0), LPARAM(0));
if let Some(b) = s().foto_bmp.clone() {
match salvar_png(&b, &path) {
Ok(()) => println!("foto: {path}"),
Err(e) => eprintln!("foto falhou: {e}"),
}
}
}
let _ = DestroyWindow(wnd());
}
}
pub fn size() -> D2D_SIZE_F {
let mut r = RECT::default();
unsafe {
let _ = GetClientRect(wnd(), &mut r);
}
let s_ = sc();
D2D_SIZE_F { width: r.right as f32 / s_, height: r.bottom as f32 / s_ }
}
// ---- campo de edição (EDIT do Windows por cima do desenho)
fn field_end(key: i32) {
let f = &mut s().field;
if f.h.0.is_null() || f.ending {
return;
}
f.ending = true;
unsafe {
let n = GetWindowTextLengthW(f.h);
let mut b = vec![0u16; n as usize + 1];
GetWindowTextW(f.h, &mut b);
let t = from_w(&b);
let h = f.h;
f.h = HWND(std::ptr::null_mut());
let done = f.done.take();
let _ = DestroyWindow(h);
s().field.ending = false;
if let Some(mut d) = done {
d(t, key);
}
let _ = InvalidateRect(wnd(), None, FALSE);
}
}
pub fn field_close() {
field_end(0);
}
extern "system" fn field_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
unsafe {
if m == WM_GETDLGCODE {
return LRESULT(DLGC_WANTALLKEYS as isize);
}
if m == WM_KEYDOWN && (w_.0 == 0x0D || w_.0 == 0x1B || w_.0 == 0x09) {
field_end(w_.0 as i32);
return LRESULT(0);
}
if m == WM_CHAR && (w_.0 == 13 || w_.0 == 27 || w_.0 == 9) {
return LRESULT(0);
}
if m == WM_KILLFOCUS {
let _ = PostMessageW(wnd(), WM_APP + 77, WPARAM(0), LPARAM(0));
}
let old: WNDPROC = std::mem::transmute(s().field.old);
CallWindowProcW(old, h, m, w_, l)
}
}
/// r em DIP; size em pt. O app deve tratar WM_APP + 77 chamando field_close() (perdeu o foco).
pub fn field_open(r: RectF, texto: &str, size: f32, bold: bool, done: impl FnMut(String, i32) + 'static) {
field_end(0);
let s_ = sc();
unsafe {
let f = &mut s().field;
if !f.font.0.is_null() {
let _ = DeleteObject(f.font);
}
let fam = wz(&family());
f.font = CreateFontW(
-((size * s_).round() as i32),
0,
0,
0,
if bold { 600 } else { 400 },
0,
0,
0,
DEFAULT_CHARSET.0 as u32,
0,
0,
CLEARTYPE_QUALITY.0 as u32,
0,
pc(&fam),
);
let hgt = (size * s_ * 1.45).round() as i32;
let y = ((r.top + r.bottom) / 2.0 * s_).round() as i32 - hgt / 2;
let t = wz(texto);
let inst = GetModuleHandleW(None).unwrap_or_default();
let Ok(h) = CreateWindowExW(
WINDOW_EX_STYLE(0),
w!("EDIT"),
pc(&t),
WS_CHILD | WS_VISIBLE | WINDOW_STYLE(ES_AUTOHSCROLL as u32),
(r.left * s_).round() as i32,
y,
((r.right - r.left) * s_).round() as i32,
hgt,
wnd(),
None,
inst,
None,
) else {
return;
};
f.h = h;
f.done = Some(Box::new(done));
SendMessageW(h, WM_SETFONT, WPARAM(f.font.0 as usize), LPARAM(1));
f.old = crate::util::set_wlp(h, GWLP_WNDPROC, field_proc as *const () as isize);
SendMessageW(h, 0x00B1 /* EM_SETSEL */, WPARAM(0), LPARAM(-1));
let _ = windows::Win32::UI::Input::KeyboardAndMouse::SetFocus(h);
}
}
/// WM_CTLCOLOREDIT: fundo do app e texto do tema
pub fn field_colors(dc: HDC, bg: COLORREF) -> LRESULT {
unsafe {
let d = dark();
SetTextColor(dc, if d { COLORREF(0x00F0F0F0) } else { COLORREF(0x00141414) });
SetBkColor(dc, bg);
if !s().field_brush.0.is_null() {
let _ = DeleteObject(s().field_brush);
}
s().field_brush = CreateSolidBrush(bg);
LRESULT(s().field_brush.0 as isize)
}
}
/// COLORREF a partir de r, g, b
pub fn colorref(r: u8, g: u8, b: u8) -> COLORREF {
COLORREF(r as u32 | (g as u32) << 8 | (b as u32) << 16)
}
// ---- dados em %APPDATA%\Shell
pub fn read_lines(path: &std::path::Path) -> Vec<String> {
match std::fs::read(path) {
Ok(b) => {
let t = String::from_utf8_lossy(&b);
let t = t.strip_prefix('\u{feff}').unwrap_or(&t);
t.lines().map(|l| l.trim_end_matches('\r').to_string()).collect()
}
Err(_) => Vec::new(),
}
}
pub fn write_lines(path: &std::path::Path, lines: &[String]) -> bool {
let mut tmp = path.as_os_str().to_owned();
tmp.push(".tmp");
let mut s_ = String::from('\u{feff}');
for l in lines {
s_.push_str(l);
s_.push('\n');
}
std::fs::write(&tmp, s_).is_ok() && std::fs::rename(&tmp, path).is_ok()
}
pub fn esc(s_: &str) -> String {
let mut o = String::with_capacity(s_.len());
for c in s_.chars() {
match c {
'\\' => o.push_str("\\\\"),
'\t' => o.push_str("\\t"),
'\n' => o.push_str("\\n"),
'\r' => {}
c => o.push(c),
}
}
o
}
pub fn unesc(s_: &str) -> String {
let mut o = String::with_capacity(s_.len());
let mut it = s_.chars().peekable();
while let Some(c) = it.next() {
if c == '\\' {
if let Some(n) = it.next() {
o.push(match n {
't' => '\t',
'n' => '\n',
x => x,
});
continue;
}
}
o.push(c);
}
o
}
pub fn split(s_: &str) -> Vec<String> {
s_.split('\t').map(str::to_string).collect()
}
// ---- datas: minutos desde 1970 (hora local)
const UNIX_EM_FT: i64 = 116444736000000000; // 1970-01-01 em FILETIME (100 ns)
pub fn now_min() -> i64 {
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64 / 60).unwrap_or(0)
}
pub fn to_min(st: &SYSTEMTIME) -> i64 {
unsafe {
let mut l = *st;
l.wSecond = 0;
l.wMilliseconds = 0;
let mut utc = SYSTEMTIME::default();
if TzSpecificLocalTimeToSystemTime(None, &l, &mut utc).is_err() {
return 0;
}
let mut ft = FILETIME::default();
if SystemTimeToFileTime(&utc, &mut ft).is_err() {
return 0;
}
let v = ((ft.dwHighDateTime as i64) << 32) | ft.dwLowDateTime as i64;
(v - UNIX_EM_FT) / 10_000_000 / 60
}
}
pub fn from_min(m: i64) -> SYSTEMTIME {
unsafe {
let v = m * 60 * 10_000_000 + UNIX_EM_FT;
let ft = FILETIME { dwLowDateTime: v as u32, dwHighDateTime: (v >> 32) as u32 };
let mut utc = SYSTEMTIME::default();
let _ = FileTimeToSystemTime(&ft, &mut utc);
let mut l = SYSTEMTIME::default();
let _ = SystemTimeToTzSpecificLocalTime(None, &utc, &mut l);
l
}
}
pub fn day_start(m: i64) -> i64 {
let mut s_ = from_min(m);
s_.wHour = 0;
s_.wMinute = 0;
to_min(&s_)
}
pub fn local_now() -> SYSTEMTIME {
unsafe { GetLocalTime() }
}
pub fn month_name(m: i32) -> String {
const PT: [&str; 12] = ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"];
const EN: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let i = ((m - 1).rem_euclid(12)) as usize;
if idioma::pt() {
return PT[i].into();
}
if idioma::en() {
return EN[i].into();
}
idioma::cap(&idioma::month_name(m, false))
}
pub fn weekday_short(d: i32) -> String {
const PT: [&str; 7] = ["dom.", "seg.", "ter.", "qua.", "qui.", "sex.", "sáb."];
const EN: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
let i = d.rem_euclid(7) as usize;
if idioma::pt() {
return PT[i].into();
}
if idioma::en() {
return EN[i].into();
}
idioma::day_name(d, 1)
}
/// "Hoje, 14:30" / "Amanhã" / "12/11/2026, 09:00"
pub fn due_text(m: i64, with_time: bool) -> String {
if m == 0 {
return String::new();
}
let today = day_start(now_min());
let day = day_start(m);
let s_ = from_min(m);
let mut d = if day == today {
tr("Hoje")
} else if day == today + 24 * 60 {
tr("Amanhã")
} else if day == today - 24 * 60 {
tr("Ontem")
} else if idioma::pt() {
format!("{:02}/{:02}/{:04}", s_.wDay, s_.wMonth, s_.wYear)
} else {
let loc = wz(idioma::locale());
let mut b = [0u16; 64];
unsafe {
windows::Win32::Globalization::GetDateFormatEx(pc(&loc), windows::Win32::Globalization::DATE_SHORTDATE, Some(&s_), PCWSTR::null(), Some(&mut b), None);
}
from_w(&b)
};
if with_time {
d.push_str(&format!(", {:02}:{:02}", s_.wHour, s_.wMinute));
}
d
}
// ---- lugar e tamanho da janela lembrados (janela-<classe>.txt)
fn lembrar_arquivo(h: HWND) -> std::path::PathBuf {
let mut c = [0u16; 64];
let n = unsafe { GetClassNameW(h, &mut c) } as usize;
data_path(&format!("janela-{}.txt", String::from_utf16_lossy(&c[..n])))
}
extern "system" fn lembrar_sub(h: HWND, m: u32, w_: WPARAM, l: LPARAM, id: usize, max_pend: usize) -> LRESULT {
unsafe {
if m == WM_SHOWWINDOW && w_.0 != 0 && max_pend != 0 {
let _ = SetWindowSubclass(h, Some(lembrar_sub), id, 0);
let _ = PostMessageW(h, WM_SYSCOMMAND, WPARAM(SC_MAXIMIZE as usize), LPARAM(0));
}
// no modo --foto não grava a posição (a janela nem apareceu)
if m == WM_DESTROY && !modo_foto() {
let mut wp = WINDOWPLACEMENT { length: std::mem::size_of::<WINDOWPLACEMENT>() as u32, ..Default::default() };
if GetWindowPlacement(h, &mut wp).is_ok() {
let r = wp.rcNormalPosition;
let maxed = wp.showCmd == SW_SHOWMAXIMIZED.0 as u32 || (wp.showCmd == SW_SHOWMINIMIZED.0 as u32 && (wp.flags & WPF_RESTORETOMAXIMIZED).0 != 0);
if r.right - r.left >= 200 && r.bottom - r.top >= 120 {
write_lines(&lembrar_arquivo(h), &[format!("{} {} {} {} {}", r.left, r.top, r.right, r.bottom, if maxed { 1 } else { 0 })]);
}
}
let _ = RemoveWindowSubclass(h, Some(lembrar_sub), id);
}
DefSubclassProc(h, m, w_, l)
}
}
pub fn lembrar(h: HWND) {
let mut maxed = false;
let v = read_lines(&lembrar_arquivo(h));
if let Some(l) = v.first() {
let n: Vec<i32> = l.split_whitespace().filter_map(|x| x.parse().ok()).collect();
if n.len() == 5 && n[2] - n[0] >= 200 && n[3] - n[1] >= 120 {
let r = RECT { left: n[0], top: n[1], right: n[2], bottom: n[3] };
unsafe {
let mut wp = WINDOWPLACEMENT { length: std::mem::size_of::<WINDOWPLACEMENT>() as u32, ..Default::default() };
let _ = GetWindowPlacement(h, &mut wp);
wp.rcNormalPosition = r;
wp.showCmd = SW_HIDE.0 as u32;
wp.flags = WINDOWPLACEMENT_FLAGS(0);
let meio = POINT { x: (r.left + r.right) / 2, y: r.top + 20 };
if !MonitorFromPoint(meio, MONITOR_DEFAULTTONULL).0.is_null() {
let _ = SetWindowPlacement(h, &wp);
maxed = n[4] != 0;
}
}
}
}
unsafe {
let _ = SetWindowSubclass(h, Some(lembrar_sub), 0x4C4D, if maxed { 1 } else { 0 });
}
}
pub type Proc = extern "system" fn(HWND, u32, WPARAM, LPARAM) -> LRESULT;
/// Registra a classe e cria a janela principal no meio do monitor do ponteiro
pub fn create_main(cls: &str, titulo: &str, proc_: Proc, w_: i32, h: i32) -> Option<HWND> {
unsafe {
let inst: HINSTANCE = GetModuleHandleW(None).ok()?.into();
let c = wz(cls);
let t = wz(titulo);
let wc = WNDCLASSEXW {
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
style: CS_DBLCLKS,
lpfnWndProc: Some(std::mem::transmute::<Proc, unsafe extern "system" fn(HWND, u32, WPARAM, LPARAM) -> LRESULT>(proc_)),
hInstance: inst,
lpszClassName: pc(&c),
hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(),
hIcon: LoadIconW(inst, PCWSTR(1 as *const u16)).unwrap_or_default(),
..Default::default()
};
RegisterClassExW(&wc);
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
let mut cpos = POINT::default();
let _ = GetCursorPos(&mut cpos);
let _ = GetMonitorInfoW(MonitorFromPoint(cpos, MONITOR_DEFAULTTOPRIMARY), &mut mi);
let k = GetDpiForSystem() as f32 / 96.0;
let (ww, hh) = ((w_ as f32 * k) as i32, (h as f32 * k) as i32);
let mac = !modo_foto() && barramac::ligar();
let hw = CreateWindowExW(
WINDOW_EX_STYLE(0),
pc(&c),
pc(&t),
WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
mi.rcWork.left + (mi.rcWork.right - mi.rcWork.left - ww) / 2,
mi.rcWork.top + (mi.rcWork.bottom - mi.rcWork.top - hh) / 2,
ww,
hh,
None,
None,
inst,
None,
)
.ok()?;
s().wnd = hw;
let d = BOOL::from(dark());
let _ = DwmSetWindowAttribute(hw, DWMWINDOWATTRIBUTE(20), &d as *const _ as *const c_void, 4);
if mac && semaforo::aqua() && s().bar_wanted > 0.0 {
s().bar = s().bar_wanted;
let p = wz("WacOSBarraUnificada");
let _ = SetPropW(hw, pc(&p), HANDLE(s().bar.round() as isize as *mut c_void));
let _ = SetWindowSubclass(hw, Some(unified_sub), 0x55A1, 0);
let _ = SetWindowPos(hw, None, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
// --foto: a janela fica escondida e sem a DLL; com o Golden Gate, a barra unificada vale igual (como a foto do C++)
if modo_foto() && semaforo::aqua() && s().bar_wanted > 0.0 {
s().bar = s().bar_wanted;
}
// no modo foto o tamanho é o de fábrica (não lê nem grava janela-*.txt)
if !modo_foto() {
lembrar(hw);
}
Some(hw)
}
}
/// ShowWindow, menos no modo --foto (a janela fica escondida: o desenho vai direto para o bitmap)
pub fn show(h: HWND, cmd: SHOW_WINDOW_CMD) {
if !modo_foto() {
unsafe {
let _ = ShowWindow(h, cmd);
}
}
}
// ---- barra lateral tingida pelo papel de parede
pub fn tint_on() -> bool {
crate::ajustes::ler_padrao().get("tingir_janelas").map(|v| v != "0").unwrap_or(true)
}
pub fn wallpaper_average() -> Option<(f32, f32, f32)> {
unsafe {
let mut wp = [0u16; 260];
if SystemParametersInfoW(SPI_GETDESKWALLPAPER, 260, Some(wp.as_mut_ptr() as *mut c_void), SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0)).is_err() || wp[0] == 0 {
return None;
}
let w_ = wic()?;
let dec = w_.CreateDecoderFromFilename(PCWSTR(wp.as_ptr()), None, GENERIC_READ, WICDecodeMetadataCacheOnDemand).ok()?;
let fr = dec.GetFrame(0).ok()?;
let scl = w_.CreateBitmapScaler().ok()?;
scl.Initialize(&fr, 24, 24, WICBitmapInterpolationModeFant).ok()?;
let cv = w_.CreateFormatConverter().ok()?;
cv.Initialize(&scl, &GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
let mut px = vec![0u8; 24 * 24 * 4];
cv.CopyPixels(std::ptr::null(), 24 * 4, &mut px).ok()?;
let (mut r, mut g, mut b) = (0f64, 0f64, 0f64);
for c in px.chunks(4) {
b += c[0] as f64;
g += c[1] as f64;
r += c[2] as f64;
}
let n = 24.0 * 24.0 * 255.0;
Some(((r / n) as f32, (g / n) as f32, (b / n) as f32))
}
}
pub fn tinted(base: Cor) -> Cor {
let st = s().tint.get_or_insert_with(|| {
if !tint_on() {
return None;
}
let (r, g, b) = wallpaper_average()?;
let lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
let lim = |v: f32| v.clamp(-0.3, 0.3);
Some((lim(r - lum), lim(g - lum), lim(b - lum)))
});
let Some((dr, dg, db)) = *st else { return base };
let k = if dark() { 0.11 } else { 0.09 };
let cl = |v: f32| v.clamp(0.0, 1.0);
col(cl(base.r + dr * k), cl(base.g + dg * k), cl(base.b + db * k), base.a)
}
pub fn sidebar_color() -> Cor {
if semaforo::aqua() {
return if dark() { rgb(43, 41, 40, 1.0) } else { rgb(237, 237, 236, 1.0) };
}
tinted(if dark() { rgb(40, 40, 42, 1.0) } else { rgb(242, 242, 245, 1.0) })
}
/// Grava um ajuste (pelo Shell, se estiver aberto; senão direto no arquivo)
pub fn set_app_setting(key: &str, v: &str) {
unsafe {
let sh = FindWindowExW(HWND_MESSAGE, None, w!("ShellMensagens"), PCWSTR::null()).ok().filter(|h| !h.0.is_null()).or_else(|| find_window("ShellMensagens"));
let kv = format!("{key}={v}");
if let Some(sh) = sh {
let t = wz(&kv);
let cd = COPYDATASTRUCT { dwData: 0x534A5354, cbData: (t.len() * 2) as u32, lpData: t.as_ptr() as *mut c_void };
let mut r = 0usize;
if SendMessageTimeoutW(sh, WM_COPYDATA, WPARAM(wnd().0 as usize), LPARAM(&cd as *const _ as isize), SMTO_ABORTIFHUNG, 500, Some(&mut r)).0 != 0 && r != 0 {
return;
}
}
let path = data_path("ajustes.txt");
let want = format!("{key}=");
let mut lines = read_lines(&path);
let mut done = false;
for l in lines.iter_mut() {
if l.starts_with(&want) {
*l = kv.clone();
done = true;
}
}
if !done {
lines.push(kv);
}
write_lines(&path, &lines);
if let Some(sh) = sh {
let _ = PostMessageW(sh, reg_msg("ShellAjustesMudaram"), WPARAM(0), LPARAM(0));
}
}
}
/// Laço de mensagens (no modo --foto: desenha depois de 1,8 s, salva e fecha)
pub fn run() -> i32 {
unsafe {
if modo_foto() && !wnd().0.is_null() {
let espera = arg_valor("--foto-espera").and_then(|v| v.parse().ok()).unwrap_or(1800);
SetTimer(None, 0, espera, Some(foto_tick));
// um desenho antes da foto: o app pede o que for carregar (miniaturas, capas) e elas chegam a tempo
SetTimer(None, 0, 300, Some(foto_pre));
}
let mut m = MSG::default();
while GetMessageW(&mut m, None, 0, 0).as_bool() {
let _ = TranslateMessage(&m);
DispatchMessageW(&m);
}
}
0
}
/// Carrega um PNG como bitmap do Direct2D no rt atual
pub fn load_bitmap(caminho: &std::path::Path) -> Option<ID2D1Bitmap> {
unsafe {
let w_ = wic()?;
let p = wz(&caminho.to_string_lossy());
let dec = w_.CreateDecoderFromFilename(pc(&p), None, GENERIC_READ, WICDecodeMetadataCacheOnDemand).ok()?;
let fr = dec.GetFrame(0).ok()?;
let cv = w_.CreateFormatConverter().ok()?;
cv.Initialize(&fr, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
rt().CreateBitmapFromWicBitmap(&cv, None).ok()
}
}
/// O tratamento comum das mensagens (WM_PAINT chama `paint`)
pub fn wm_paint(h: HWND, paint: impl FnOnce()) -> LRESULT {
unsafe {
let mut ps = PAINTSTRUCT::default();
BeginPaint(h, &mut ps);
paint();
let _ = EndPaint(h, &ps);
}
LRESULT(0)
}
pub fn invalidate() {
unsafe {
let _ = InvalidateRect(wnd(), None, FALSE);
// --foto: a janela está escondida e não recebe WM_PAINT sozinha; o desenho vai para o bitmap mesmo assim
if modo_foto() && !wnd().0.is_null() {
let _ = PostMessageW(wnd(), WM_PAINT, WPARAM(0), LPARAM(0));
}
}
}
/// IFileOpenDialog / IFileSaveDialog com um filtro. None = cancelou.
pub fn pick_file(save: bool, filtros: &[(&str, &str)], ext: Option<&str>, nome: Option<&str>) -> Option<String> {
unsafe {
let d: IFileDialog = if save {
CoCreateInstance::<_, IFileSaveDialog>(&FileSaveDialog, None, CLSCTX_INPROC_SERVER).ok()?.cast().ok()?
} else {
CoCreateInstance::<_, IFileOpenDialog>(&FileOpenDialog, None, CLSCTX_INPROC_SERVER).ok()?.cast().ok()?
};
let textos: Vec<(Vec<u16>, Vec<u16>)> = filtros.iter().map(|(a, b)| (wz(a), wz(b))).collect();
let specs: Vec<windows::Win32::UI::Shell::Common::COMDLG_FILTERSPEC> = textos.iter().map(|(a, b)| windows::Win32::UI::Shell::Common::COMDLG_FILTERSPEC { pszName: pc(a), pszSpec: pc(b) }).collect();
if !specs.is_empty() {
let _ = d.SetFileTypes(&specs);
}
if let Some(e) = ext {
let e = wz(e);
let _ = d.SetDefaultExtension(pc(&e));
}
if let Some(n) = nome {
let n = wz(n);
let _ = d.SetFileName(pc(&n));
}
d.Show(wnd()).ok()?;
let it = d.GetResult().ok()?;
let p = it.GetDisplayName(SIGDN_FILESYSPATH).ok()?;
let s_ = from_pcwstr(PCWSTR(p.0));
CoTaskMemFree(Some(p.0 as *const c_void));
Some(s_)
}
}
/// MessageBoxW; devolve o botão (IDOK, IDCANCEL...)
pub fn message_box(texto: &str, titulo: &str, estilo: MESSAGEBOX_STYLE) -> MESSAGEBOX_RESULT {
let t = wz(texto);
let c = wz(titulo);
unsafe { MessageBoxW(wnd(), pc(&t), pc(&c), estilo) }
}
/// AppendMenuW com texto
pub fn append_menu(m: HMENU, flags: MENU_ITEM_FLAGS, id: usize, texto: &str) {
let t = wz(texto);
unsafe {
let _ = AppendMenuW(m, flags, id, pc(&t));
}
}
/// tecla apertada agora (GetKeyState < 0)
pub fn key_down(vk: u16) -> bool {
unsafe { windows::Win32::UI::Input::KeyboardAndMouse::GetKeyState(vk as i32) < 0 }
}
/// ponto do cliente para a tela
pub fn to_screen(h: HWND, x: i32, y: i32) -> POINT {
let mut p = POINT { x, y };
unsafe {
let _ = ClientToScreen(h, &mut p);
}
p
}
pub fn push_clip(r: RectF) {
unsafe { rt().PushAxisAlignedClip(&r, D2D1_ANTIALIAS_MODE_ALIASED) }
}
pub fn pop_clip() {
unsafe { rt().PopAxisAlignedClip() }
}
/// DrawText com opções próprias (sem o CLIP padrão, ou num formato com quebra de linha)
pub fn text_opt(t: &str, f: &IDWriteTextFormat, r: RectF, c: Cor, op: D2D1_DRAW_TEXT_OPTIONS) {
if t.is_empty() {
return;
}
unsafe {
br().SetColor(&c);
rt().DrawText(&w(t), f, &r, br(), op, DWRITE_MEASURING_MODE_NATURAL);
}
}
pub fn clear(c: Cor) {
unsafe { rt().Clear(Some(&c)) }
}
pub fn post(h: HWND, m: u32, w_: usize, l: isize) {
unsafe {
let _ = PostMessageW(h, m, WPARAM(w_), LPARAM(l));
}
}
pub fn wheel_delta(w_: WPARAM) -> f32 {
((w_.0 >> 16) & 0xFFFF) as u16 as i16 as f32
}
pub fn screen_to_client(h: HWND, l: LPARAM) -> POINT {
let mut p = POINT { x: get_x_lparam(l), y: get_y_lparam(l) };
unsafe {
let _ = ScreenToClient(h, &mut p);
}
p
}
/// O ícone do arquivo (SHGetFileInfo, grande ou pequeno) como bitmap do Direct2D no rt atual
pub fn icon_bitmap(path: &str, grande: bool) -> Option<ID2D1Bitmap> {
unsafe {
let p = wz(path);
let mut fi = SHFILEINFOW::default();
let fl = SHGFI_ICON | if grande { SHGFI_LARGEICON } else { SHGFI_SMALLICON };
if SHGetFileInfoW(pc(&p), FILE_FLAGS_AND_ATTRIBUTES(0), Some(&mut fi), std::mem::size_of::<SHFILEINFOW>() as u32, fl) == 0 || fi.hIcon.0.is_null() {
return None;
}
let r = icon_to_bitmap(fi.hIcon);
let _ = DestroyIcon(fi.hIcon);
r
}
}
/// HICON -> bitmap do Direct2D (pelo WIC, com o alfa certo)
pub fn icon_to_bitmap(ic: HICON) -> Option<ID2D1Bitmap> {
unsafe {
let w_ = wic()?;
let wb = w_.CreateBitmapFromHICON(ic).ok()?;
let cv = w_.CreateFormatConverter().ok()?;
cv.Initialize(&wb, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
rt().CreateBitmapFromWicBitmap(&cv, None).ok()
}
}
/// Para apps com laço de mensagens próprio: no modo --foto, marca a foto (como o run() faz)
pub fn foto_timer(ms: u32) {
if modo_foto() && !wnd().0.is_null() {
unsafe {
SetTimer(None, 0, ms, Some(foto_tick));
}
}
}