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
50.5 KB
Raw Blame
//! Fotos (src\fotos\main.cpp): imagens e vídeos da pasta Imagens (e Vídeos, e as capturas da mesa) em grade, com as
//! miniaturas lidas em duas threads, favoritos, busca e o editor (ajustes, filtros, girar, recortar, salvar cópia).
#![windows_subsystem = "windows"]

use std::collections::{BTreeSet, HashMap, VecDeque};
use std::ffi::c_void;
use std::sync::{Arc, Condvar, Mutex};

use comum::app2d::{self, *};
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::Gdi::HDC;
use comum::windows::Win32::Graphics::Imaging::*;
use comum::windows::Win32::Storage::FileSystem::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::SystemInformation::GetTickCount64;
use comum::windows::Win32::System::Time::FileTimeToSystemTime;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

const WM_SCAN: u32 = WM_APP + 3;
const WM_THUMB: u32 = WM_APP + 4;
const HEADH: f32 = 40.0;
const NAMES: [&str; 5] = ["Biblioteca", "Favoritos", "Recentes", "Capturas de Tela", "Vídeos"];
const FILTERS: [&str; 8] = ["Original", "Vívido", "Dramático", "Quente", "Frio", "Mono", "Prata", "Noir"];

#[derive(Clone)]
struct ItemF {
    path: String,
    time: u64,
    video: bool,
    shot: bool,
}
struct ThumbData {
    path: String,
    img: Option<(u32, u32, Vec<u8>)>,
}
#[derive(Default)]
struct Thumb {
    bmp: Option<ID2D1Bitmap>,
    px: Option<(u32, u32, Vec<u8>)>, // chegou da thread; vira bitmap no próximo desenho
    asked: bool,
    used: u64,
}
#[derive(Clone, Copy)]
struct Cell {
    idx: usize,
    r: RectF,
}

#[derive(Default)]
struct Editor {
    on: bool,
    path: String,
    fw: u32,
    fh: u32,
    full: Vec<u8>,
    pw: u32,
    ph: u32,
    prev: Vec<u8>,
    bmp: Option<ID2D1Bitmap>,
    vals: [f32; 4], // luz, contraste, saturação, calor
    filter: i32,
    crop_mode: bool,
    cropping: bool,
    c0: Ponto,
    c1: Ponto,
    crop: Option<RectF>,
    drag: i32,
    img_rect: RectF,
    hits: Vec<(i32, i32, RectF)>,
}

#[derive(Default)]
struct App {
    sb: f32,
    tb: f32,
    gap: f32,
    all: Vec<ItemF>,
    fav: BTreeSet<String>,
    fav_file: std::path::PathBuf,
    view: i32,
    cell: f32,
    scroll: f32,
    sel: i32,
    shown: Vec<usize>,
    scanning: bool,
    thumbs: HashMap<String, Thumb>,
    queue: Option<Arc<(Mutex<VecDeque<String>>, Condvar)>>,
    px: i32,
    search: String,
    show_mode: i32,
    fill_sq: bool,
    newest: bool,
    cells: Vec<Cell>,
    heads: Vec<(String, f32)>,
    total: f32,
    gh: Vec<(i32, i32, RectF)>,
    sb_hidden: bool,
    ed: Editor,
    tf: HashMap<&'static str, IDWriteTextFormat>,
}
static A: Global<Option<App>> = Global::new(None);
fn a() -> &'static mut App {
    A.get().as_mut().unwrap()
}
fn tf(n: &str) -> &'static IDWriteTextFormat {
    &a().tf[n]
}

fn ext(p: &str) -> String {
    std::path::Path::new(p).extension().map(|x| x.to_string_lossy().to_lowercase()).unwrap_or_default()
}
fn is_img(x: &str) -> bool {
    matches!(x, "jpg" | "jpeg" | "png" | "gif" | "bmp" | "webp" | "heic" | "heif" | "tif" | "tiff" | "avif" | "jfif")
}
fn is_vid(x: &str) -> bool {
    matches!(x, "mp4" | "mov" | "m4v" | "mkv" | "avi" | "wmv" | "webm")
}

// ---- miniaturas: duas threads pegam o pedido mais novo da fila
fn thumb_worker(q: Arc<(Mutex<VecDeque<String>>, Condvar)>, h: usize, px: i32) {
    unsafe {
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
    }
    loop {
        let p = {
            let (m, cv) = &*q;
            let mut g = m.lock().unwrap();
            while g.is_empty() {
                g = cv.wait(g).unwrap();
            }
            g.pop_back().unwrap()
        };
        let mut img = shell_thumbnail(&p, px, SIIGBF_RESIZETOFIT);
        if let Some((_, _, d)) = &mut img {
            if !d.iter().skip(3).step_by(4).any(|&a| a != 0) {
                for i in (3..d.len()).step_by(4) {
                    d[i] = 255;
                }
            }
        }
        let ptr = Box::into_raw(Box::new(ThumbData { path: p, img }));
        unsafe {
            if PostMessageW(HWND(h as *mut c_void), WM_THUMB, WPARAM(0), LPARAM(ptr as isize)).is_err() {
                drop(Box::from_raw(ptr));
            }
        }
    }
}
fn ask_thumb(p: &str) {
    if let Some(q) = &a().queue {
        q.0.lock().unwrap().push_back(p.to_string());
        q.1.notify_one();
    }
}

