A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! limites.cpp: a barra de menus e o Dock são linhas que as janelas não cruzam (como no Mac): ao soltar uma janela, ou
//! quando uma janela nova aparece, o que passou da área de trabalho volta para dentro (deslizando, ~0,18 s; a janela
//! nova vai direto). Maximizadas que ignoram a área de trabalho (issue #24) voltam para ela, no máximo 3 vezes.
#![allow(dead_code)]
use std::collections::HashMap;
use std::sync::Mutex;
use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Dwm::*;
use comum::windows::Win32::Graphics::Gdi::{GetMonitorInfoW, GetWindowRgnBox, MonitorFromRect, MonitorFromWindow, MONITORINFO, MONITOR_DEFAULTTONEAREST};
use comum::windows::Win32::System::SystemInformation::GetTickCount;
use comum::windows::Win32::UI::Accessibility::*;
use comum::windows::Win32::UI::HiDpi::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;
use crate::palco;
use crate::{anim, apps, dock, log, principal, shell};
static SLIDING: Mutex<Vec<isize>> = Mutex::new(Vec::new());
struct S {
hook_move: HWINEVENTHOOK,
hook_show: HWINEVENTHOOK,
rechecks: Vec<(isize, u32)>,
timer: usize,
feitas: Vec<isize>,
antes: HashMap<isize, (RECT, i32, u32)>,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
SS.get().get_or_insert_with(|| S { hook_move: HWINEVENTHOOK::default(), hook_show: HWINEVENTHOOK::default(), rechecks: Vec::new(), timer: 0, feitas: Vec::new(), antes: HashMap::new() })
}
fn candidate(h: HWND) -> bool {
unsafe {
if !IsWindow(h).as_bool() || GetAncestor(h, GA_ROOT) != h || !IsWindowVisible(h).as_bool() || IsIconic(h).as_bool() || IsZoomed(h).as_bool() {
return false;
}
if crate::janelas::fora_de_tudo(h) {
return false; // pedido de 02/12/2026: o WacOS não toca nesses programas
}
let st = GetWindowLongW(h, GWL_STYLE) as u32;
let ex = GetWindowLongW(h, GWL_EXSTYLE) as u32;
if st & WS_CHILD.0 != 0 || ex & (WS_EX_TOOLWINDOW.0 | WS_EX_NOACTIVATE.0 | WS_EX_TOPMOST.0) != 0 {
return false;
}
if st & WS_CAPTION.0 == 0 && st & WS_THICKFRAME.0 == 0 {
return false; // popups sem moldura (menus, avisos, splash)
}
// o Organizador Visual a deixou fora da tela; ampliada pelo botão verde já ocupa a área certa
!shell::nossa(h) && !palco::estacionada(h) && GetPropW(h, w!("MacJanelaAmpliada")).is_invalid()
}
}
/// volta deslizando (ease-out, ~0,18 s), a cada quadro da tela (DwmFlush)
fn slide_thread(h: isize, from: RECT, to: RECT) {
let hw = HWND(h as *mut _);
let t0 = anim::now();
loop {
unsafe {
let _ = DwmFlush();
let u = ((anim::now() - t0) / 180.0).min(1.0);
let e = 1.0 - (1.0 - u).powi(3); // desacelera no fim
let lerp = |a: i32, b: i32| (a as f64 + (b - a) as f64 * e).round() as i32;
if !IsWindow(hw).as_bool() || IsZoomed(hw).as_bool() || IsIconic(hw).as_bool() {
break;
}
let (l, t, r, b) = (lerp(from.left, to.left), lerp(from.top, to.top), lerp(from.right, to.right), lerp(from.bottom, to.bottom));
let _ = SetWindowPos(hw, None, l, t, r - l, b - t, SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS);
if u >= 1.0 {
break;
}
}
}
SLIDING.lock().unwrap().retain(|x| *x != h);
}
/// o usuário está arrastando/redimensionando esta janela agora (aí ela pode passar do Dock até soltar)
fn in_move_size(h: HWND) -> bool {
unsafe {
let mut gi = GUITHREADINFO { cbSize: std::mem::size_of::<GUITHREADINFO>() as u32, ..Default::default() };
GetGUIThreadInfo(GetWindowThreadProcessId(h, None), &mut gi).is_ok() && gi.flags.0 & GUI_INMOVESIZE.0 != 0 && gi.hwndMoveSize == h
}
}
/// na_hora = janela que acabou de aparecer: vai direto para o lugar (issue #29)
fn clamp(h: HWND, na_hora: bool) {
if !candidate(h) || in_move_size(h) {
return;
}
unsafe {
let mut wr = RECT::default();
let _ = GetWindowRect(h, &mut wr);
let mut vis = RECT::default();
if DwmGetWindowAttribute(h, DWMWA_EXTENDED_FRAME_BOUNDS, &mut vis as *mut _ as *mut _, std::mem::size_of::<RECT>() as u32).is_err() {
vis = wr;
}
// fora da tela de propósito (o alerta do Mac esconde a caixa original em -32000)
if wr.left <= -30000 || wr.top <= -30000 {
return;
}
let mac = !GetPropW(h, w!("MacJanela")).is_invalid();
let mut bx = RECT::default();
if mac && GetWindowRgnBox(h, &mut bx).0 != 0 && bx.right > bx.left {
vis = RECT { left: wr.left + bx.left, top: wr.top + bx.top, right: wr.left + bx.right, bottom: wr.top + bx.bottom };
}
let hm = MonitorFromRect(&vis, MONITOR_DEFAULTTONEAREST);
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
if !GetMonitorInfoW(hm, &mut mi).as_bool() {
return;
}
let (wa, mon) = (principal::work_area_for(hm), mi.rcMonitor);
if vis.left <= mon.left && vis.top <= mon.top && vis.right >= mon.right && vis.bottom >= mon.bottom {
return; // tela cheia
}
if wa == mon {
return; // sem barra nem Dock reservando espaço
}
let (w_, hh) = (vis.right - vis.left, vis.bottom - vis.top);
if w_ < 120 || hh < 80 {
return;
}
let mut dy = 0;
let mut new_h = hh;
if vis.top < wa.top {
dy = wa.top - vis.top; // passou da barra de menus
} else if vis.bottom > wa.bottom {
dy = -(vis.bottom - wa.bottom).min(vis.top - wa.top); // passou do Dock: sobe o que der
}
let resizable = GetWindowLongW(h, GWL_STYLE) as u32 & WS_THICKFRAME.0 != 0 || mac;
if vis.top + dy + new_h > wa.bottom && resizable {
new_h = wa.bottom - (vis.top + dy);
}
// Dock à esquerda ou à direita: a mesma conta na horizontal, só do lado dele
let (mut dx, mut new_w) = (0, w_);
let pos = dock::posicao();
if pos != 0 && hm == dock::monitor_handle() {
if pos == 1 && vis.left < wa.left {
dx = wa.left - vis.left;
} else if pos == 2 && vis.right > wa.right {
dx = -(vis.right - wa.right).min((vis.left - wa.left).max(0));
}
if pos == 2 && vis.left + dx + new_w > wa.right && resizable {
new_w = 120.max(wa.right - (vis.left + dx));
}
}
if dy == 0 && new_h == hh && dx == 0 && new_w == w_ {
return;
}
{
let mut sl = SLIDING.lock().unwrap();
if sl.contains(&(h.0 as isize)) {
return; // já deslizando
}
sl.push(h.0 as isize);
}
let (bt, bb, bl, brr) = (vis.top - wr.top, wr.bottom - vis.bottom, vis.left - wr.left, wr.right - vis.right);
let to = RECT { left: wr.left + dx, top: wr.top + dy, right: wr.left + dx + new_w + bl + brr, bottom: wr.top + dy + new_h + bt + bb };
let msg_move = RegisterWindowMessageW(w!("MacJanelaMover"));
let mut ok = 0usize;
// a DLL das janelas só sabe deslizar na vertical: na horizontal a janela anda pela thread
if na_hora {
let _ = SetWindowPos(h, None, to.left, to.top, to.right - to.left, to.bottom - to.top, SWP_NOZORDER | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS);
SLIDING.lock().unwrap().retain(|x| *x != h.0 as isize);
} else if dx == 0 && new_w == w_ && mac && SendMessageTimeoutW(h, msg_move, WPARAM(dy as isize as usize), LPARAM((to.bottom - to.top) as isize), SMTO_ABORTIFHUNG, 300, Some(&mut ok)).0 != 0 && ok != 0 {
SLIDING.lock().unwrap().retain(|x| *x != h.0 as isize);
} else {
let hv = h.0 as isize;
std::thread::spawn(move || slide_thread(hv, wr, to));
}
log!("limites: {} voltando para a área{} (dx {dx}, dy {dy}, altura {hh} -> {new_h}, largura {w_} -> {new_w})", shell::class_name(h), if na_hora { " na hora" } else { "" });
}
}
unsafe extern "system" fn on_move_end(_: HWINEVENTHOOK, _: u32, h: HWND, obj: i32, child: i32, _: u32, _: u32) {
if obj == OBJID_WINDOW.0 && child == CHILDID_SELF as i32 {
clamp(h, false);
}
}
unsafe extern "system" fn enum_clamp(h: HWND, _: LPARAM) -> BOOL {
if candidate(h) {
clamp(h, false);
}
TRUE
}
/// confere de novo um pouco depois: apps como o Ableton aparecem pequenos e só depois crescem
unsafe extern "system" fn recheck_tick(_: HWND, _: u32, _: usize, _: u32) {
let st = s();
let now = GetTickCount();
let mut due = Vec::new();
st.rechecks.retain(|(h, at)| {
if now.wrapping_sub(*at) as i32 >= 0 {
due.push(*h);
false
} else {
true
}
});
if st.rechecks.is_empty() && st.timer != 0 {
let _ = KillTimer(None, st.timer);
st.timer = 0;
}
for h in due {
if h != 0 {
clamp(HWND(h as *mut _), false);
} else {
let _ = EnumWindows(Some(enum_clamp), LPARAM(0)); // todas
}
}
}
fn later(h: isize, delays: &[u32]) {
let st = s();
let now = unsafe { GetTickCount() };
for d in delays {
st.rechecks.push((h, now.wrapping_add(*d)));
}
if st.timer == 0 {
st.timer = unsafe { SetTimer(None, 0, 150, Some(recheck_tick)) };
}
}
unsafe extern "system" fn on_show(_: HWINEVENTHOOK, _: u32, h: HWND, obj: i32, child: i32, _: u32, _: u32) {
if obj != OBJID_WINDOW.0 || child != CHILDID_SELF as i32 || !candidate(h) {
return;
}
if !GetPropW(h, w!("ShellLimiteVisto")).is_invalid() {
return; // só na primeira vez (depois o usuário manda)
}
let _ = SetPropW(h, w!("ShellLimiteVisto"), HANDLE(1 as *mut _));
clamp(h, true);
later(h.0 as isize, &[600, 1800, 4500]);
}
unsafe extern "system" fn enum_inicio(h: HWND, _: LPARAM) -> BOOL {
if candidate(h) {
let _ = SetPropW(h, w!("ShellLimiteVisto"), HANDLE(1 as *mut _));
clamp(h, false);
}
TRUE
}
pub fn start() {
if shell::foto() || shell::setting("limitar_janelas", "1") != "1" {
return;
}
let st = s();
unsafe {
let f = WINEVENT_OUTOFCONTEXT | shell::sem_proprio();
if st.hook_move.is_invalid() {
st.hook_move = SetWinEventHook(EVENT_SYSTEM_MOVESIZEEND, EVENT_SYSTEM_MOVESIZEEND, None, Some(on_move_end), 0, 0, f);
}
if st.hook_show.is_invalid() {
st.hook_show = SetWinEventHook(EVENT_OBJECT_SHOW, EVENT_OBJECT_SHOW, None, Some(on_show), 0, 0, f);
}
// as que já estavam abertas (Shell reiniciado)
let _ = EnumWindows(Some(enum_inicio), LPARAM(0));
}
later(0, &[2500, 8000, 20000]); // ao ligar o PC os apps ainda estão abrindo e se ajeitando
}
pub fn stop() {
let st = s();
unsafe {
if !st.hook_move.is_invalid() {
let _ = UnhookWinEvent(st.hook_move);
st.hook_move = HWINEVENTHOOK::default();
}
if !st.hook_show.is_invalid() {
let _ = UnhookWinEvent(st.hook_show);
st.hook_show = HWINEVENTHOOK::default();
}
if st.timer != 0 {
let _ = KillTimer(None, st.timer);
st.timer = 0;
}
}
st.rechecks.clear();
}
/// maximizada por cima da barra de menus e do Dock (issue #24): volta para a área de trabalho, com as bordas invisíveis
/// para fora; até 3 vezes a cada maximizar, e quem volta exatamente para onde estava insiste no lugar dele
pub fn maximizada(h: HWND) {
let st = s();
let k = h.0 as isize;
unsafe {
if h.0.is_null() {
return;
}
if !IsZoomed(h).as_bool() || IsIconic(h).as_bool() {
st.feitas.retain(|x| *x != k);
st.antes.remove(&k);
return;
}
if !IsWindowVisible(h).as_bool() || apps::is_shell_window(h) || st.feitas.contains(&k) {
return;
}
if GetWindowLongW(h, GWL_STYLE) as u32 & WS_CAPTION.0 != WS_CAPTION.0 || !GetPropW(h, w!("MacJanela")).is_invalid() {
return; // a da DLL usa o ampliar
}
let hm = MonitorFromWindow(h, MONITOR_DEFAULTTONEAREST);
let wa = principal::work_area_for(hm);
let mut wr = RECT::default();
if GetWindowRect(h, &mut wr).is_err() {
return;
}
let mut fb = RECT::default();
if DwmGetWindowAttribute(h, DWMWA_EXTENDED_FRAME_BOUNDS, &mut fb as *mut _ as *mut _, std::mem::size_of::<RECT>() as u32).is_err() {
fb = wr;
}
// a borda invisível de redimensionar fica para fora numa maximizada comum: só corrige quem passa dela
let dpi = GetDpiForWindow(h);
let borda = GetSystemMetricsForDpi(SM_CYSIZEFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) + 2;
if fb.top >= wa.top - borda && fb.bottom <= wa.bottom + borda {
return;
}
if st.feitas.len() > 64 {
st.feitas.clear();
}
if st.antes.len() > 64 {
st.antes.clear();
}
let now = GetTickCount();
let a = st.antes.entry(k).or_insert((RECT::default(), 0, 0));
if a.1 > 0 && a.0 == wr && now.wrapping_sub(a.2) < 300 {
return; // a correção ainda não chegou
}
if a.1 >= 3 || (a.1 > 0 && a.0 == wr) {
st.feitas.push(k);
log!("limites: maximizada '{}' fica onde o programa quer (insistiu)", shell::class_name(h));
return;
}
*a = (wr, a.1 + 1, now);
let (dl, dt, dr, db) = (fb.left - wr.left, fb.top - wr.top, wr.right - fb.right, wr.bottom - fb.bottom);
let _ = SetWindowPos(h, None, wa.left - dl, wa.top - dt, (wa.right - wa.left) + dl + dr, (wa.bottom - wa.top) + dt + db, SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_ASYNCWINDOWPOS);
log!("limites: maximizada '{}' por cima da barra/do Dock: volta para a área de trabalho", shell::class_name(h));
}
}