Skip to content

armgit / WacOS

Public Imported from GitHub
0

A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.

Rust
28.9 KB
Raw Blame
// macjanela.cpp, parte 3: a janela da faixa (cliques, botões, menu verde), manter acima da janela, cores da barra
// (lidas da tela ou do DC do app) e a medida da barra própria.

static G_DUPLO: Global<(u32, POINT)> = Global::new((0, POINT { x: 0, y: 0 }));
pub unsafe extern "system" fn overlay_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    // pânico aqui não pode derrubar o programa onde a DLL está (vira o valor neutro)
    crate::guarda(LRESULT(0), || {
        let ip = comum::util::get_wlp(h, GWLP_USERDATA) as *mut Info;
        let inf = if ip.is_null() { None } else { Some(&mut *ip) };
        let pt_l = POINT { x: get_x_lparam(l), y: get_y_lparam(l) };
        match m {
            WM_NCHITTEST => {
                let Some(i) = inf else { return DefWindowProcW(h, m, w_, l) };
                let r = bar_rect(i);
                let p = POINT { x: pt_l.x - r.left, y: pt_l.y - r.top };
                let sc = scale(i.owner);
                if i.custom {
                    // só as duas faixas pintadas; o resto deixa o clique passar para a barra do app (abas, arrastar)
                    if p.x as f32 / sc < patch_left(i) || p.x as f32 / sc > (r.right - r.left) as f32 / sc - patch_r(i) {
                        return LRESULT(HTCLIENT as isize);
                    }
                    return LRESULT(HTTRANSPARENT as isize);
                }
                if (p.x as f32 / sc) < (if unified_bar(i.owner) > 40 { 84.0 } else { 72.0 }) + win_app_inset(i) {
                    return LRESULT(HTCLIENT as isize);
                }
                LRESULT(HTTRANSPARENT as isize)
            }
            WM_MOUSEACTIVATE => LRESULT(MA_NOACTIVATE as isize),
            WM_TIMER => {
                if w_.0 == 9 {
                    // o menu do ˅: levar para baixo do ˅ da direita (até 40 tentativas de 40 ms)
                    let n = GetPropW(h, w!("MacSetaMenu")).0 as isize + 1;
                    let _ = SetPropW(h, w!("MacSetaMenu"), HANDLE(n as *mut _));
                    let feito = match inf {
                        Some(i) => levar_menu_da_seta(i),
                        None => true,
                    };
                    if feito || n > 40 {
                        let _ = KillTimer(h, 9);
                        let _ = RemovePropW(h, w!("MacSetaMenu"));
                    }
                    return LRESULT(0);
                }
                if w_.0 == 11 {
                    // faixa filha com o mouse no grupo movido ou no ˅: refaz a foto (o realce do app aparece na cópia)
                    match inf {
                        Some(i) if !(i.sobre == 0 && (tick().wrapping_sub(i.recap_ate) as i32) > 0) => {
                            if i.sobre != 0 {
                                i.recap_ate = tick().wrapping_add(400); // e mais uma vez logo depois de sair (o realce apaga)
                            }
                            medir_barra(i);
                        }
                        _ => {
                            let _ = KillTimer(h, 11);
                            if !ip.is_null() {
                                (*ip).recap_on = false;
                            }
                        }
                    }
                    return LRESULT(0);
                }
                if w_.0 == 7 {
                    // ponteiro parado no botão verde: o menu de encaixe do Shell (como no macOS Sequoia)
                    let _ = KillTimer(h, 7);
                    let mut c = POINT::default();
                    let _ = GetCursorPos(&mut c);
                    let mut p = c;
                    let _ = ScreenToClient(h, &mut p);
                    if let Some(i) = inf {
                        if hit_light(i, p) == 2 && i.style as u32 & WS_MAXIMIZEBOX.0 != 0 && GetAsyncKeyState(VK_LBUTTON.0 as i32) >= 0 {
                            if let Some(sh) = find_window("ShellMensagens") {
                                let _ = PostMessageW(sh, reg_msg("ShellMenuVerde"), WPARAM(i.owner.0 as usize), makelparam(c.x, c.y + 14));
                            }
                        }
                    }
                    return LRESULT(0);
                }
                if let Some(i) = inf {
                    if i.custom {
                        // barra_mac_propria desligado com a janela já pega: solta (o modo leve volta na próxima varredura)
                        let undo = G_MSG_UNDO.load(Ordering::SeqCst);
                        if !barra_propria() && undo != 0 {
                            let _ = KillTimer(h, 1);
                            let _ = PostMessageW(i.owner, undo, WPARAM(0), LPARAM(0));
                            return LRESULT(0);
                        }
                        sample_bar(i);
                        // a faixa filha no topo das filhas do app (o Chromium cria as dele depois e elas ficavam por cima)
                        if i.filho && visible(i.overlay) && GetWindow(i.owner, GW_CHILD).unwrap_or_default() != i.overlay {
                            let _ = SetWindowPos(i.overlay, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
                        }
                        // onde ficam os botões: logo ao pegar a janela, depois de mudar de tamanho/ativar, e a cada 8 s ativa
                        if i.layout_at == 0 || (i.active && tick().wrapping_sub(i.layout_at) > 8000) {
                            medir_barra(i);
                        }
                    } else {
                        sample_caption(i);
                    }
                    update_shadow(i);
                    // logo depois de aparecer ou ativar: relê a cada quadro até a cor firmar; depois, devagar
                    let fast = tick() < i.fast_until && (i.custom || i.need_color);
                    SetTimer(
                        h,
                        1,
                        if fast {
                            if i.custom {
                                RELE_COR_MS
                            } else {
                                16
                            }
                        } else if i.active {
                            if economia() { 3000 } else { 1500 }
                        } else if economia() {
                            8000
                        } else {
                            4000
                        },
                        None,
                    );
                }
                LRESULT(0)
            }
            WM_MOUSEMOVE => {
                if let Some(i) = inf {
                    let p = pt_l;
                    let mut t = TRACKMOUSEEVENT { cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE, hwndTrack: h, dwHoverTime: 0 };
                    let _ = TrackMouseEvent(&mut t);
                    // o grupo movido (setas do Discord): o mouse vai para o app, que acende o botão no lugar de verdade
                    let (alvo, _) = alvo_movido(i, p);
                    if alvo != 0 {
                        repassa_grupo(i, p, WM_MOUSEMOVE);
                    }
                    if alvo != i.sobre {
                        if i.sobre != 0 && alvo == 0 {
                            sai_do_grupo(i);
                        }
                        i.sobre = alvo;
                        if i.filho {
                            paint(i);
                        }
                    }
                    // o realce do app na cópia: só liga o relógio se ainda não está correndo (o SetTimer o reiniciava)
                    if i.filho && alvo != 0 {
                        i.recap_ate = tick().wrapping_add(400);
                        if !i.recap_on {
                            i.recap_on = true;
                            SetTimer(h, 11, REFOTO_MS, None);
                        }
                    }
                    // os símbolos (× − +) só em cima dos botões do Mac, como no Mac
                    let luzes = alvo == 0 && (!i.custom || (p.x as f32 / scale(i.owner)) < patch_l(i));
                    if luzes != i.hover_lights {
                        i.hover_lights = luzes;
                        paint(i);
                    }
                    // em cima do verde: conta o tempo parado; saiu dele: cancela
                    if hit_light(i, p) == 2 {
                        if GetPropW(h, w!("MacVerdeEspera")).0.is_null() {
                            let _ = SetPropW(h, w!("MacVerdeEspera"), HANDLE(1 as *mut _));
                            SetTimer(h, 7, 650, None);
                        }
                    } else if !RemovePropW(h, w!("MacVerdeEspera")).unwrap_or_default().0.is_null() {
                        let _ = KillTimer(h, 7);
                    }
                }
                LRESULT(0)
            }
            WM_MOUSELEAVE_ => {
                if let Some(i) = inf {
                    i.hover_lights = false;
                    i.press = -1;
                    paint(i);
                    if i.sobre != 0 {
                        i.sobre = 0;
                        sai_do_grupo(i);
                        if i.filho {
                            paint(i);
                        }
                    }
                }
                let _ = RemovePropW(h, w!("MacVerdeEspera"));
                let _ = KillTimer(h, 7);
                LRESULT(0)
            }
            WM_LBUTTONDOWN => {
                let _ = RemovePropW(h, w!("MacVerdeEspera"));
                let _ = KillTimer(h, 7);
                if let Some(i) = inf {
                    let p = pt_l;
                    let (alvo, _) = alvo_movido(i, p);
                    if alvo == 2 {
                        i.press = 101; // o ˅: o clique inteiro vai quando o botão solta
                        SetCapture(h);
                        return LRESULT(0);
                    }
                    if repassa_grupo(i, p, WM_LBUTTONDOWN) {
                        i.press = 100;
                        return LRESULT(0);
                    }
                    i.press = hit_light(i, p);
                    if i.custom && i.press < 0 {
                        // barra própria, fora das bolinhas: é barra de título, como no Mac. Duplo clique amplia/restaura;
                        // senão arrasta a janela
                        let mut sp = p;
                        let _ = ClientToScreen(h, &mut sp);
                        let agora = GetMessageTime() as u32;
                        let (ultimo, onde) = *G_DUPLO.get();
                        let duplo = agora.wrapping_sub(ultimo) <= GetDoubleClickTime() && (sp.x - onde.x).abs() <= GetSystemMetrics(SM_CXDOUBLECLK) && (sp.y - onde.y).abs() <= GetSystemMetrics(SM_CYDOUBLECLK);
                        *G_DUPLO.get() = (if duplo { 0 } else { agora }, sp);
                        if duplo {
                            if i.style as u32 & WS_MAXIMIZEBOX.0 != 0 {
                                let _ = ShowWindow(i.owner, if zoomed(i.owner) { SW_RESTORE } else { SW_MAXIMIZE });
                            }
                            return LRESULT(0);
                        }
                        // nada de WM_NCLBUTTONDOWN no ponto do clique: por baixo da faixa da direita estão os botões do
                        // Chromium (o clique minimizava ou fechava). Só arrasta se o ponteiro andar.
                        if DragDetect(h, sp).as_bool() {
                            arrasta_janela(i.owner, sp);
                        }
                        return LRESULT(0);
                    }
                    SetCapture(h);
                }
                LRESULT(0)
            }
            WM_LBUTTONUP => {
                let _ = ReleaseCapture();
                let Some(i) = inf else { return LRESULT(0) };
                let p = pt_l;
                if i.press == 100 {
                    repassa_grupo(i, p, WM_LBUTTONUP);
                    i.press = -1;
                    return LRESULT(0);
                }
                if i.press == 101 {
                    // o ˅: mover, apertar e soltar de uma vez no de verdade (o Chrome cancela se vierem separados)
                    i.press = -1;
                    if alvo_movido(i, p).0 == 2 {
                        repassa_grupo(i, p, WM_LBUTTONDOWN);
                        repassa_grupo(i, p, WM_LBUTTONUP);
                        let _ = SetPropW(h, w!("MacSetaMenu"), HANDLE(std::ptr::null_mut()));
                        SetTimer(h, 9, 40, None);
                    }
                    return LRESULT(0);
                }
                let k = hit_light(i, p);
                let st = i.style as u32;
                if k >= 0 && k == i.press {
                    if k == 0 {
                        let _ = PostMessageW(i.owner, WM_SYSCOMMAND, WPARAM(SC_CLOSE as usize), LPARAM(0));
                    } else if k == 1 && st & WS_MINIMIZEBOX.0 != 0 {
                        let _ = ShowWindow(i.owner, SW_MINIMIZE);
                    } else if k == 2 && st & WS_MAXIMIZEBOX.0 != 0 && i.custom {
                        let _ = ShowWindow(i.owner, if zoomed(i.owner) { SW_RESTORE } else { SW_MAXIMIZE }); // (o Chromium ignora o SC_MAXIMIZE postado)
                    } else if k == 2 && st & WS_MAXIMIZEBOX.0 != 0 {
                        toggle_zoom(i);
                    }
                }
                i.press = -1;
                LRESULT(0)
            }
            _ => DefWindowProcW(h, m, w_, l),
        }
    })
}
/// a faixa e os cantos ficam logo acima da janela (o Cubase traz as janelas de plug-in para a frente com
/// SWP_NOOWNERZORDER e elas passavam por cima das próprias janelas de dono)
pub fn keep_above(i: &Info) {
    let h = i.owner;
    if !visible(h) {
        return;
    }
    unsafe {
        for o in [if i.filho { i.minis } else { i.overlay }, i.corner[0]] {
            if !visible(o) {
                continue;
            }
            // logo acima da janela: só as camadas dela (faixa, cantos, prévia) podem estar no meio
            let mut above = false;
            let mut x = GetWindow(h, GW_HWNDPREV).unwrap_or_default();
            while !x.0.is_null() {
                if x == o {
                    above = true;
                    break;
                }
                if owner_of(x) != h && IsWindowVisible(x).as_bool() {
                    break; // outra janela no meio: não está colada
                }
                x = GetWindow(x, GW_HWNDPREV).unwrap_or_default();
            }
            if above {
                continue;
            }
            let prev = GetWindow(h, GW_HWNDPREV).unwrap_or_default();
            let _ = SetWindowPos(o, if prev.0.is_null() { HWND_TOP } else { prev }, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
        }
    }
}
pub fn place_overlay(i: &mut Info) {
    if i.overlay.0.is_null() || i.transit {
        return;
    }
    unsafe {
        if !GetPropW(i.owner, w!("MacJanelaPintando")).0.is_null() {
            return; // aparecendo: a barra espera a janela pintar
        }
        let show = !(i.custom && i.recusa) && visible(i.owner) && !iconic(i.owner) && !fullscreen(i.owner) && !controles::is_alert(i.owner) && !taken_by_shell(i.owner);
        // a faixa filha some e volta junto com a janela: minimizada, fica como está, e ao restaurar já está lá
        // (escondê-la e mostrá-la de novo depois fazia os botões do Windows piscarem; PR #263)
        if !show && i.filho && iconic(i.owner) && !(i.custom && i.recusa) {
            return;
        }
        if !show {
            let _ = ShowWindow(i.overlay, SW_HIDE);
            if !i.minis.0.is_null() {
                let _ = ShowWindow(i.minis, SW_HIDE);
            }
            return;
        }
        paint(i); // UpdateLayeredWindow já posiciona e redimensiona
        if !visible(i.overlay) {
            let _ = ShowWindow(i.overlay, SW_SHOWNOACTIVATE);
            keep_above(i);
            if i.custom {
                minis(i);
            }
        }
    }
}
fn luma_escura(c: u32) -> bool {
    (get_r(c) as u32 * 299 + get_g(c) as u32 * 587 + get_b(c) as u32 * 114) / 1000 < 128
}
/// barra com a cor do próprio app (como no Mac); antes da primeira leitura, a cor da barra do Mac no tema do Windows
pub fn apply_colors(i: &mut Info) {
    if i.custom {
        return; // barra própria: a cor, a borda e o escuro são do app
    }
    let mut cap = i.cap;
    if cap == CLR_INVALID {
        i.dark = dark();
        cap = if i.dark { rgb(0x2D, 0x2D, 0x2F) } else { rgb(0xE9, 0xE9, 0xEA) };
    } else {
        i.dark = luma_escura(cap);
    }
    unsafe {
        let _ = DwmSetWindowAttribute(i.owner, DWMWINDOWATTRIBUTE(35), &cap as *const _ as *const _, 4); // DWMWA_CAPTION_COLOR
        // tela cheia (vídeo, jogo): sem a borda fina colorida, cuja cor (lida do topo da janela) mudava com o vídeo (issue #101)
        let border = if i.rgn.cx != 0 || fullscreen(i.owner) { 0xFFFF_FFFE } else { rgb(get_r(cap) * 8 / 10, get_g(cap) * 8 / 10, get_b(cap) * 8 / 10) };
        let _ = DwmSetWindowAttribute(i.owner, DWMWINDOWATTRIBUTE(34), &border as *const _ as *const _, 4);
    }
    paint_nc(i);
    unsafe {
        let dk: i32 = i.dark as i32;
        let _ = DwmSetWindowAttribute(i.owner, DWMWINDOWATTRIBUTE(20), &dk as *const _ as *const _, 4); // DWMWA_USE_IMMERSIVE_DARK_MODE
    }
}
/// a cor mais comum numa faixa de 4 px (src: a tela ou o DC da própria janela); CLR_INVALID se não deu
pub fn strip_color(src: HDC, x: i32, y: i32, w_: i32) -> u32 {
    const H: i32 = 4;
    unsafe {
        let mem = CreateCompatibleDC(src);
        let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: w_, biHeight: -H, biPlanes: 1, biBitCount: 32, ..Default::default() }, ..Default::default() };
        let mut bits: *mut core::ffi::c_void = std::ptr::null_mut();
        let Ok(bmp) = CreateDIBSection(mem, &bi, DIB_RGB_COLORS, &mut bits, None, 0) else {
            let _ = DeleteDC(mem);
            return CLR_INVALID;
        };
        let old = SelectObject(mem, bmp);
        let ok = BitBlt(mem, 0, 0, w_, H, src, x, y, SRCCOPY).is_ok();
        let px = std::slice::from_raw_parts(bits as *const u32, (w_ * H) as usize);
        let mut count: Vec<(u32, i32)> = Vec::new();
        for yy in 0..H {
            let mut xx = w_ / 10;
            while xx < w_ - w_ / 10 {
                let v = px[(yy * w_ + xx) as usize] & 0xFFFFFF;
                match count.iter_mut().find(|p| p.0 == v) {
                    Some(p) => p.1 += 1,
                    None => count.push((v, 1)),
                }
                xx += (w_ / 40).max(1);
            }
        }
        SelectObject(mem, old);
        let _ = DeleteObject(bmp);
        let _ = DeleteDC(mem);
        if !ok || count.is_empty() {
            return CLR_INVALID;
        }
        let v = count.iter().max_by_key(|p| p.1).unwrap().0; // BGR do DIB
        let c = rgb(((v >> 16) & 255) as u8, ((v >> 8) & 255) as u8, (v & 255) as u8);
        if c == 0 {
            CLR_INVALID // preto puro: o app ainda não desenhou
        } else {
            c
        }
    }
}
/// usa a cor lida: aplica na hora; guarda só quando duas leituras seguidas concordam
pub fn use_color(i: &mut Info, c: u32) {
    if c == CLR_INVALID || i.tool {
        return; // plug-in: barra escura fixa
    }
    // ampliando, ou logo depois: o topo do app vem preto
    if i.transit || (tick().wrapping_sub(i.color_freeze_until) as i32) < 0 {
        return;
    }
    let stable = c == i.last_read;
    i.last_read = c;
    if stable {
        i.need_color = false;
        if i.cor_gravada != c {
            i.cor_gravada = c;
            save_color(i.owner, c);
        }
    }
    if c == i.cap {
        return;
    }
    i.cap = c;
    apply_colors(i);
    paint(i);
}
/// direto da imagem da própria janela (quem desenha com GDI); quem desenha pela placa de vídeo devolve preto
pub fn sample_own_dc(i: &mut Info) -> bool {
    if iconic(i.owner) {
        return false;
    }
    let cr = client_rect(i.owner);
    if cr.right < 60 || cr.bottom < 30 {
        return false;
    }
    let c = unsafe {
        let dc = GetDC(i.owner);
        let c = strip_color(dc, 0, 1, cr.right);
        ReleaseDC(i.owner, dc);
        c
    };
    if c == CLR_INVALID {
        return false;
    }
    use_color(i, c);
    true
}
/// lê a cor do topo da área do app, logo abaixo da barra (só com a janela na frente: senão pode estar coberta)
pub fn sample_caption(i: &mut Info) {
    unsafe {
        if GetForegroundWindow() != i.owner || iconic(i.owner) {
            return;
        }
        let c = client_origin(i.owner);
        let cr = client_rect(i.owner);
        if cr.right < 60 || cr.bottom < 30 {
            return;
        }
        let screen = GetDC(None);
        let cor = strip_color(screen, c.x, c.y + 1, cr.right);
        ReleaseDC(None, screen);
        use_color(i, cor);
    }
}
fn bgr_to_cor(v: u32) -> u32 {
    rgb(((v >> 16) & 255) as u8, ((v >> 8) & 255) as u8, (v & 255) as u8)
}
fn perto(a: u32, b: u32) -> bool {
    let d = ((a & 255) as i32 - (b & 255) as i32).abs() + (((a >> 8) & 255) as i32 - ((b >> 8) & 255) as i32).abs() + (((a >> 16) & 255) as i32 - ((b >> 16) & 255) as i32).abs();
    d <= 12
}
fn mais_comum(v: &[u32]) -> Option<u32> {
    let mut cnt: Vec<(u32, i32)> = Vec::new();
    for &x in v {
        match cnt.iter_mut().find(|p| p.0 == x) {
            Some(p) => p.1 += 1,
            None => cnt.push((x, 1)),
        }
    }
    // o primeiro com a contagem máxima (como o max_element do C++)
    let mut best: Option<(u32, i32)> = None;
    for c in cnt {
        if best.is_none_or(|b| c.1 > b.1) {
            best = Some(c);
        }
    }
    best.map(|b| b.0)
}
/// modo barra própria: lê a cor da barra do app ao lado dos botões dele e na esquerda, e a altura da barra
pub fn sample_bar(i: &mut Info) {
    if iconic(i.owner) || !visible(i.owner) || i.transit {
        return;
    }
    if i.size_at != 0 && tick().wrapping_sub(i.size_at) < 700 {
        return; // a janela ainda está assentando
    }
    let f = frame_rect(i.owner);
    let sc = scale(i.owner);
    unsafe {
        // inativa também (o Chrome clareia a barra ao perder o foco): só lê se os pontos lidos estão à mostra
        if GetForegroundWindow() != i.owner {
            let pts = [POINT { x: f.right - ((patch_r(i) + 12.0) * sc) as i32, y: f.top + (5.0 * sc) as i32 }, POINT { x: f.left + ((PATCH_L + 12.0) * sc) as i32, y: f.top + (5.0 * sc) as i32 }];
            for p in pts {
                let at = WindowFromPoint(p);
                let root = if at.0.is_null() { HWND::default() } else { GetAncestor(at, GA_ROOT) };
                if root != i.owner && root != i.overlay {
                    return;
                }
            }
        }
        let (w_, h) = (f.right - f.left, ((64.0 * sc) as i32).min(f.bottom - f.top));
        if w_ < 300 || h < 20 {
            return;
        }
        let screen = GetDC(None);
        let mem = CreateCompatibleDC(screen);
        let bi = BITMAPINFO { bmiHeader: BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: w_, biHeight: -h, biPlanes: 1, biBitCount: 32, ..Default::default() }, ..Default::default() };
        let mut bits: *mut core::ffi::c_void = std::ptr::null_mut();
        let Ok(bmp) = CreateDIBSection(mem, &bi, DIB_RGB_COLORS, &mut bits, None, 0) else {
            let _ = DeleteDC(mem);
            ReleaseDC(None, screen);
            return;
        };
        let old = SelectObject(mem, bmp);
        let _ = BitBlt(mem, 0, 0, w_, h, screen, f.left, f.top, SRCCOPY);
        let px = std::slice::from_raw_parts(bits as *const u32, (w_ * h) as usize);
        let at = |x: i32, y: i32| px[(y.clamp(0, h - 1) * w_ + x.clamp(0, w_ - 1)) as usize] & 0xFFFFFF;
        let mut xr = w_ - ((patch_r(i) + 4.0) * sc) as i32;
        let y0 = (5.0 * sc) as i32;
        // a cor mais comum num trecho de 30 pt logo antes dos botões (um ponto só às vezes caía num ícone)
        let ini = (xr - (30.0 * sc) as i32).max(0);
        let trecho: Vec<u32> = (ini..=xr).map(|x| at(x, y0)).collect();
        let right = mais_comum(&trecho).unwrap_or(at(xr, y0));
        let mut x = xr;
        while x >= ini {
            if at(x, y0) == right {
                xr = x; // a altura é medida numa coluna dessa cor
                break;
            }
            x -= 1;
        }
        // altura da barra: desce ao lado dos botões enquanto a cor é a mesma
        let mut bar_h = h;
        for y in y0..h {
            if !perto(at(xr, y), right) && !perto(at(xr, y + 1), right) {
                bar_h = y;
                break;
            }
        }
        // esquerda: a cor mais comum numa linha do topo, logo depois da faixa dos botões do Mac (só 24 pt)
        let lx = if i.custom { (patch_left(i) * sc) as i32 + 4 } else { (PATCH_L * sc) as i32 + 4 };
        let linha: Vec<u32> = (lx..w_.min(lx + (24.0 * sc) as i32)).map(|x| at(x, y0)).collect();
        SelectObject(mem, old);
        let _ = DeleteObject(bmp);
        let _ = DeleteDC(mem);
        ReleaseDC(None, screen);
        let left = mais_comum(&linha).unwrap_or(right);
        bar_h = bar_h.clamp((30.0 * sc) as i32, (48.0 * sc) as i32); // mínimo 30 pt (o Discord media 20)
        i.bar_cor = bar_h;
        if i.bar_glyph != 0 {
            bar_h = i.bar_glyph; // a medida pelos botões do app vale mais (medir_barra)
        }
        let (lc, rc) = (bgr_to_cor(left), bgr_to_cor(right));
        if lc == i.left_color && rc == i.right_color && bar_h == i.bar_h {
            return;
        }
        if bar_h != i.bar_h {
            i.layout_at = 0; // outra altura de barra: mede de novo onde ficam os botões
        }
        i.left_color = lc;
        i.right_color = rc;
        i.bar_h = bar_h;
        i.dark = luma_escura(lc); // o fundo dos botões do Mac
    }
    place_overlay(i);
}
// ---- a medida da barra própria (botões do app, grupo movido, ˅ do Chrome)
pub static G_LP_SLOT: AtomicIsize = AtomicIsize::new(0); // o gancho das abas do Chrome está posto (gancho_abas)
pub static G_ULTIMO_PATCH: Global<f32> = Global::new(0.0);
/// largura (pt) da área reservada no começo da linha das abas (gancho)
pub static G_LEAD_W: AtomicU32 = AtomicU32::new(0);
pub fn lead_w_get() -> f32 {
    f32::from_bits(G_LEAD_W.load(Ordering::SeqCst))
}
pub fn lead_w_set(v: f32) {
    G_LEAD_W.store(v.to_bits(), Ordering::SeqCst);
}
/// quanto a área reservada encolhe para o ˅ de verdade caber debaixo dos botões do Mac (pt)
pub static G_SETA_AJUSTE: Global<f32> = Global::new(0.0);
/// Chrome com o gancho: o ˅ (~28 pt com fundo próprio) logo depois da área reservada. Achou: a área reservada encolhe
/// para a 1ª aba ficar no lugar de sempre, com o ˅ escondido debaixo da faixa dos botões, e a cópia dele vai para a
/// ponta direita. Não achou (desafixado): normal.
#[allow(clippy::too_many_arguments)]
pub fn medir_seta(i: &mut Info, at: &dyn Fn(i32, i32) -> u32, dist: &dyn Fn(u32, u32) -> i32, bg: u32, x0: i32, x1: i32, y0: i32, ya: i32, yb: i32, sc: f32) {
    let lead = x0 + (lead_w_get() * sc).round() as i32;
    // só na faixa do meio da linha (±10 pt): embaixo, o "pé" curvo da 1ª aba encosta no fundo do ˅
    let cy = (ya + yb) / 2;
    let (ba, bb) = (ya.max(cy - (10.0 * sc) as i32), yb.min(cy + (10.0 * sc) as i32));
    let ink = |x: i32| (ba..bb).any(|y| dist(at(x, y), bg) > 40);
    let (mut s, mut e, mut gap) = (-1, -1, 0);
    let mut x = x0.max(lead - (2.0 * sc) as i32);
    while x < x1.min(lead + (70.0 * sc) as i32) {
        if ink(x) {
            if s < 0 {
                s = x;
            }
            e = x;
            gap = 0;
        } else if s >= 0 {
            gap += 1;
            if gap >= (3.0 * sc) as i32 {
                break;
            }
        }
        x += 1;
    }
    let w_ = e - s + 1;
    i.seta_w = 0;
    if s >= 0 && w_ >= (18.0 * sc) as i32 && w_ <= (44.0 * sc) as i32 && s <= lead + (14.0 * sc) as i32 {
        let (mut ymin, mut ymax) = (i32::MAX, -1);
        for xx in s + 2..=e - 2 {
            for y in ya..yb {
                if dist(at(xx, y), bg) > 40 {
                    ymin = ymin.min(y);
                    ymax = ymax.max(y);
                }
            }
        }
        if ymax > ymin {
            i.seta_x = s - x0;
            i.seta_w = w_;
            i.seta_y = ymin - y0;
            i.seta_h = ymax - ymin + 1;
        }
    }
    // diagnóstico: onde achou o ˅ e onde a busca começou
    let diag = (if s < 0 { 0 } else { (s - x0) & 0xFFF }) | (if w_ > 0 { w_ & 0xFF } else { 0 }) << 12 | ((lead - x0) & 0xFFF) << 20;
    unsafe {
        let _ = SetPropW(i.owner, w!("MacJanelaSeta"), HANDLE(diag as isize as *mut _));
    }
    let (lx0, lp, lr) = lights_layout(i);
    let alvo = lx0 + 2.0 * lp + lr + 16.0; // onde a 1ª aba fica (pt)
    let mut aj = 0.0;
    if i.seta_w != 0 {
        aj = *G_SETA_AJUSTE.get() + ((i.seta_x + i.seta_w) as f32 / sc + 7.0 - alvo);
    }
    let aj = aj.max(0.0f32);
    if (aj - *G_SETA_AJUSTE.get()).abs() > 1.0 {
        *G_SETA_AJUSTE.get() = aj;
        lead_w_set(lead_w(i) - aj);
        i.remedir = true; // mede de novo depois de o Chrome refazer a linha
        refaz_barra(i.owner);
    }
}