// ---- varredura (numa thread; o resultado volta pela mensagem)
fn scan_dir(dir: &std::path::Path, depth: i32, out: &mut Vec<ItemF>, shots_only: bool) {
    use std::os::windows::fs::MetadataExt;
    let Ok(rd) = std::fs::read_dir(dir) else { return };
    let dir_s = dir.to_string_lossy().to_string();
    for e in rd.flatten() {
        let nome = e.file_name().to_string_lossy().into_owned();
        let Ok(md) = e.metadata() else { continue };
        if nome.starts_with('.') || md.file_attributes() & (FILE_ATTRIBUTE_HIDDEN.0 | FILE_ATTRIBUTE_SYSTEM.0) != 0 {
            continue;
        }
        if md.is_dir() {
            if depth < 6 && !shots_only {
                scan_dir(&e.path(), depth + 1, out, false);
            }
            continue;
        }
        let x = ext(&nome);
        let (img, vid) = (is_img(&x), is_vid(&x));
        if !img && !vid {
            continue;
        }
        let low = nome.to_lowercase();
        let shot = low.starts_with("captura de tela") || low.starts_with("screenshot") || dir_s.contains("Screenshots") || dir_s.contains("Capturas");
        if shots_only && !shot {
            continue;
        }
        out.push(ItemF { path: e.path().to_string_lossy().into_owned(), time: md.last_write_time(), video: vid, shot });
    }
}
fn scan() {
    let h = wnd().0 as usize;
    std::thread::spawn(move || unsafe {
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
        let known = |id: &GUID| {
            SHGetKnownFolderPath(id, KNOWN_FOLDER_FLAG(0), None)
                .map(|p| {
                    let s = from_pcwstr(PCWSTR(p.0));
                    CoTaskMemFree(Some(p.0 as *const c_void));
                    s
                })
                .unwrap_or_default()
        };
        let (pics, vids, desk) = (known(&FOLDERID_Pictures), known(&FOLDERID_Videos), known(&FOLDERID_Desktop));
        let mut v = Vec::new();
        if !pics.is_empty() {
            scan_dir(std::path::Path::new(&pics), 0, &mut v, false);
        }
        if !vids.is_empty() && !vids.starts_with(&pics) {
            scan_dir(std::path::Path::new(&vids), 0, &mut v, false);
        }
        if !desk.is_empty() {
            scan_dir(std::path::Path::new(&desk), 6, &mut v, true);
        }
        v.sort_by_key(|i| i.time);
        let ptr = Box::into_raw(Box::new(v));
        if PostMessageW(HWND(h as *mut c_void), WM_SCAN, WPARAM(0), LPARAM(ptr as isize)).is_err() {
            drop(Box::from_raw(ptr));
        }
    });
}
fn load_fav() {
    a().fav = read_lines(&a().fav_file).into_iter().filter(|l| !l.is_empty() && !l.starts_with('#')).collect();
}
fn save_fav() {
    let mut v = vec!["# Fotos favoritas".to_string()];
    v.extend(a().fav.iter().cloned());
    write_lines(&a().fav_file, &v);
}
fn scroll_start() -> f32 {
    if a().newest {
        0.0
    } else {
        1e9
    }
}
fn ft_now() -> u64 {
    let d = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap();
    d.as_secs() * 10_000_000 + 116444736000000000
}
fn filter() {
    let a = a();
    let q = a.search.to_lowercase();
    let n = ft_now();
    let month = 30u64 * 24 * 3600 * 10_000_000;
    a.shown = (0..a.all.len())
        .filter(|&i| {
            let it = &a.all[i];
            let ok = match a.view {
                0 => true,
                1 => a.fav.contains(&it.path),
                2 => n.saturating_sub(it.time) < month,
                3 => it.shot,
                _ => it.video,
            };
            ok && (q.is_empty() || it.path.rsplit(['\\', '/']).next().unwrap_or("").to_lowercase().contains(&q))
        })
        .collect();
    if a.newest {
        a.shown.reverse();
    }
    if a.sel >= a.shown.len() as i32 {
        a.sel = -1;
    }
}
fn st_local(t: u64) -> SYSTEMTIME {
    let ft = FILETIME { dwLowDateTime: t as u32, dwHighDateTime: (t >> 32) as u32 };
    let mut loc = FILETIME::default();
    let mut st = SYSTEMTIME::default();
    unsafe {
        let _ = FileTimeToLocalFileTime(&ft, &mut loc);
        let _ = FileTimeToSystemTime(&loc, &mut st);
    }
    st
}
fn layout() {
    let a = a();
    a.cells.clear();
    a.heads.clear();
    let sz = size();
    let gg = bar() > 0.0;
    let m = if gg { 17.0 } else { 16.0 };
    let wd = sz.width - a.sb - 2.0 * m;
    let cols = (((wd + a.gap) / (a.cell + a.gap)) as i32).max(1);
    let cw = (wd - (cols - 1) as f32 * a.gap) / cols as f32;
    let mut y = if gg { 6.0 } else { 8.0 };
    let (mut col, mut last_key) = (0, -1);
    for (k, &i) in a.shown.iter().enumerate() {
        let st = st_local(a.all[i].time);
        let years = gg && a.show_mode == 0;
        let key = if years { st.wYear as i32 } else { st.wYear as i32 * 12 + st.wMonth as i32 };
        if key != last_key && (!gg || a.show_mode < 2) {
            if col > 0 {
                y += cw + a.gap;
                col = 0;
            }
            last_key = key;
            a.heads.push((if years { st.wYear.to_string() } else { idioma::date(&st, idioma::D_MONTH_YEAR) }, y));
            y += HEADH;
        }
        let x = a.sb + m + col as f32 * (cw + a.gap);
        a.cells.push(Cell { idx: k, r: rf(x, a.tb + y, x + cw, a.tb + y + cw) });
        col += 1;
        if col >= cols {
            col = 0;
            y += cw + a.gap;
        }
    }
    if col > 0 {
        y += cw + a.gap;
    }
    a.total = y + if gg { 70.0 } else { 20.0 };
}
fn sel_path() -> String {
    let a = a();
    if a.sel >= 0 && (a.sel as usize) < a.shown.len() {
        a.all[a.shown[a.sel as usize]].path.clone()
    } else {
        String::new()
    }
}
fn glyph(g: &str, r: RectF, c: Cor) {
    text(g, tf("icon"), r, c);
}

/// o quadrado de uma foto; devolve o retângulo da imagem
fn draw_cell(r: RectF, idx: usize, golden: bool, dark: bool, now: u64) -> RectF {
    let path = a().all[a().shown[idx]].path.clone();
    let video = a().all[a().shown[idx]].video;
    let t = a().thumbs.entry(path.clone()).or_default();
    t.used = now;
    if t.bmp.is_none() {
        if let Some((tw, th, px)) = t.px.take() {
            t.bmp = unsafe { bitmap_bgra(app2d::rt(), tw, th, &px) };
        }
    }
    if t.bmp.is_none() && !t.asked {
        t.asked = true;
        ask_thumb(&path);
    }
    let bmp = t.bmp.clone();
    let mut ir = r;
    unsafe {
        let rtt = app2d::rt();
        if golden {
            match &bmp {
                Some(b) => {
                    let bs = b.GetSize();
                    let (rw, rh) = (r.right - r.left, r.bottom - r.top);
                    let k = if a().fill_sq { (rw / bs.width).max(rh / bs.height) } else { (rw / bs.width).min(rh / bs.height) };
                    let (wd, hh) = (bs.width * k, bs.height * k);
                    let (cx, cy) = ((r.left + r.right) / 2.0, (r.top + r.bottom) / 2.0);
                    ir = rf(cx - wd / 2.0, cy - hh / 2.0, cx + wd / 2.0, cy + hh / 2.0);
                    let bp = D2D1_BITMAP_BRUSH_PROPERTIES { extendModeX: D2D1_EXTEND_MODE_CLAMP, extendModeY: D2D1_EXTEND_MODE_CLAMP, interpolationMode: D2D1_BITMAP_INTERPOLATION_MODE_LINEAR };
                    if let Ok(bb) = rtt.CreateBitmapBrush(b, Some(&bp), None) {
                        bb.SetTransform(&mat::mul(&mat::scale(k, k, 0.0, 0.0), &mat::trans(ir.left, ir.top)));
                        rtt.FillRoundedRectangle(&rr(if a().fill_sq { r } else { ir }, 8.0, 8.0), &bb);
                    }
                    if a().fill_sq {
                        ir = r;
                    }
                }
                None => {
                    let (cy, hh) = ((r.top + r.bottom) / 2.0, (r.right - r.left) * 0.66);
                    ir = rf(r.left, cy - hh / 2.0, r.right, cy + hh / 2.0);
                    fill(ir, if dark { rgb(48, 48, 50, 1.0) } else { rgb(238, 238, 240, 1.0) }, 8.0);
                }
            }
        } else {
            fill(r, if dark { rgb(48, 48, 50, 1.0) } else { rgb(236, 236, 238, 1.0) }, 0.0);
            if let Some(b) = &bmp {
                let bs = b.GetSize();
                let k = ((r.right - r.left) / bs.width).max((r.bottom - r.top) / bs.height);
                let (sw, sh) = ((r.right - r.left) / k, (r.bottom - r.top) / k);
                let src = rf((bs.width - sw) / 2.0, (bs.height - sh) / 2.0, (bs.width + sw) / 2.0, (bs.height + sh) / 2.0);
                rtt.DrawBitmap(b, Some(&r), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, Some(&src));
            }
        }
    }
    let badge = rf(ir.left + 4.0, ir.bottom - 22.0, ir.left + 24.0, ir.bottom - 2.0);
    if video {
        text("\u{E714}", tf(if golden { "icon" } else { "badge" }), badge, rgb(255, 255, 255, 1.0));
    }
    if a().fav.contains(&path) {
        text("♥", tf("badge"), badge, rgb(255, 255, 255, 1.0));
    }
    ir
}

