A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! Prévia das janelas no Dock (issue #467): com o ponteiro parado ~0,6 s sobre um app aberto, um painel acima do
//! ícone (ao lado, com o Dock na esquerda ou na direita) mostra as janelas dele como miniaturas vivas do DWM, com o
//! título embaixo. Clicar numa miniatura traz aquela janela (a minimizada volta). Passar para outro app troca o painel
//! na hora; sair do Dock e do painel fecha. Ajuste `dock_previa` (padrão desligado, Ajustes > Mesa e Dock).
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::Common::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::System::LibraryLoader::GetModuleHandleW;
use comum::windows::Win32::UI::Controls::MARGINS;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::{TrackMouseEvent, TME_LEAVE, TRACKMOUSEEVENT};
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;
use crate::{log, shell, ui};
const T_ABRE: usize = 1;
const T_FECHA: usize = 2;
/// aberta: confere a cada 250 ms se o ponteiro ainda está nela ou no Dock (o aviso de saída do Dock nem sempre chega
/// e a miniatura ficava na tela com o ponteiro longe, vídeo de usuário de 02/12)
const T_VIGIA: usize = 3;
/// aparecer e sumir em ~170 ms (opacidade da janela em camadas e das miniaturas; entra subindo 6 pt, como no Mac)
const T_FADE: usize = 4;
const FADE_MS: f32 = 170.0;
const MAX_JANELAS: usize = 8;
#[derive(Default)]
struct S {
wnd: HWND,
rt: Option<ID2D1HwndRenderTarget>,
tf: Option<IDWriteTextFormat>,
/// o que está aberto: (janela, título)
wins: Vec<(HWND, String)>,
thumbs: Vec<isize>,
/// as caixas das miniaturas (px da janela) e a faixa do título embaixo de cada uma
cells: Vec<RECT>,
titulo_h: i32,
hover: i32,
/// o pedido do Dock ainda não mostrado
quer: Vec<(HWND, String)>,
anchor: POINT,
pos: i32,
sc: f32,
/// tamanho da janela aberta (px), para seguir o ícone sem remontar
tam: (i32, i32),
/// opacidade agora (0..1), a de partida, o alvo e quando a animação começou
alfa: f32,
alfa0: f32,
alvo: f32,
fade_t0: u64,
aberto: bool,
rastreando: bool,
}
static G: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
G.get().get_or_insert_with(S::default)
}
/// issue #548: quanto o ponteiro fica parado antes de abrir (ms; antes 600 fixo) e o tamanho das miniaturas
fn atraso() -> u32 {
shell::setting("dock_previa_atraso", "250").parse::<u32>().unwrap_or(250).clamp(0, 2000)
}
fn tamanho() -> f32 {
match shell::setting("dock_previa_tamanho", "m").as_str() {
"p" => 0.6,
"g" => 1.0,
_ => 0.8,
}
}
/// a prévia está na tela (o Dock a faz acompanhar o ícone)
pub fn aberta() -> bool {
s().aberto
}
/// ligado nos Ajustes (Mesa e Dock > Prévia das janelas)
pub fn ligado() -> bool {
shell::setting("dock_previa", "0") == "1"
}
fn cria() -> bool {
let st = s();
if !st.wnd.0.is_null() {
return true;
}
unsafe {
let Ok(hi) = GetModuleHandleW(None) else { return false };
let cls = w!("WacOSDockPrevia");
RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi.into(), lpszClassName: cls, hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() });
st.wnd = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE | WS_EX_LAYERED, cls, w!(""), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
if st.wnd.0.is_null() {
return false;
}
crate::apps::ours().push(st.wnd);
// cantos redondos e o vidro do Windows atrás (o que não for pintado fica com o fundo desfocado)
let canto: u32 = 2;
let _ = DwmSetWindowAttribute(st.wnd, DWMWINDOWATTRIBUTE(33), &canto as *const _ as *const _, 4);
let m = MARGINS { cxLeftWidth: -1, cxRightWidth: -1, cyTopHeight: -1, cyBottomHeight: -1 };
let _ = DwmExtendFrameIntoClientArea(st.wnd, &m);
}
true
}
/// o Dock: o ponteiro está sobre um app com estas janelas (vazio = não está sobre um app aberto)
pub fn quer(wins: Vec<(HWND, String)>, anchor: POINT, pos: i32, sc: f32) {
let st = s();
if wins.is_empty() || !ligado() {
solta();
return;
}
if !cria() {
return;
}
unsafe {
let _ = KillTimer(st.wnd, T_FECHA);
}
let mesmo = st.aberto && st.wins.iter().map(|w| w.0).eq(wins.iter().map(|w| w.0));
if mesmo {
// a mesma prévia: só acompanha o ícone (a ampliação o move)
if st.anchor != anchor || st.pos != pos {
st.anchor = anchor;
st.pos = pos;
posiciona(true);
}
return;
}
// esperando para abrir com as mesmas janelas: só atualiza onde (sem reiniciar a espera)
if !st.aberto && !st.quer.is_empty() && st.quer.iter().map(|w| w.0).eq(wins.iter().take(MAX_JANELAS).map(|w| w.0)) {
st.anchor = anchor;
st.pos = pos;
return;
}
st.quer = wins.into_iter().take(MAX_JANELAS).collect();
st.anchor = anchor;
st.pos = pos;
st.sc = if sc > 0.0 { sc } else { 1.0 };
unsafe {
if st.aberto {
mostra(); // já aberto: o do vizinho na hora, como no Mac
} else {
SetTimer(st.wnd, T_ABRE, atraso(), None);
}
}
}
/// o ponteiro saiu do ícone: fecha logo, a não ser que tenha ido para o painel
pub fn solta() {
let st = s();
st.quer.clear();
if st.wnd.0.is_null() {
return;
}
unsafe {
let _ = KillTimer(st.wnd, T_ABRE);
if st.aberto {
SetTimer(st.wnd, T_FECHA, 350, None);
}
}
}
/// some num fade (a janela fica até a opacidade chegar a 0; aí esconde_ja)
pub fn esconde() {
let st = s();
if st.wnd.0.is_null() || !st.aberto || !unsafe { IsWindowVisible(st.wnd) }.as_bool() {
esconde_ja();
return;
}
st.quer.clear();
st.aberto = false;
st.hover = -1;
unsafe {
let _ = KillTimer(st.wnd, T_ABRE);
let _ = KillTimer(st.wnd, T_FECHA);
let _ = KillTimer(st.wnd, T_VIGIA);
}
fade_para(0.0);
}
fn agora_ms() -> u64 {
unsafe { comum::windows::Win32::System::SystemInformation::GetTickCount64() }
}
fn fade_para(alvo: f32) {
let st = s();
st.alfa0 = st.alfa;
st.alvo = alvo;
st.fade_t0 = agora_ms();
unsafe {
SetTimer(st.wnd, T_FADE, 15, None);
}
}
/// a opacidade na janela e nas miniaturas; entrando, sobe de 6 pt abaixo do lugar
fn aplica_alfa() {
let st = s();
let a = st.alfa.clamp(0.0, 1.0);
unsafe {
let _ = SetLayeredWindowAttributes(st.wnd, COLORREF(0), (a * 255.0).round() as u8, LWA_ALPHA);
for &t in &st.thumbs {
if t != 0 {
let p = DWM_THUMBNAIL_PROPERTIES { dwFlags: DWM_TNP_OPACITY, opacity: (a * 255.0).round() as u8, ..Default::default() };
let _ = DwmUpdateThumbnailProperties(t, &p);
}
}
}
if st.alvo > 0.5 {
posiciona(true);
}
}
/// clique no Dock, arrasto, menu: fecha já, sem fade
fn esconde_ja() {
let st = s();
st.quer.clear();
if st.wnd.0.is_null() {
return;
}
unsafe {
let _ = KillTimer(st.wnd, T_ABRE);
let _ = KillTimer(st.wnd, T_FECHA);
let _ = KillTimer(st.wnd, T_VIGIA);
let _ = KillTimer(st.wnd, T_FADE);
for &t in &st.thumbs {
let _ = DwmUnregisterThumbnail(t);
}
let _ = ShowWindow(st.wnd, SW_HIDE);
}
st.thumbs.clear();
st.wins.clear();
st.cells.clear();
st.aberto = false;
st.hover = -1;
st.rastreando = false;
st.alfa = 0.0;
st.alvo = 0.0;
unsafe {
let _ = KillTimer(st.wnd, T_FADE);
}
}
fn fonte() -> Option<IDWriteTextFormat> {
let st = s();
if st.tf.is_none() {
unsafe {
if let Ok(tf) = ui::dw().CreateTextFormat(&HSTRING::from(ui::family()), None, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 11.5, w!("")) {
let _ = tf.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
let _ = tf.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
let _ = tf.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
if let Ok(sinal) = ui::dw().CreateEllipsisTrimmingSign(&tf) {
let tr_ = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
let _ = tf.SetTrimming(&tr_, &sinal);
}
st.tf = Some(tf);
}
}
}
st.tf.clone()
}
/// acima do ícone (Dock embaixo), centrada nele como a etiqueta do Mac, ou ao lado (Dock na esquerda/direita); dentro
/// do monitor. `so_mover`: já aberta, só acompanha o ícone
fn posiciona(so_mover: bool) {
let st = s();
let (ww, hh) = st.tam;
if ww <= 0 || hh <= 0 || st.wnd.0.is_null() {
return;
}
let k = st.sc;
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
unsafe {
let _ = GetMonitorInfoW(MonitorFromPoint(st.anchor, MONITOR_DEFAULTTONEAREST), &mut mi);
}
let area = mi.rcMonitor;
let (mut x, mut y) = match st.pos {
1 => (st.anchor.x + (6.0 * k) as i32, st.anchor.y - hh / 2),
2 => (st.anchor.x - ww - (6.0 * k) as i32, st.anchor.y - hh / 2),
_ => (st.anchor.x - ww / 2, st.anchor.y - hh - (6.0 * k) as i32),
};
x = x.clamp(area.left + 4, (area.right - ww - 4).max(area.left));
y = y.clamp(area.top + 4, (area.bottom - hh - 4).max(area.top));
if st.pos == 0 && st.alvo > 0.5 {
y += ((1.0 - st.alfa.clamp(0.0, 1.0)) * 6.0 * k).round() as i32; // entra subindo
}
unsafe {
let _ = SetWindowPos(st.wnd, HWND_TOPMOST, x, y, ww, hh, SWP_NOACTIVATE | if so_mover { SWP_NOSIZE } else { SET_WINDOW_POS_FLAGS(0) });
}
}
fn mostra() {
let st = s();
if st.quer.is_empty() {
return;
}
let novas = std::mem::take(&mut st.quer);
unsafe {
for &t in &st.thumbs {
let _ = DwmUnregisterThumbnail(t);
}
st.thumbs.clear();
// tamanho de cada janela (a minimizada não tem miniatura: o retângulo da última posição)
let k = st.sc;
let f0 = tamanho();
let (mut bw, mut bh) = (220.0 * k * f0, 140.0 * k * f0);
let (pad, gap) = ((12.0 * k).round() as i32, (12.0 * k).round() as i32);
st.titulo_h = (22.0 * k).round() as i32;
let n = novas.len() as i32;
// cabe no monitor (sem passar da área de trabalho): as caixas encolhem
let mon = MonitorFromPoint(st.anchor, MONITOR_DEFAULTTONEAREST);
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
let _ = GetMonitorInfoW(mon, &mut mi);
let area = mi.rcMonitor;
let cabe = (area.right - area.left - 2 * pad - (n - 1) * gap - (40.0 * k) as i32) as f32;
if bw * n as f32 > cabe && cabe > 0.0 {
let f = cabe / (bw * n as f32);
bw *= f;
bh *= f;
}
let (bwi, bhi) = (bw.round() as i32, bh.round() as i32);
let ww = 2 * pad + n * bwi + (n - 1) * gap;
let hh = 2 * pad + bhi + st.titulo_h;
st.cells.clear();
for i in 0..n {
let x = pad + i * (bwi + gap);
st.cells.push(RECT { left: x, top: pad, right: x + bwi, bottom: pad + bhi });
}
st.tam = (ww, hh);
let escuro: u32 = ui::dark() as u32;
let _ = DwmSetWindowAttribute(st.wnd, DWMWINDOWATTRIBUTE(20), &escuro as *const _ as *const _, 4);
let vidro: u32 = 3; // acrílico (Windows 11 22H2+); antes disso o fundo pintado já basta
let _ = DwmSetWindowAttribute(st.wnd, DWMWINDOWATTRIBUTE(38), &vidro as *const _ as *const _, 4);
posiciona(false);
if let Some(rt) = &st.rt {
let _ = rt.Resize(&D2D_SIZE_U { width: ww as u32, height: hh as u32 });
}
for (i, (h, _)) in novas.iter().enumerate() {
let Ok(th) = DwmRegisterThumbnail(st.wnd, *h) else {
st.thumbs.push(0);
continue;
};
// a miniatura no meio da caixa, sem deformar
let src = DwmQueryThumbnailSourceSize(th).unwrap_or_default();
let c = st.cells[i];
let (cw, ch) = ((c.right - c.left) as f32, (c.bottom - c.top) as f32);
let f = if src.cx > 0 && src.cy > 0 { (cw / src.cx as f32).min(ch / src.cy as f32).min(1.0) } else { 1.0 };
let (tw, th_) = ((src.cx as f32 * f).round() as i32, (src.cy as f32 * f).round() as i32);
let dst = RECT { left: c.left + ((cw as i32 - tw) / 2), top: c.top + ((ch as i32 - th_) / 2), right: c.left + ((cw as i32 - tw) / 2) + tw, bottom: c.top + ((ch as i32 - th_) / 2) + th_ };
let p = DWM_THUMBNAIL_PROPERTIES { dwFlags: DWM_TNP_RECTDESTINATION | DWM_TNP_VISIBLE | DWM_TNP_SOURCECLIENTAREAONLY | DWM_TNP_OPACITY, rcDestination: dst, fVisible: TRUE, fSourceClientAreaOnly: FALSE, opacity: 255, ..Default::default() };
let _ = DwmUpdateThumbnailProperties(th, &p);
st.thumbs.push(th);
}
st.wins = novas;
st.hover = -1;
st.aberto = true;
SetTimer(st.wnd, T_VIGIA, 250, None);
// já na tela (outro ícone, ou sumindo): só muda e volta a 1, sem piscar; nova: entra do 0
let visivel = IsWindowVisible(st.wnd).as_bool() && st.alfa > 0.01;
if !visivel {
st.alfa = 0.0;
}
st.alvo = 1.0;
aplica_alfa();
let _ = ShowWindow(st.wnd, SW_SHOWNOACTIVATE);
if st.alfa < 0.999 {
fade_para(1.0);
}
let _ = InvalidateRect(st.wnd, None, FALSE);
}
log!("dock: prévia de {} janela(s)", st.wins.len());
}
fn pinta() {
let st = s();
unsafe {
let mut rc = RECT::default();
let _ = GetClientRect(st.wnd, &mut rc);
if st.rt.is_none() {
let props = D2D1_RENDER_TARGET_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: comum::windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 96.0, dpiY: 96.0, ..Default::default() };
let hp = D2D1_HWND_RENDER_TARGET_PROPERTIES { hwnd: st.wnd, pixelSize: D2D_SIZE_U { width: rc.right as u32, height: rc.bottom as u32 }, presentOptions: D2D1_PRESENT_OPTIONS_NONE };
st.rt = ui::d2d().CreateHwndRenderTarget(&props, &hp).ok();
}
let Some(rt) = st.rt.clone() else { return };
let escuro = ui::dark();
rt.BeginDraw();
rt.Clear(Some(&col(0.0, 0.0, 0.0, 0.0)));
if let Ok(b) = rt.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 0.0), None) {
let k = st.sc;
let (wf, hf) = (rc.right as f32, rc.bottom as f32);
// o fundo: translúcido por cima do vidro do Windows (sem o vidro, ainda dá para ler)
b.SetColor(&if escuro { col(0.12, 0.12, 0.13, 0.80) } else { col(0.96, 0.96, 0.97, 0.82) });
rt.FillRoundedRectangle(&rr(rf(0.0, 0.0, wf, hf), 12.0 * k, 12.0 * k), &b);
b.SetColor(&if escuro { col(1.0, 1.0, 1.0, 0.14) } else { col(0.0, 0.0, 0.0, 0.12) });
rt.DrawRoundedRectangle(&rr(rf(0.5, 0.5, wf - 0.5, hf - 0.5), 12.0 * k, 12.0 * k), &b, 1.0, None);
let tf = fonte();
for (i, c) in st.cells.iter().enumerate() {
let caixa = rf(c.left as f32, c.top as f32, c.right as f32, c.bottom as f32);
if i as i32 == st.hover {
b.SetColor(&if escuro { col(1.0, 1.0, 1.0, 0.16) } else { col(0.0, 0.0, 0.0, 0.08) });
let m = 5.0 * k;
rt.FillRoundedRectangle(&rr(rf(caixa.left - m, caixa.top - m, caixa.right + m, caixa.bottom + st.titulo_h as f32), 8.0 * k, 8.0 * k), &b);
}
// a minimizada (sem miniatura do DWM): um cartão com o título
if st.thumbs.get(i).copied().unwrap_or(0) == 0 || st.wins.get(i).map(|w| IsIconic(w.0).as_bool()).unwrap_or(false) {
b.SetColor(&if escuro { col(1.0, 1.0, 1.0, 0.08) } else { col(0.0, 0.0, 0.0, 0.05) });
rt.FillRoundedRectangle(&rr(caixa, 6.0 * k, 6.0 * k), &b);
}
if let (Some(tf), Some((_, titulo))) = (&tf, st.wins.get(i)) {
b.SetColor(&if escuro { col(1.0, 1.0, 1.0, 0.90) } else { col(0.0, 0.0, 0.0, 0.85) });
let t = rf(caixa.left, caixa.bottom + 2.0 * k, caixa.right, caixa.bottom + st.titulo_h as f32);
// o texto em DIP: o alvo está em 96 ppp, então a fonte cresce com a escala
rt.SetTransform(&comum::windows::Foundation::Numerics::Matrix3x2 { M11: k, M12: 0.0, M21: 0.0, M22: k, M31: 0.0, M32: 0.0 });
rt.DrawText(&w(titulo), tf, &rf(t.left / k, t.top / k, t.right / k, t.bottom / k), &b, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
rt.SetTransform(&comum::windows::Foundation::Numerics::Matrix3x2::identity());
}
}
}
if rt.EndDraw(None, None).is_err() {
st.rt = None;
}
}
}
fn hit(x: i32, y: i32) -> i32 {
let st = s();
for (i, c) in st.cells.iter().enumerate() {
if x >= c.left - 6 && x < c.right + 6 && y >= c.top - 6 && y < c.bottom + st.titulo_h {
return i as i32;
}
}
-1
}
fn ativa(i: usize) {
let Some((h, _)) = s().wins.get(i).cloned() else { return };
esconde();
unsafe {
if IsIconic(h).as_bool() {
let _ = ShowWindowAsync(h, SW_RESTORE);
}
}
shell::traz_pra_frente(h);
}
fn ponteiro_dentro() -> bool {
let st = s();
let mut c = POINT::default();
let mut r = RECT::default();
unsafe { GetCursorPos(&mut c).is_ok() && GetWindowRect(st.wnd, &mut r).is_ok() && IsWindowVisible(st.wnd).as_bool() && c.x >= r.left && c.x < r.right && c.y >= r.top && c.y < r.bottom }
}
unsafe extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
let st = s();
match m {
WM_MOUSEACTIVATE => return LRESULT(MA_NOACTIVATE as isize),
WM_TIMER => {
if w_.0 == T_ABRE {
let _ = KillTimer(h, T_ABRE);
mostra();
} else if w_.0 == T_FADE {
let u = ((agora_ms().saturating_sub(st.fade_t0)) as f32 / FADE_MS).min(1.0);
let e = 1.0 - (1.0 - u) * (1.0 - u); // desacelera no fim
st.alfa = st.alfa0 + (st.alvo - st.alfa0) * e;
aplica_alfa();
if u >= 1.0 {
let _ = KillTimer(h, T_FADE);
if st.alvo <= 0.0 {
esconde_ja();
}
}
} else if w_.0 == T_VIGIA {
let mut c = POINT::default();
let _ = GetCursorPos(&mut c);
let sob = WindowFromPoint(c);
let raiz = GetAncestor(sob, GA_ROOT);
let dock = crate::dock::hwnd();
if !ponteiro_dentro() && sob != dock && raiz != dock {
log!("dock: prévia fechada (o ponteiro saiu sem aviso)");
esconde();
}
} else if w_.0 == T_FECHA {
let _ = KillTimer(h, T_FECHA);
if ponteiro_dentro() {
SetTimer(h, T_FECHA, 350, None); // está no painel: confere de novo
} else {
esconde();
}
}
return LRESULT(0);
}
WM_MOUSEMOVE => {
let _ = KillTimer(h, T_FECHA);
if !st.rastreando {
let mut tme = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
let _ = TrackMouseEvent(&mut tme);
st.rastreando = true;
}
let i = hit((l.0 & 0xFFFF) as i16 as i32, ((l.0 >> 16) & 0xFFFF) as i16 as i32);
if i != st.hover {
st.hover = i;
let _ = InvalidateRect(h, None, FALSE);
}
return LRESULT(0);
}
0x02A3 /* WM_MOUSELEAVE */ => {
st.rastreando = false;
if st.hover >= 0 {
st.hover = -1;
let _ = InvalidateRect(h, None, FALSE);
}
SetTimer(h, T_FECHA, 350, None);
return LRESULT(0);
}
WM_LBUTTONUP => {
let i = hit((l.0 & 0xFFFF) as i16 as i32, ((l.0 >> 16) & 0xFFFF) as i16 as i32);
if i >= 0 {
ativa(i as usize);
}
return LRESULT(0);
}
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
BeginPaint(h, &mut ps);
pinta();
let _ = EndPaint(h, &ps);
return LRESULT(0);
}
WM_ERASEBKGND => return LRESULT(1),
_ => {}
}
DefWindowProcW(h, m, w_, l)
}