fn paint_golden(sz: D2D_SIZE_F, dark: bool) {
    a().gh.clear();
    let text_c = if dark { rgb(245, 245, 247, 1.0) } else { rgb(29, 29, 31, 1.0) };
    let gray = if dark { rgb(152, 152, 157, 1.0) } else { rgb(134, 134, 139, 1.0) };
    let accent = rgb(0, 136, 255, 1.0);
    let sep = if dark { rgb(255, 255, 255, 0.10) } else { rgb(0, 0, 0, 0.09) };
    clear(if dark { rgb(30, 30, 30, 1.0) } else { rgb(255, 255, 255, 1.0) });
    layout();
    let (tb, x0) = (a().tb, a().sb);
    a().scroll = a().scroll.clamp(0.0, (a().total - (sz.height - tb)).max(0.0));
    push_clip(rf(x0, tb, sz.width, sz.height));
    let now = unsafe { GetTickCount64() };
    let mut last_bottom = tb;
    for c in a().cells.clone() {
        let r = rf(c.r.left, c.r.top - a().scroll, c.r.right, c.r.bottom - a().scroll);
        last_bottom = last_bottom.max(r.bottom);
        if r.bottom < tb - 200.0 || r.top > sz.height + 200.0 {
            continue;
        }
        let ir = draw_cell(r, c.idx, true, dark, now);
        if c.idx as i32 == a().sel {
            stroke_rect(rf(ir.left - 2.0, ir.top - 2.0, ir.right + 2.0, ir.bottom + 2.0), accent, 10.0, 3.0);
        }
    }
    for (t, hy) in a().heads.clone() {
        let y = tb + hy - a().scroll;
        if y < tb - HEADH || y > sz.height {
            continue;
        }
        text(&t, tf("titleg"), rf(x0 + 17.0, y + 8.0, sz.width - 17.0, y + HEADH - 6.0), text_c);
    }
    if a().shown.is_empty() {
        let t = if a().scanning {
            tr("Lendo a biblioteca…")
        } else if !a().search.is_empty() {
            tr("Nenhum Resultado")
        } else {
            tr("Nenhuma Foto")
        };
        text(&t, tf("title"), rf(x0, tb, sz.width, sz.height), gray);
    } else {
        let nv = a().shown.iter().filter(|&&k| a().all[k].video).count();
        let np = a().shown.len() - nv;
        let b = if nv > 0 && np > 0 {
            cf!(tr("%d Fotos, %d Vídeos"), np, nv)
        } else if nv > 0 {
            cf!(tr("%d Vídeos"), nv)
        } else {
            cf!(tr("%d Fotos"), np)
        };
        text(&b, tf("footb"), rf(x0, last_bottom + 22.0, sz.width, last_bottom + 40.0), text_c);
    }
    pop_clip();
    fill(rf(x0, 0.0, sz.width, tb), if dark { rgb(30, 30, 30, 1.0) } else { rgb(255, 255, 255, 1.0) }, 0.0);
    fill(rf(x0, tb - 0.5, sz.width, tb), sep, 0.0);
    let tx = x0 + if a().sb_hidden { 140.0 } else { 20.0 };
    text(&tr(NAMES[a().view as usize]), tf("titleg"), rf(tx, 10.0, tx + 300.0, 29.0), text_c);
    if let (Some(&f), Some(&l)) = (a().shown.first(), a().shown.last()) {
        let (t0, t1) = (a().all[f].time.min(a().all[l].time), a().all[f].time.max(a().all[l].time));
        let fmt = |t: u64| idioma::date(&st_local(t), idioma::D_SHORT);
        text(&format!("{} – {}", fmt(t0), fmt(t1)), tf("small"), rf(tx, 27.0, tx + 320.0, 42.0), gray);
    }
    let r_ = std::cell::Cell::new(sz.width - 8.0);
    let cy = 26.0;
    let group = |w_: f32| {
        let r = rf(r_.get() - w_, cy - 18.0, r_.get(), cy + 18.0);
        glass_button(r, dark, false);
        bar_button(r);
        r_.set(r.left);
        r
    };
    {
        let s = a().search.clone();
        let r = group(if s.is_empty() { 36.0 } else { 200.0 });
        icon_search(pt(if s.is_empty() { (r.left + r.right) / 2.0 - 0.5 } else { r.left + 18.0 }, cy - 0.5), text_c, 1.05);
        if !s.is_empty() {
            text(&s, tf("seg"), rf(r.left + 32.0, r.top, r.right - 10.0, r.bottom), text_c);
        }
        a().gh.push((11, 0, r));
        r_.set(r_.get() - 8.0);
    }
    {
        let r = group(146.0);
        let fav = a().sel >= 0 && a().fav.contains(&sel_path());
        let gl = ["\u{E946}", "\u{E72D}", if fav { "\u{EB52}" } else { "\u{EB51}" }, "\u{E70F}"];
        let kinds = [7, 6, 5, 8];
        for i in 0..4 {
            let c = rf(r.left + 6.0 + i as f32 * 33.5, r.top, r.left + 6.0 + (i + 1) as f32 * 33.5, r.bottom);
            glyph(gl[i], c, if a().sel >= 0 { text_c } else { gray });
            a().gh.push((kinds[i], 0, c));
        }
        r_.set(r_.get() - 7.0);
    }
    {
        let r = group(110.0);
        let gl = [if a().fill_sq { "\u{E9A6}" } else { "\u{E740}" }, "\u{E8CB}", "\u{E712}"];
        for i in 0..3 {
            let c = rf(r.left + 6.0 + i as f32 * 32.6, r.top, r.left + 6.0 + (i + 1) as f32 * 32.6, r.bottom);
            glyph(gl[i], c, text_c);
            a().gh.push((12 + i as i32, 0, c));
        }
        r_.set(r_.get() - 12.0);
    }
    if r_.get() - 253.0 - 16.0 - 73.0 > tx + 160.0 {
        let r = group(253.0);
        let seg = ["Anos", "Meses", "Todas as Fotos"];
        let ws = [70.0, 76.0, 107.0];
        let mut x = r.left;
        for i in 0..3 {
            let c = rf(x, r.top, x + ws[i], r.bottom);
            if i as i32 == a().show_mode {
                fill(rf(c.left + 4.0, c.top + 4.0, c.right - 4.0, c.bottom - 4.0), if dark { rgb(255, 255, 255, 0.14) } else { rgb(0, 0, 0, 0.08) }, 14.0);
            }
            text(&tr(seg[i]), tf("seg"), c, text_c);
            a().gh.push((10, i as i32, c));
            x += ws[i];
        }
        r_.set(r_.get() - 16.0);
        let z = group(73.0);
        let ra = rf(z.left, z.top, z.left + 36.5, z.bottom);
        let rb = rf(z.left + 36.5, z.top, z.right, z.bottom);
        line(pt(ra.left + 11.0, cy), pt(ra.right - 11.0, cy), text_c, 1.6);
        icon_plus(pt((rb.left + rb.right) / 2.0, cy), text_c, 7.0);
        fill(rf(z.left + 36.25, cy - 9.0, z.left + 36.75, cy + 9.0), sep, 0.0);
        a().gh.push((3, 0, ra));
        a().gh.push((4, 0, rb));
    }
    let sb = a().sb;
    if !a().sb_hidden {
        fill(rf(0.0, 0.0, sb, sz.height), sidebar_color(), 0.0);
        fill(rf(sb - 0.5, 0.0, sb, sz.height), if dark { rgb(0, 0, 0, 0.5) } else { rgb(0, 0, 0, 0.08) }, 0.0);
        let tbtn = rf(172.0, cy - 18.0, 208.0, cy + 18.0);
        glass_button(tbtn, dark, false);
        icon_sidebar(pt(190.0, cy), text_c);
        a().gh.push((2, 0, tbtn));
        bar_button(tbtn);
        let icons = ["\u{E8B9}", "\u{EB51}", "\u{E823}", "\u{E714}", "\u{E722}"];
        let order = [0, 1, 2, 4, 3];
        let ys = [68.0, 132.0, 164.0, 196.0, 228.0];
        text(&tr("Fixados"), tf("sec"), rf(16.0, 98.0, sb, 114.0), gray);
        for k in 0..5 {
            let v = order[k];
            let r = rf(10.0, ys[k] - 16.0, sb - 10.0, ys[k] + 16.0);
            let on = v == a().view;
            if on {
                fill(r, if dark { rgb(255, 255, 255, 0.10) } else { rgb(0, 0, 0, 0.07) }, 9.0);
            }
            glyph(icons[k], rf(26.0, r.top, 48.0, r.bottom), accent);
            text(&tr(NAMES[v as usize]), tf(if on { "sideb" } else { "side" }), rf(55.0, r.top, r.right - 6.0, r.bottom), text_c);
            a().gh.push((1, v, r));
        }
    } else {
        let tbtn = rf(90.0, cy - 18.0, 126.0, cy + 18.0);
        glass_button(tbtn, dark, false);
        icon_sidebar(pt(108.0, cy), text_c);
        a().gh.push((2, 0, tbtn));
        bar_button(tbtn);
    }
}

fn paint() {
    if !begin_paint() {
        return;
    }
    let dark = dark();
    let sz = size();
    if a().ed.on {
        paint_editor(sz);
        end_paint();
        return;
    }
    if bar() > 0.0 {
        paint_golden(sz, dark);
        end_paint();
        return;
    }
    let text_c = if dark { rgb(245, 245, 247, 1.0) } else { rgb(29, 29, 31, 1.0) };
    let gray = if dark { rgb(152, 152, 157, 1.0) } else { rgb(134, 134, 139, 1.0) };
    clear(if dark { rgb(30, 30, 30, 1.0) } else { rgb(255, 255, 255, 1.0) });
    layout();
    let (tb, sb) = (a().tb, a().sb);
    a().scroll = a().scroll.clamp(0.0, (a().total - (sz.height - tb)).max(0.0));
    push_clip(rf(sb, tb, sz.width, sz.height));
    let now = unsafe { GetTickCount64() };
    for c in a().cells.clone() {
        let r = rf(c.r.left, c.r.top - a().scroll, c.r.right, c.r.bottom - a().scroll);
        if r.bottom < tb - 200.0 || r.top > sz.height + 200.0 {
            continue;
        }
        draw_cell(r, c.idx, false, dark, now);
        if c.idx as i32 == a().sel {
            stroke_rect(rf(r.left + 1.5, r.top + 1.5, r.right - 1.5, r.bottom - 1.5), rgb(10, 132, 255, 1.0), 0.0, 3.0);
        }
    }
    for (t, hy) in a().heads.clone() {
        let y = tb + hy - a().scroll;
        if y < tb - HEADH || y > sz.height {
            continue;
        }
        text(&t, tf("head"), rf(sb + 16.0, y + 6.0, sz.width - 16.0, y + HEADH - 4.0), text_c);
    }
    if a().shown.is_empty() {
        text(&if a().scanning { tr("Lendo a biblioteca…") } else { tr("Nenhuma Foto") }, tf("title"), rf(sb, tb, sz.width, sz.height), gray);
    }
    pop_clip();
    fill(rf(sb, 0.0, sz.width, tb), if dark { rgb(40, 40, 42, 0.96) } else { rgb(250, 250, 252, 0.96) }, 0.0);
    text(&tr(NAMES[a().view as usize]), tf("title"), rf(sb + 16.0, 10.0, sz.width - 200.0, 32.0), text_c);
    text(&cf!(tr("%d itens"), a().shown.len()), tf("small"), rf(sb + 16.0, 30.0, sz.width - 200.0, 48.0), gray);
    fill(rf(0.0, 0.0, sb, sz.height), sidebar_color(), 0.0);
    text(&tr("Fotos"), tf("head"), rf(16.0, 16.0, sb, 40.0), gray);
    let icons = ["\u{E8B9}", "\u{EB51}", "\u{E823}", "\u{E722}", "\u{E714}"];
    for i in 0..5 {
        let r = rf(8.0, 48.0 + i as f32 * 34.0, sb - 8.0, 48.0 + i as f32 * 34.0 + 30.0);
        if i as i32 == a().view {
            fill(r, if dark { rgb(255, 255, 255, 0.12) } else { rgb(0, 0, 0, 0.08) }, 7.0);
        }
        glyph(icons[i], rf(r.left + 6.0, r.top, r.left + 30.0, r.bottom), rgb(10, 132, 255, 1.0));
        text(&tr(NAMES[i]), tf("side"), rf(r.left + 36.0, r.top, r.right, r.bottom), text_c);
    }
    end_paint();
    if a().thumbs.len() > 900 {
        a().thumbs.retain(|_, t| t.bmp.is_none() || now - t.used <= 20000);
    }
}

// ======================= editor
fn wic() -> Option<IWICImagingFactory> {
    unsafe { CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok() }
}
fn load_full(p: &str) -> bool {
    unsafe {
        let Some(f) = wic() else { return false };
        let pw = wz(p);
        let Ok(dec) = f.CreateDecoderFromFilename(pc(&pw), None, GENERIC_READ, WICDecodeMetadataCacheOnDemand) else { return false };
        let Ok(fr) = dec.GetFrame(0) else { return false };
        let mut src: IWICBitmapSource = fr.cast().unwrap();
        let mut o = 1u16;
        if let Ok(q) = fr.GetMetadataQueryReader() {
            for k in [w!("/app1/ifd/{ushort=274}"), w!("/ifd/{ushort=274}")] {
                let mut v = PROPVARIANT::default();
                if q.GetMetadataByName(k, &mut v).is_ok() {
                    if let Ok(x) = u16::try_from(&v) {
                        o = x;
                        break;
                    }
                }
            }
        }
        let t = match o {
            3 => WICBitmapTransformRotate180,
            6 => WICBitmapTransformRotate90,
            8 => WICBitmapTransformRotate270,
            _ => WICBitmapTransformRotate0,
        };
        if t != WICBitmapTransformRotate0 {
            if let Ok(rot) = f.CreateBitmapFlipRotator() {
                if rot.Initialize(&fr, t).is_ok() {
                    src = rot.cast().unwrap();
                }
            }
        }
        let Ok(cv) = f.CreateFormatConverter() else { return false };
        if cv.Initialize(&src, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).is_err() {
            return false;
        }
        let e = &mut a().ed;
        if cv.GetSize(&mut e.fw, &mut e.fh).is_err() {
            return false;
        }
        e.full = vec![0u8; (e.fw * e.fh * 4) as usize];
        cv.CopyPixels(std::ptr::null(), e.fw * 4, &mut e.full).is_ok()
    }
}
fn make_preview() {
    let e = &mut a().ed;
    let k = 1.0f32.min(1600.0 / e.fw.max(e.fh) as f32);
    e.pw = ((e.fw as f32 * k) as u32).max(1);
    e.ph = ((e.fh as f32 * k) as u32).max(1);
    e.prev = vec![0u8; (e.pw * e.ph * 4) as usize];
    for y in 0..e.ph {
        let sy = ((y as f32 / k) as u32).min(e.fh - 1);
        for x in 0..e.pw {
            let sx = ((x as f32 / k) as u32).min(e.fw - 1);
            let (d, s) = (((y * e.pw + x) * 4) as usize, ((sy * e.fw + sx) * 4) as usize);
            e.prev[d..d + 4].copy_from_slice(&e.full[s..s + 4]);
        }
    }
}
fn params() -> (f32, f32, f32, f32) {
    let e = &a().ed;
    let (mut l, mut c, mut s, mut w_) = (e.vals[0], e.vals[1], e.vals[2], e.vals[3]);
    match e.filter {
        1 => {
            s += 0.35;
            c += 0.15
        }
        2 => {
            c += 0.4;
            l -= 0.1;
            s -= 0.1
        }
        3 => w_ += 0.6,
        4 => w_ -= 0.6,
        5 => s = -1.0,
        6 => {
            s = -1.0;
            c += 0.2;
            l += 0.05
        }
        7 => {
            s = -1.0;
            c += 0.6;
            l -= 0.15
        }
        _ => {}
    }
    (l, c, s, w_)
}
fn adjust(px: &mut [u8]) {
    let (e, c, s, w_) = params();
    let ex = 2f32.powf(e);
    let ck = 1.0 + c.clamp(-0.6, 1.2);
    let sk = 1.0 + s.clamp(-1.0, 1.0);
    let lut: Vec<u8> = (0..256).map(|i| ((((i as f32 / 255.0 * ex) - 0.5) * ck + 0.5).clamp(0.0, 1.0) * 255.0).round() as u8).collect();
    for p in px.chunks_mut(4) {
        let (mut b, mut g, mut r) = (lut[p[0] as usize] as f32 / 255.0, lut[p[1] as usize] as f32 / 255.0, lut[p[2] as usize] as f32 / 255.0);
        let l = 0.299 * r + 0.587 * g + 0.114 * b;
        r = l + (r - l) * sk;
        g = l + (g - l) * sk;
        b = l + (b - l) * sk;
        r += w_ * 0.08;
        b -= w_ * 0.08;
        p[0] = (b.clamp(0.0, 1.0) * 255.0).round() as u8;
        p[1] = (g.clamp(0.0, 1.0) * 255.0).round() as u8;
        p[2] = (r.clamp(0.0, 1.0) * 255.0).round() as u8;
        p[3] = 255;
    }
}
fn rot90(px: &mut Vec<u8>, w_: &mut u32, h: &mut u32) {
    let mut o = vec![0u8; px.len()];
    for y in 0..*h {
        for x in 0..*w_ {
            let d = (((*w_ - 1 - x) * *h + y) * 4) as usize;
            let s = ((y * *w_ + x) * 4) as usize;
            o[d..d + 4].copy_from_slice(&px[s..s + 4]);
        }
    }
    *px = o;
    std::mem::swap(w_, h);
}
fn refresh_ed() {
    let mut p = a().ed.prev.clone();
    adjust(&mut p);
    let (pw, ph) = (a().ed.pw, a().ed.ph);
    a().ed.bmp = app2d::s().rt.as_ref().and_then(|r| unsafe { bitmap_bgra(r, pw, ph, &p) });
    invalidate();
}
fn edit_open(p: &str) {
    if !is_img(&ext(p)) {
        return;
    }
    a().ed = Editor { path: p.to_string(), drag: -1, ..Default::default() };
    if !load_full(p) {
        message_box(&tr("Não foi possível abrir a foto para editar."), &tr("Fotos"), MB_OK);
        return;
    }
    make_preview();
    a().ed.on = true;
    refresh_ed();
}
fn edit_close() {
    a().ed = Editor { drag: -1, ..Default::default() };
    invalidate();
}
fn edit_save() {
    let e = &a().ed;
    let (mut px, mut w_, mut h) = (e.full.clone(), e.fw, e.fh);
    if let Some(c) = e.crop {
        let (x0, y0) = ((c.left * w_ as f32) as u32, (c.top * h as f32) as u32);
        let (x1, y1) = ((c.right * w_ as f32) as u32, (c.bottom * h as f32) as u32);
        let (cw, ch) = ((x1 - x0).max(1), (y1 - y0).max(1));
        let mut o = vec![0u8; (cw * ch * 4) as usize];
        for y in 0..ch {
            let s = (((y0 + y) * w_ + x0) * 4) as usize;
            o[(y * cw * 4) as usize..((y + 1) * cw * 4) as usize].copy_from_slice(&px[s..s + (cw * 4) as usize]);
        }
        px = o;
        w_ = cw;
        h = ch;
    }
    adjust(&mut px);
    let stem = e.path.rsplit_once('.').map(|(s, _)| s.to_string()).unwrap_or(e.path.clone());
    let suf = tr(" (editada)");
    let mut out = format!("{stem}{suf}.jpg");
    let mut k = 2;
    while std::path::Path::new(&out).exists() && k < 100 {
        out = format!("{stem}{suf} {k}.jpg");
        k += 1;
    }
    let ok = (|| -> Result<()> {
        unsafe {
            let f = wic().ok_or_else(|| Error::from(E_FAIL))?;
            let wb = f.CreateBitmapFromMemory(w_, h, &GUID_WICPixelFormat32bppPBGRA, w_ * 4, &px)?;
            let st = f.CreateStream()?;
            let o = wz(&out);
            st.InitializeFromFilename(pc(&o), GENERIC_WRITE.0)?;
            let enc = f.CreateEncoder(&GUID_ContainerFormatJpeg, std::ptr::null())?;
            enc.Initialize(&st, WICBitmapEncoderNoCache)?;
            let mut fe: Option<IWICBitmapFrameEncode> = None;
            enc.CreateNewFrame(&mut fe, std::ptr::null_mut())?;
            let fe = fe.ok_or_else(|| Error::from(E_FAIL))?;
            fe.Initialize(None)?;
            fe.SetSize(w_, h)?;
            let mut fmt = GUID_WICPixelFormat24bppBGR;
            fe.SetPixelFormat(&mut fmt)?;
            let cv = f.CreateFormatConverter()?;
            cv.Initialize(&wb, &fmt, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom)?;
            fe.WriteSource(&cv, std::ptr::null())?;
            fe.Commit()?;
            enc.Commit()
        }
    })();
    if ok.is_err() {
        message_box(&tr("Não foi possível salvar a foto."), &tr("Fotos"), MB_OK | MB_ICONERROR);
        return;
    }
    use std::os::windows::fs::MetadataExt;
    let t = std::fs::metadata(&out).map(|m| m.last_write_time()).unwrap_or(ft_now());
    a().all.push(ItemF { path: out, time: t, video: false, shot: false });
    filter();
    edit_close();
}
fn paint_editor(sz: D2D_SIZE_F) {
    a().ed.hits.clear();
    let text_c = rgb(245, 245, 247, 1.0);
    let gray = rgb(152, 152, 157, 1.0);
    let yellow = rgb(255, 204, 0, 1.0);
    let cinza = rgb(58, 58, 60, 1.0);
    let preto = rgb(0, 0, 0, 1.0);
    clear(rgb(18, 18, 18, 1.0));
    let panel = 270.0;
    let (aw, ah) = (sz.width - panel - 40.0, sz.height - 90.0);
    if let Some(b) = a().ed.bmp.clone() {
        let e = &a().ed;
        let k = (aw / e.pw as f32).min(ah / e.ph as f32);
        let (wd, hh) = (e.pw as f32 * k, e.ph as f32 * k);
        let (x, y) = (20.0 + (aw - wd) / 2.0, 60.0 + (ah - hh) / 2.0);
        a().ed.img_rect = rf(x, y, x + wd, y + hh);
        unsafe { app2d::rt().DrawBitmap(&b, Some(&a().ed.img_rect), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None) };
        let e = &a().ed;
        let c = if e.cropping {
            Some(rf(e.c0.x.min(e.c1.x), e.c0.y.min(e.c1.y), e.c0.x.max(e.c1.x), e.c0.y.max(e.c1.y)))
        } else {
            e.crop.map(|f| rf(x + f.left * wd, y + f.top * hh, x + f.right * wd, y + f.bottom * hh))
        };
        if let Some(c) = c {
            let dim = rgb(0, 0, 0, 0.55);
            let ir = e.img_rect;
            fill(rf(ir.left, ir.top, ir.right, c.top), dim, 0.0);
            fill(rf(ir.left, c.bottom, ir.right, ir.bottom), dim, 0.0);
            fill(rf(ir.left, c.top, c.left, c.bottom), dim, 0.0);
            fill(rf(c.right, c.top, ir.right, c.bottom), dim, 0.0);
            stroke_rect(c, yellow, 0.0, 2.0);
        }
    }
    let btn = |kind: i32, arg: i32, r: RectF, label: &str, on: bool| {
        fill(r, if on { yellow } else { cinza }, 7.0);
        text(label, tf("side2"), r, if on { preto } else { text_c });
        a().ed.hits.push((kind, arg, r));
    };
    btn(6, 0, rf(20.0, 14.0, 120.0, 42.0), &tr("Cancelar"), false);
    btn(7, 0, rf(sz.width - 160.0, 14.0, sz.width - 20.0, 42.0), &tr("Salvar Cópia"), true);
    let nome = a().ed.path.rsplit('\\').next().unwrap_or("").to_string();
    text(&nome, tf("smallc"), rf(140.0, 14.0, sz.width - 180.0, 42.0), gray);
    let px = sz.width - panel;
    let mut y = 60.0;
    text(&tr("Ajustar"), tf("title"), rf(px, y, sz.width - 20.0, y + 24.0), text_c);
    y += 34.0;
    let names = ["Luz", "Contraste", "Saturação", "Calor"];
    for (i, n) in names.iter().enumerate() {
        text(&tr(n), tf("side"), rf(px, y, sz.width - 20.0, y + 20.0), text_c);
        let trk = rf(px, y + 26.0, sz.width - 30.0, y + 30.0);
        fill(trk, rgb(72, 72, 74, 1.0), 2.0);
        let mid = (trk.left + trk.right) / 2.0;
        let kx = mid + a().ed.vals[i] * (trk.right - trk.left) / 2.0;
        fill(rf(mid.min(kx), trk.top, mid.max(kx), trk.bottom), yellow, 2.0);
        circle(pt(kx, (trk.top + trk.bottom) / 2.0), 7.0, rgb(255, 255, 255, 1.0), true, 1.5);
        a().ed.hits.push((1, i as i32, rf(trk.left - 8.0, trk.top - 12.0, trk.right + 8.0, trk.bottom + 12.0)));
        y += 50.0;
    }
    y += 6.0;
    text(&tr("Filtros"), tf("title"), rf(px, y, sz.width - 20.0, y + 24.0), text_c);
    y += 32.0;
    for i in 0..8 {
        let (cx, cy) = ((i % 2) as f32 * 120.0, (i / 2) as f32 * 36.0);
        let r = rf(px + cx, y + cy, px + cx + 112.0, y + cy + 30.0);
        btn(2, i, r, &tr(FILTERS[i as usize]), a().ed.filter == i);
    }
    y += 4.0 * 36.0 + 14.0;
    btn(3, 0, rf(px, y, px + 112.0, y + 32.0), &tr("Girar"), false);
    let cm = a().ed.crop_mode;
    btn(4, 0, rf(px + 120.0, y, px + 232.0, y + 32.0), &tr("Recortar"), cm);
    btn(5, 0, rf(px, y + 40.0, px + 232.0, y + 72.0), &tr("Restaurar Original"), false);
    if cm {
        text(&tr("Arraste sobre a foto para escolher o recorte."), tf("small"), rf(px, y + 80.0, sz.width - 10.0, y + 100.0), gray);
    }
}
fn slider_to(i: i32, x: f32) {
    if let Some(h) = a().ed.hits.iter().find(|h| h.0 == 1 && h.1 == i).copied() {
        let (l, r) = (h.2.left + 8.0, h.2.right - 8.0);
        let mut v = (((x - l) / (r - l)) * 2.0 - 1.0).clamp(-1.0, 1.0);
        if v.abs() < 0.04 {
            v = 0.0;
        }
        a().ed.vals[i as usize] = v;
        refresh_ed();
    }
}
fn edit_mouse(m: u32, x: f32, y: f32) {
    unsafe {
        if m == WM_LBUTTONDOWN {
            if let Some(h) = a().ed.hits.iter().find(|h| in_rect(&h.2, x, y)).copied() {
                match h.0 {
                    1 => {
                        a().ed.drag = h.1;
                        SetCapture(wnd());
                        slider_to(h.1, x);
                    }
                    2 => {
                        a().ed.filter = h.1;
                        refresh_ed();
                    }
                    3 => {
                        let e = &mut a().ed;
                        rot90(&mut e.full, &mut e.fw, &mut e.fh);
                        rot90(&mut e.prev, &mut e.pw, &mut e.ph);
                        e.crop = None;
                        refresh_ed();
                    }
                    4 => {
                        a().ed.crop_mode = !a().ed.crop_mode;
                        invalidate();
                    }
                    5 => {
                        let p = a().ed.path.clone();
                        edit_open(&p);
                    }
                    6 => edit_close(),
                    7 => edit_save(),
                    _ => {}
                }
                return;
            }
            if a().ed.crop_mode && in_rect(&a().ed.img_rect, x, y) {
                a().ed.cropping = true;
                a().ed.c0 = pt(x, y);
                a().ed.c1 = pt(x, y);
                SetCapture(wnd());
            }
        } else if m == WM_MOUSEMOVE {
            if a().ed.drag >= 0 {
                slider_to(a().ed.drag, x);
            }
            if a().ed.cropping {
                let ir = a().ed.img_rect;
                a().ed.c1 = pt(x.clamp(ir.left, ir.right), y.clamp(ir.top, ir.bottom));
                invalidate();
            }
        } else if m == WM_LBUTTONUP {
            if a().ed.drag >= 0 {
                a().ed.drag = -1;
                let _ = ReleaseCapture();
            }
            if a().ed.cropping {
                a().ed.cropping = false;
                let _ = ReleaseCapture();
                let e = &mut a().ed;
                let ir = e.img_rect;
                let (wd, hh) = (ir.right - ir.left, ir.bottom - ir.top);
                let c = rf((e.c0.x.min(e.c1.x) - ir.left) / wd, (e.c0.y.min(e.c1.y) - ir.top) / hh, (e.c0.x.max(e.c1.x) - ir.left) / wd, (e.c0.y.max(e.c1.y) - ir.top) / hh);
                if c.right - c.left > 0.03 && c.bottom - c.top > 0.03 {
                    e.crop = Some(c);
                }
                invalidate();
            }
        }
    }
}

fn hit_cell(x: f32, y: f32) -> i32 {
    a().cells.iter().find(|c| in_rect(&c.r, x, y + a().scroll)).map(|c| c.idx as i32).unwrap_or(-1)
}
fn open_sel() {
    let p = sel_path();
    if p.is_empty() {
        return;
    }
    let pv = exe_dir().join(nomes::EXE_PREVIEW);
    if is_img(&ext(&p)) && pv.exists() {
        let mut args = format!("\"{p}\"");
        let lst = std::env::temp_dir().join(format!("fot{}.txt", std::process::id()));
        let lista: Vec<String> = a().shown.iter().map(|&i| a().all[i].path.clone()).filter(|q| is_img(&ext(q))).collect();
        if write_lines(&lst, &lista) {
            args += &format!(" --lista \"{}\"", lst.display());
        }
        shell_open(&pv.to_string_lossy(), Some(&args));
    } else if !nomes::abrir_no_app_mac(&p) {
        shell_open(&p, None);
    }
}
fn toggle_fav() {
    let p = sel_path();
    if p.is_empty() {
        return;
    }
    if !a().fav.remove(&p) {
        a().fav.insert(p);
    }
    save_fav();
    if a().view == 1 {
        filter();
    }
    invalidate();
}
fn trash() {
    let p = sel_path();
    if p.is_empty() {
        return;
    }
    let dbl: Vec<u16> = p.encode_utf16().chain([0, 0]).collect();
    let mut op = SHFILEOPSTRUCTW { hwnd: wnd(), wFunc: FO_DELETE, pFrom: PCWSTR(dbl.as_ptr()), fFlags: (FOF_ALLOWUNDO | FOF_NOCONFIRMATION).0 as u16, ..Default::default() };
    if unsafe { SHFileOperationW(&mut op) } == 0 {
        a().all.retain(|i| i.path != p);
    }
    filter();
    invalidate();
}
fn zoom(f: f32) {
    a().cell = (a().cell * f).clamp(60.0, 420.0);
    invalidate();
}
fn verb(v: &str) {
    let p = sel_path();
    if p.is_empty() {
        return;
    }
    let (vw, pw) = (wz(v), wz(&p));
    let mut se = SHELLEXECUTEINFOW { cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32, fMask: SEE_MASK_INVOKEIDLIST, lpVerb: pc(&vw), lpFile: pc(&pw), nShow: SW_SHOWNORMAL.0, ..Default::default() };
    unsafe {
        let _ = ShellExecuteExW(&mut se);
    }
}
fn mostrar_no_finder() {
    let p = wz(&sel_path());
    unsafe {
        let pidl = ILCreateFromPathW(pc(&p));
        if !pidl.is_null() {
            let _ = SHOpenFolderAndSelectItems(pidl, None, 0);
            ILFree(Some(pidl));
        }
    }
}
fn sidebar_toggle() {
    a().sb_hidden = !a().sb_hidden;
    a().sb = if a().sb_hidden { 0.0 } else { 216.0 };
}

fn click_golden(h: HWND, m: u32, x: f32, y: f32) -> bool {
    let Some(g) = a().gh.iter().find(|g| in_rect(&g.2, x, y)).copied() else { return false };
    if m == WM_RBUTTONUP {
        return true;
    }
    unsafe {
        match g.0 {
            1 => {
                a().view = g.1;
                a().sel = -1;
                filter();
                a().scroll = scroll_start();
            }
            2 => sidebar_toggle(),
            3 => zoom(1.0 / 1.2),
            4 => zoom(1.2),
            5 => toggle_fav(),
            6 => verb("windows.modernshare"),
            7 => verb("properties"),
            8 => edit_open(&sel_path()),
            10 => {
                a().show_mode = g.1;
                a().scroll = 0.0;
            }
            12 => a().fill_sq = !a().fill_sq,
            13 | 14 => {
                let s_ = sc();
                let scr = to_screen(h, (g.2.left * s_) as i32, (g.2.bottom * s_ + 4.0) as i32);
                let Ok(mm) = CreatePopupMenu() else { return true };
                let sel = !sel_path().is_empty();
                let ck = |b: bool| if b { MF_CHECKED } else { MF_UNCHECKED };
                let en = if sel { MF_ENABLED } else { MF_GRAYED };
                if g.0 == 13 {
                    append_menu(mm, MF_STRING | ck(!a().newest), 1, &tr("Mais Antigas Primeiro"));
                    append_menu(mm, MF_STRING | ck(a().newest), 2, &tr("Mais Recentes Primeiro"));
                } else {
                    append_menu(mm, MF_STRING | en, 3, &tr("Abrir"));
                    append_menu(mm, MF_STRING | en, 4, &tr("Mostrar no Finder"));
                    append_menu(mm, MF_STRING | en, 5, &tr("Mover para o Lixo"));
                    let _ = AppendMenuW(mm, MF_SEPARATOR, 0, PCWSTR::null());
                    append_menu(mm, MF_STRING, 6, &if a().sb_hidden { tr("Mostrar Barra Lateral") } else { tr("Ocultar Barra Lateral") });
                    append_menu(mm, MF_STRING, 7, &tr("Atualizar a Biblioteca"));
                }
                let k = TrackPopupMenu(mm, TPM_RETURNCMD | TPM_LEFTALIGN | TPM_TOPALIGN, scr.x, scr.y, 0, h, None).0;
                let _ = DestroyMenu(mm);
                match k {
                    1 | 2 => {
                        a().newest = k == 2;
                        a().sel = -1;
                        filter();
                        a().scroll = scroll_start();
                    }
                    3 => open_sel(),
                    4 => mostrar_no_finder(),
                    5 => trash(),
                    6 => sidebar_toggle(),
                    7 => {
                        a().scanning = true;
                        scan();
                    }
                    _ => {}
                }
            }
            11 => {
                let s0 = a().search.clone();
                field_open(rf(g.2.right - 168.0, g.2.top + 9.0, g.2.right - 10.0, g.2.bottom - 9.0), &s0, 13.0, false, |q, key| {
                    a().search = if key == VK_ESCAPE.0 as i32 { String::new() } else { q };
                    a().sel = -1;
                    filter();
                    a().scroll = 0.0;
                    invalidate();
                });
                return true;
            }
            _ => {}
        }
    }
    invalidate();
    true
}

extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    unsafe {
        let s_ = sc();
        let (x, y) = (get_x_lparam(l) as f32 / s_, get_y_lparam(l) as f32 / s_);
        match m {
            WM_PAINT => return wm_paint(h, paint),
            WM_ERASEBKGND => return LRESULT(1),
            WM_SIZE => on_size(l),
            WM_DPICHANGED => on_dpi(w_, l),
            WM_SETTINGCHANGE => invalidate(),
            WM_CTLCOLOREDIT => return field_colors(HDC(w_.0 as *mut c_void), if dark() { colorref(30, 30, 30) } else { colorref(255, 255, 255) }),
            WM_SCAN => {
                a().all = *Box::from_raw(l.0 as *mut Vec<ItemF>);
                a().scanning = false;
                filter();
                a().scroll = scroll_start();
                invalidate();
            }
            WM_THUMB => {
                let d = *Box::from_raw(l.0 as *mut ThumbData);
                if let (Some(img), Some(t)) = (d.img, a().thumbs.get_mut(&d.path)) {
                    t.px = Some(img);
                    invalidate();
                }
            }
            WM_MOUSEWHEEL => {
                let d = wheel_delta(w_) / 120.0;
                if loword(w_.0) & 0x0008 != 0 {
                    zoom(if d > 0.0 { 1.12 } else { 1.0 / 1.12 });
                } else {
                    a().scroll -= d * 120.0;
                    invalidate();
                }
            }
            WM_MOUSEMOVE | WM_LBUTTONUP => {
                if a().ed.on {
                    edit_mouse(m, x, y);
                }
            }
            WM_LBUTTONDOWN | WM_LBUTTONDBLCLK | WM_RBUTTONUP => {
                if a().ed.on {
                    if m != WM_RBUTTONUP {
                        edit_mouse(WM_LBUTTONDOWN, x, y);
                    }
                    return LRESULT(0);
                }
                if bar() > 0.0 {
                    if click_golden(h, m, x, y) || x < a().sb || y < a().tb {
                        return LRESULT(0);
                    }
                } else if x < a().sb {
                    let i = ((y - 48.0) / 34.0) as i32;
                    if y >= 48.0 && (0..5).contains(&i) {
                        a().view = i;
                        a().sel = -1;
                        filter();
                        a().scroll = scroll_start();
                        invalidate();
                    }
                    return LRESULT(0);
                }
                let c = hit_cell(x, y);
                a().sel = c;
                invalidate();
                if c < 0 {
                    return LRESULT(0);
                }
                if m == WM_LBUTTONDBLCLK {
                    open_sel();
                } else if m == WM_RBUTTONUP {
                    let scr = to_screen(h, get_x_lparam(l), get_y_lparam(l));
                    let fav = a().fav.contains(&sel_path());
                    let Ok(mm) = CreatePopupMenu() else { return LRESULT(0) };
                    append_menu(mm, MF_STRING, 1, &tr("Abrir"));
                    append_menu(mm, MF_STRING, 2, &if fav { tr("Remover dos Favoritos") } else { tr("Favoritar") });
                    append_menu(mm, MF_STRING, 3, &tr("Mostrar no Finder"));
                    let _ = AppendMenuW(mm, MF_SEPARATOR, 0, PCWSTR::null());
                    append_menu(mm, MF_STRING, 4, &tr("Mover para o Lixo"));
                    let k = TrackPopupMenu(mm, TPM_RETURNCMD | TPM_RIGHTBUTTON, scr.x, scr.y, 0, h, None).0;
                    let _ = DestroyMenu(mm);
                    match k {
                        1 => open_sel(),
                        2 => toggle_fav(),
                        3 => mostrar_no_finder(),
                        4 => trash(),
                        _ => {}
                    }
                }
            }
            WM_KEYDOWN => {
                let ctrl = key_down(VK_CONTROL.0);
                let k = w_.0 as u16;
                if a().ed.on {
                    if k == VK_ESCAPE.0 {
                        edit_close();
                    } else if ctrl && k == 'S' as u16 {
                        edit_save();
                    }
                    return LRESULT(0);
                }
                if k == 'E' as u16 && !ctrl {
                    edit_open(&sel_path());
                    return LRESULT(0);
                }
                let cells = a().cells.clone();
                let cols = cells.first().map(|c0| cells.iter().take_while(|c| c.r.top == c0.r.top).count()).unwrap_or(1).max(1) as i32;
                if ctrl && (k == VK_OEM_PLUS.0 || k == VK_ADD.0) {
                    zoom(1.2);
                } else if ctrl && (k == VK_OEM_MINUS.0 || k == VK_SUBTRACT.0) {
                    zoom(1.0 / 1.2);
                } else if ctrl && k == 'W' as u16 {
                    let _ = DestroyWindow(h);
                } else if k == VK_RETURN.0 || k == VK_SPACE.0 {
                    open_sel();
                } else if k == VK_OEM_PERIOD.0 {
                    toggle_fav();
                } else if k == VK_DELETE.0 {
                    trash();
                } else if [VK_LEFT.0, VK_RIGHT.0, VK_UP.0, VK_DOWN.0].contains(&k) && !a().shown.is_empty() {
                    let d = if k == VK_LEFT.0 {
                        -1
                    } else if k == VK_RIGHT.0 {
                        1
                    } else if k == VK_UP.0 {
                        -cols
                    } else {
                        cols
                    };
                    let n = a().shown.len() as i32;
                    a().sel = (if a().sel < 0 { n - 1 } else { a().sel + d }).clamp(0, n - 1);
                    if let Some(c) = cells.iter().find(|c| c.idx as i32 == a().sel) {
                        let vh = size().height;
                        if c.r.top - a().scroll < a().tb {
                            a().scroll = c.r.top - a().tb - 8.0;
                        }
                        if c.r.bottom - a().scroll > vh {
                            a().scroll = c.r.bottom - vh + 8.0;
                        }
                    }
                    invalidate();
                }
            }
            WM_DESTROY => PostQuitMessage(0),
            _ => return DefWindowProcW(h, m, w_, l),
        }
        LRESULT(0)
    }
}

fn main() {
    if !app2d::init() {
        std::process::exit(1);
    }
    *A.get() = Some(App { sb: 210.0, tb: 52.0, gap: 3.0, cell: 150.0, sel: -1, scanning: true, show_mode: 2, fav_file: data_path("fotos-favoritos.txt"), ..Default::default() });
    a().ed.drag = -1;
    load_fav();
    use DWRITE_TEXT_ALIGNMENT_CENTER as C;
    use DWRITE_TEXT_ALIGNMENT_LEADING as L;
    let ic = icon_family();
    let f = |s: f32, w_: DWRITE_FONT_WEIGHT, al: DWRITE_TEXT_ALIGNMENT, fam: Option<&str>| fmt_full(s, w_, al, false, fam);
    let (n, b, sb_) = (DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_WEIGHT_SEMI_BOLD);
    let t = &mut a().tf;
    for (k, v) in [
        ("side", f(13.0, n, L, None)),
        ("side2", f(13.0, n, C, None)),
        ("smallc", f(12.0, n, C, None)),
        ("head", f(17.0, b, L, None)),
        ("title", f(17.0, sb_, L, None)),
        ("small", f(12.0, n, L, None)),
        ("icon", f(15.0, n, C, Some(&ic))),
        ("badge", f(13.0, sb_, C, None)),
        ("titleg", f(13.0, b, L, None)),
        ("sideb", f(13.0, sb_, L, None)),
        ("sec", f(11.0, sb_, L, None)),
        ("seg", f(13.0, n, C, None)),
        ("footb", f(12.0, b, C, None)),
    ] {
        t.insert(k, v);
    }
    set_bar_wanted(52.0);
    let aq = semaforo::aqua();
    let Some(h) = create_main("FotosJanela", &tr("Fotos"), proc_, if aq { 1222 } else { 1200 }, if aq { 720 } else { 800 }) else { std::process::exit(1) };
    if bar() > 0.0 {
        a().sb = 216.0;
        a().gap = 17.5;
        a().cell = 176.0;
    }
    a().px = (256.0 * sc()).round() as i32;
    let q = Arc::new((Mutex::new(VecDeque::new()), Condvar::new()));
    a().queue = Some(q.clone());
    for _ in 0..2 {
        let (q, hh, px) = (q.clone(), h.0 as usize, a().px);
        std::thread::spawn(move || thumb_worker(q, hh, px));
    }
    if let Some(e) = arg_valor("--editar") {
        edit_open(&e); // teste: abre o editor nessa foto
    }
    scan();
    show(h, SW_SHOWNORMAL);
    std::process::exit(run());
}