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
43.4 KB
Raw Blame
//! Música (src\musica\main.cpp): a pasta Música do usuário (Recentes, Artistas, Álbuns, Músicas) tocada pelo
//! MediaPlayer do Windows (WinRT), com o "Tocando Agora" preenchido (nome, artista e capa).
//! No modo --foto não procura outra janela aberta nem toca nada.
#![windows_subsystem = "windows"]

use std::collections::{BTreeSet, HashMap};

use comum::app2d::{self, *};
use comum::windows::core::*;
use comum::windows::Foundation::*;
use comum::windows::Media::Core::MediaSource;
use comum::windows::Media::Playback::*;
use comum::windows::Media::MediaPlaybackType;
use comum::windows::Storage::FileProperties::{ThumbnailMode, ThumbnailType};
use comum::windows::Storage::StorageFile;
use comum::windows::Storage::Streams::RandomAccessStreamReference;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
use comum::windows::Win32::Storage::EnhancedStorage::*;
use comum::windows::Win32::Storage::FileSystem::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::DataExchange::COPYDATASTRUCT;
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_ART: u32 = WM_APP + 4;
const WM_ENDED: u32 = WM_APP + 6;
const WM_SKIP: u32 = WM_APP + 7;
const TITLES: [&str; 4] = ["Recentes", "Artistas", "Álbuns", "Músicas"];
const ICONS: [&str; 4] = ["\u{E823}", "\u{E77B}", "\u{E93C}", "\u{EC4F}"];

#[derive(Clone, Default)]
struct Song {
    path: String,
    title: String,
    artist: String,
    album: String,
    track: u32,
    secs: f64,
    added: u64,
}
struct ArtData {
    album: String,
    img: Option<(u32, u32, Vec<u8>)>,
}
#[derive(Clone, Copy)]
struct Hit {
    kind: i32,
    arg: i32,
    r: RectF,
}

#[derive(Default)]
struct App {
    sb: f32,
    tb: f32,
    rowh: f32,
    songs: Vec<Song>,
    scanning: bool,
    view: i32,
    artist_sel: String,
    album_sel: String,
    scroll: f32,
    sel_row: i32,
    rows: Vec<usize>,
    queue: Vec<usize>,
    /// a fila na ordem de antes do aleatório (para voltar a ela ao desligar)
    orig: Vec<usize>,
    pos: i32,
    shuffle: bool,
    repeat: i32,
    player: Option<MediaPlayer>,
    art: HashMap<String, Option<ID2D1Bitmap>>,
    art_asked: BTreeSet<String>,
    volume: f32,
    search: String,
    sort_by: i32,
    hits: Vec<Hit>,
    smtc_gen: std::sync::Arc<std::sync::atomic::AtomicI32>,
    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 hit(kind: i32, arg: i32, r: RectF) {
    a().hits.push(Hit { kind, arg, r });
}

fn eh_audio(x: &str) -> bool {
    matches!(x, "mp3" | "m4a" | "flac" | "wav" | "aac" | "ogg" | "wma" | "aif" | "aiff" | "opus")
}
fn read_song(path: &str) -> Song {
    let mut s = Song { path: path.into(), ..Default::default() };
    if let Some(ps) = property_store(path) {
        s.title = prop_text(&ps, &PKEY_Title);
        s.artist = prop_text(&ps, &PKEY_Music_Artist);
        if s.artist.is_empty() {
            s.artist = prop_text(&ps, &PKEY_Music_AlbumArtist);
        }
        s.album = prop_text(&ps, &PKEY_Music_AlbumTitle);
        s.secs = prop_u64(&ps, &PKEY_Media_Duration) as f64 / 1e7;
        s.track = prop_u64(&ps, &PKEY_Music_TrackNumber) as u32;
    }
    if s.title.is_empty() {
        let p = std::path::Path::new(path);
        s.title = p.file_stem().map(|x| x.to_string_lossy().into_owned()).unwrap_or_default();
    }
    if s.artist.is_empty() {
        s.artist = tr("Artista Desconhecido");
    }
    if s.album.is_empty() {
        s.album = tr("Álbum Desconhecido");
    }
    s
}
fn scan() {
    let h = wnd().0 as usize;
    std::thread::spawn(move || unsafe {
        let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
        let root = SHGetKnownFolderPath(&FOLDERID_Music, KNOWN_FOLDER_FLAG(0), None).map(|p| {
            let s = from_pcwstr(PCWSTR(p.0));
            CoTaskMemFree(Some(p.0 as *const _));
            s
        });
        let mut v = Vec::new();
        if let Ok(root) = root {
            let mut dirs = vec![std::path::PathBuf::from(root)];
            while let Some(d) = dirs.pop() {
                let Ok(rd) = std::fs::read_dir(&d) else { continue };
                for e in rd.flatten() {
                    let nome = e.file_name().to_string_lossy().into_owned();
                    let Ok(md) = e.metadata() else { continue };
                    use std::os::windows::fs::MetadataExt;
                    let at = md.file_attributes();
                    if nome.starts_with('.') || at & (FILE_ATTRIBUTE_HIDDEN.0 | FILE_ATTRIBUTE_SYSTEM.0) != 0 {
                        continue;
                    }
                    if md.is_dir() {
                        dirs.push(e.path());
                        continue;
                    }
                    let x = e.path().extension().map(|x| x.to_string_lossy().to_lowercase()).unwrap_or_default();
                    if !eh_audio(&x) {
                        continue;
                    }
                    let mut s = read_song(&e.path().to_string_lossy());
                    s.added = md.creation_time();
                    v.push(s);
                }
            }
        }
        v.sort_by_key(|s| s.title.to_lowercase());
        let p = Box::into_raw(Box::new(v));
        if PostMessageW(HWND(h as *mut _), WM_SCAN, WPARAM(0), LPARAM(p as isize)).is_err() {
            drop(Box::from_raw(p));
        }
    });
}
fn ask_art(album: &str, file: &str) {
    if !a().art_asked.insert(album.to_string()) {
        return;
    }
    let (album, file, h) = (album.to_string(), file.to_string(), wnd().0 as usize);
    std::thread::spawn(move || unsafe {
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
        let mut img = shell_thumbnail(&file, 300, SIIGBF_THUMBNAILONLY);
        if let Some((_, _, px)) = &mut img {
            for i in (3..px.len()).step_by(4) {
                px[i] = 255;
            }
        }
        CoUninitialize();
        let p = Box::into_raw(Box::new(ArtData { album, img }));
        if PostMessageW(HWND(h as *mut _), WM_ART, WPARAM(0), LPARAM(p as isize)).is_err() {
            drop(Box::from_raw(p));
        }
    });
}
fn art(i: usize) -> Option<ID2D1Bitmap> {
    let s = &a().songs[i];
    if let Some(b) = a().art.get(&s.album) {
        return b.clone();
    }
    let (al, p) = (s.album.clone(), s.path.clone());
    ask_art(&al, &p);
    None
}

// ---- reprodução
fn item(s: &Song) -> Result<MediaPlaybackItem> {
    let uri = Uri::CreateUri(&HSTRING::from(format!("file:///{}", s.path)))?;
    let it = MediaPlaybackItem::Create(&MediaSource::CreateFromUri(&uri)?)?;
    let dp = it.GetDisplayProperties()?;
    dp.SetType(MediaPlaybackType::Music)?;
    let mp = dp.MusicProperties()?;
    mp.SetTitle(&HSTRING::from(s.title.as_str()))?;
    mp.SetArtist(&HSTRING::from(s.artist.as_str()))?;
    mp.SetAlbumTitle(&HSTRING::from(s.album.as_str()))?;
    it.ApplyDisplayProperties(&dp)?;
    // a capa para o "Tocando Agora", em outra thread
    let gen_ = a().smtc_gen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
    let gen_ref = a().smtc_gen.clone();
    let path = s.path.clone();
    let it2 = AgileReference::new(&it)?;
    std::thread::spawn(move || {
        let r = (|| -> Result<()> {
            let f = StorageFile::GetFileFromPathAsync(&HSTRING::from(path.as_str()))?.get()?;
            let th = f.GetThumbnailAsyncOverloadDefaultOptions(ThumbnailMode::MusicView, 300)?.get()?;
            if th.Type()? == ThumbnailType::Image && gen_ == gen_ref.load(std::sync::atomic::Ordering::SeqCst) {
                let it = it2.resolve()?;
                let dp = it.GetDisplayProperties()?;
                dp.SetThumbnail(&RandomAccessStreamReference::CreateFromStream(&th)?)?;
                it.ApplyDisplayProperties(&dp)?;
            }
            Ok(())
        })();
        let _ = r;
    });
    Ok(it)
}
fn play_index(pos: i32) {
    if pos < 0 || pos as usize >= a().queue.len() {
        return;
    }
    a().pos = pos;
    let s = a().songs[a().queue[pos as usize]].clone();
    if let Some(p) = &a().player {
        if let Ok(it) = item(&s) {
            let _ = p.SetSource(&it);
            let _ = p.Play();
        }
    }
    let t = wz(&format!("{} — {}", s.title, s.artist));
    unsafe {
        let _ = SetWindowTextW(wnd(), pc(&t));
    }
    invalidate();
}
/// embaralha (Fisher-Yates com a semente do relógio) e põe `first` na frente
fn embaralha(q: &mut [usize], first: usize) {
    let mut x = (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u64) | 1;
    for i in (1..q.len()).rev() {
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        q.swap(i, (x % (i as u64 + 1)) as usize);
    }
    if let Some(k) = q.iter().position(|&v| v == first) {
        q.swap(0, k);
    }
}
fn play_from(list: &[usize], mut start: usize) {
    a().queue = list.to_vec();
    a().orig = list.to_vec();
    if list.is_empty() {
        return;
    }
    // um índice fora da lista (linha apagada, álbum vazio, clique depois de uma busca) começava o pânico aqui
    start = start.min(list.len() - 1);
    if a().shuffle {
        let first = list[start];
        embaralha(&mut a().queue, first);
        start = 0;
    }
    play_index(start as i32);
}
/// issue #477: o aleatório vale na hora. Antes só mudava a opção, que só contava ao começar a tocar uma lista nova (por
/// isso "depois de uma busca funciona"). Ligado: o resto da fila é embaralhado e a música atual continua; desligado: a
/// ordem de antes volta, a partir da música atual.
fn alterna_aleatorio() {
    let ap = a();
    ap.shuffle = !ap.shuffle;
    if ap.pos < 0 || ap.pos as usize >= ap.queue.len() {
        return;
    }
    let atual = ap.queue[ap.pos as usize];
    if ap.shuffle {
        if ap.orig.len() != ap.queue.len() {
            ap.orig = ap.queue.clone();
        }
        embaralha(&mut ap.queue, atual);
        ap.pos = 0;
    } else if !ap.orig.is_empty() {
        ap.queue = ap.orig.clone();
        ap.pos = ap.queue.iter().position(|&v| v == atual).unwrap_or(0) as i32;
    }
}
fn playing() -> bool {
    a().player.as_ref().and_then(|p| p.PlaybackSession().ok()).and_then(|s| s.PlaybackState().ok()).map(|s| s == MediaPlaybackState::Playing).unwrap_or(false)
}
fn toggle() {
    if a().pos < 0 {
        if !a().rows.is_empty() {
            let r = a().rows.clone();
            play_from(&r, a().sel_row.max(0) as usize);
        }
        return;
    }
    if let Some(p) = &a().player {
        let _ = if playing() { p.Pause() } else { p.Play() };
    }
    invalidate();
}
fn next(d: i32) {
    if a().queue.is_empty() {
        return;
    }
    let mut p = a().pos + d;
    if p >= a().queue.len() as i32 {
        if a().repeat == 1 {
            p = 0;
        } else {
            if let Some(pl) = &a().player {
                let _ = pl.Pause();
            }
            return;
        }
    }
    play_index(p.max(0));
}
fn play_file(path: &str) {
    if path.is_empty() {
        return;
    }
    let idx = match a().songs.iter().position(|s| s.path.eq_ignore_ascii_case(path)) {
        Some(i) => i,
        None => {
            a().songs.push(read_song(path));
            a().songs.len() - 1
        }
    };
    let dir = |p: &str| p.rsplit_once('\\').map(|(d, _)| d.to_lowercase()).unwrap_or_default();
    let d0 = dir(path);
    let mut q: Vec<usize> = (0..a().songs.len()).filter(|&i| dir(&a().songs[i].path) == d0).collect();
    let mut start = q.iter().position(|&i| i == idx).unwrap_or(usize::MAX);
    if start == usize::MAX {
        q = vec![idx];
        start = 0;
    }
    // issue #2: um arquivo aberto por fora (duplo clique, "Abrir com") também entra na fila. Antes ele escrevia a
    // queue na mão e tocava em ordem, mesmo com o aleatório ligado; agora passa por play_from, que respeita o modo.
    play_from(&q, start);
}
fn session() -> Option<MediaPlaybackSession> {
    a().player.as_ref()?.PlaybackSession().ok()
}
fn pos_secs() -> f64 {
    session().and_then(|s| s.Position().ok()).map(|t| t.Duration as f64 / 1e7).unwrap_or(0.0)
}
fn len_secs() -> f64 {
    session().and_then(|s| s.NaturalDuration().ok()).map(|t| t.Duration as f64 / 1e7).unwrap_or(0.0)
}
fn seek(secs: f64) {
    if let Some(s) = session() {
        let _ = s.SetPosition(TimeSpan { Duration: (secs * 1e7) as i64 });
    }
}
fn mmss(s: f64) -> String {
    let t = s as i64;
    format!("{}:{:02}", t / 60, t % 60)
}

// ---- listas
fn matches(x: &str) -> bool {
    a().search.is_empty() || x.to_lowercase().contains(&a().search.to_lowercase())
}
fn albums() -> Vec<String> {
    let mut v: Vec<String> = a()
        .songs
        .iter()
        .filter(|s| (a().artist_sel.is_empty() || s.artist == a().artist_sel) && (matches(&s.album) || matches(&s.artist)))
        .map(|s| s.album.clone())
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect();
    v.sort();
    v
}
fn artists() -> Vec<String> {
    a().songs.iter().filter(|s| matches(&s.artist)).map(|s| s.artist.clone()).collect::<BTreeSet<_>>().into_iter().collect()
}
fn build_rows() {
    let a = a();
    let mut rows: Vec<usize> = (0..a.songs.len())
        .filter(|&i| {
            let s = &a.songs[i];
            !(a.view == 1 && !a.artist_sel.is_empty() && s.artist != a.artist_sel)
                && !(a.view == 2 && !a.album_sel.is_empty() && s.album != a.album_sel)
                && (matches(&s.title) || matches(&s.artist) || matches(&s.album))
        })
        .collect();
    if a.sort_by != 0 && (a.view == 3 || a.view == 0) {
        let k = a.sort_by;
        rows.sort_by_key(|&i| {
            let s = &a.songs[i];
            match k {
                1 => s.title.to_lowercase(),
                2 => s.artist.to_lowercase(),
                _ => s.album.to_lowercase(),
            }
        });
    }
    if a.view == 0 {
        rows.sort_by(|&x, &y| a.songs[y].added.cmp(&a.songs[x].added));
    }
    if a.view == 2 && !a.album_sel.is_empty() {
        rows.sort_by_key(|&i| a.songs[i].track);
    }
    if a.view == 0 {
        rows.truncate(100);
    }
    a.rows = rows;
}
fn view_title(i: usize) -> String {
    if i == 3 {
        tr_pick("Músicas", "Songs")
    } else {
        tr(TITLES[i])
    }
}

fn paint_side_golden(sz: (f32, f32), dark: bool, text_c: Cor, gray: Cor, pink: Cor) {
    let sb = a().sb;
    fill(rf(0.0, 0.0, sb, sz.1), sidebar_color(), 0.0);
    fill(rf(sb - 0.5, 0.0, sb, sz.1), if dark { rgb(0, 0, 0, 0.5) } else { rgb(0, 0, 0, 0.08) }, 0.0);
    text(&tr("Biblioteca"), tf("sec"), rf(16.0, 58.0, sb, 74.0), gray);
    for i in 0..4 {
        let cy = 92.0 + i as f32 * 32.0;
        let r = rf(10.0, cy - 16.0, sb - 10.0, cy + 16.0);
        let on = i as i32 == a().view;
        if on {
            fill(r, if dark { rgb(255, 255, 255, 0.10) } else { rgb(0, 0, 0, 0.07) }, 9.0);
        }
        text(ICONS[i], tf("icon"), rf(26.0, r.top, 48.0, r.bottom), pink);
        text(&view_title(i), tf(if on { "sideb" } else { "side" }), rf(55.0, r.top, r.right - 6.0, r.bottom), text_c);
        hit(1, i as i32, r);
    }
}
fn paint_bar_golden(sz: (f32, f32), dark: bool, text_c: Cor, gray: Cor, head: &str) {
    let (sb, tb) = (a().sb, a().tb);
    fill(rf(sb, 0.0, sz.0, tb), if dark { rgb(30, 30, 30, 1.0) } else { rgb(255, 255, 255, 1.0) }, 0.0);
    fill(rf(sb, tb - 0.5, sz.0, tb), if dark { rgb(255, 255, 255, 0.10) } else { rgb(0, 0, 0, 0.09) }, 0.0);
    text(head, tf("titleg"), rf(sb + 20.0, 0.0, sz.0 - 240.0, tb), if dark { rgb(255, 255, 255, 0.85) } else { rgb(0, 0, 0, 0.75) });
    let f = rf(sz.0 - 8.0 - 141.0, 8.0, sz.0 - 8.0, 44.0);
    glass_field(f, dark);
    icon_search(pt(f.left + 18.0, 26.0), gray, 0.85);
    let ph = match a().view {
        2 => tr("Buscar em Álbuns"),
        1 => tr("Buscar em Artistas"),
        _ => tr("Buscar em Músicas"),
    };
    let s = a().search.clone();
    text(if s.is_empty() { &ph } else { &s }, tf("small"), rf(f.left + 30.0, f.top, f.right - 10.0, f.bottom), if s.is_empty() { gray } else { text_c });
    hit(20, 0, f);
    let b = rf(f.left - 8.0 - 36.0, 8.0, f.left - 8.0, 44.0);
    glass_button(b, dark, false);
    for i in 0..3 {
        let w_ = 7.0 - i as f32 * 2.0;
        let cx = (b.left + b.right) / 2.0;
        line(pt(cx - w_, 21.0 + i as f32 * 5.0), pt(cx + w_, 21.0 + i as f32 * 5.0), text_c, 1.4);
    }
    bar_button(b);
    bar_button(f);
    hit(21, 0, b);
}
struct Btn {
    id: i32,
    g: &'static str,
    big: bool,
    on: bool,
}
fn botoes() -> [Btn; 5] {
    let a = a();
    [
        Btn { id: 0, g: "\u{E8B1}", big: false, on: a.shuffle },
        Btn { id: 1, g: "\u{E892}", big: false, on: false },
        Btn { id: 2, g: if playing() { "\u{E769}" } else { "\u{E768}" }, big: true, on: false },
        Btn { id: 3, g: "\u{E893}", big: false, on: false },
        Btn { id: 4, g: if a.repeat == 2 { "\u{E8ED}" } else { "\u{E8EE}" }, big: false, on: a.repeat != 0 },
    ]
}
fn tocando() -> Option<usize> {
    let a = a();
    (a.pos >= 0 && (a.pos as usize) < a.queue.len()).then(|| a.queue[a.pos as usize])
}
fn paint_player_golden(sz: (f32, f32), dark: bool, text_c: Cor, gray: Cor, pink: Cor) {
    let sb = a().sb;
    let cx = (sb + sz.0) / 2.0;
    let w_ = 702.0f32.min(sz.0 - sb - 40.0);
    let cap = rf(cx - w_ / 2.0, sz.1 - 18.0 - 56.0, cx + w_ / 2.0, sz.1 - 18.0);
    for k in (1..=4).rev() {
        let k = k as f32;
        fill(rf(cap.left - k, cap.top + k * 0.8, cap.right + k, cap.bottom + k * 1.6), col(0.0, 0.0, 0.0, if dark { 0.12 } else { 0.035 }), 28.0 + k);
    }
    fill(cap, if dark { rgb(44, 44, 46, 0.96) } else { rgb(252, 252, 252, 0.97) }, 28.0);
    stroke_rect(rf(cap.left + 0.25, cap.top + 0.25, cap.right - 0.25, cap.bottom - 0.25), if dark { rgb(255, 255, 255, 0.12) } else { rgb(0, 0, 0, 0.07) }, 27.75, 0.5);
    let cy = (cap.top + cap.bottom) / 2.0;
    let has = tocando().is_some();
    let off = if dark { rgb(255, 255, 255, 0.35) } else { rgb(0, 0, 0, 0.28) };
    let xs = [24.0, 56.0, 92.0, 128.0, 160.0];
    for (b, x) in botoes().iter().zip(xs) {
        let r = rf(cap.left + x - 15.0, cy - 15.0, cap.left + x + 15.0, cy + 15.0);
        text(b.g, tf(if b.big { "iconbig" } else { "icons" }), r, if b.on { pink } else if has || b.id == 2 { text_c } else { off });
        hit(5, b.id, r);
    }
    let mid = rf(cap.left + 190.0, cap.top + 6.0, cap.right - 150.0, cap.bottom - 6.0);
    if let Some(i) = tocando() {
        let s = a().songs[i].clone();
        let ar = rf(mid.left, cy - 20.0, mid.left + 40.0, cy + 20.0);
        match art(i) {
            Some(b) => unsafe { app2d::rt().DrawBitmap(&b, Some(&ar), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None) },
            None => fill(ar, if dark { rgb(72, 72, 74, 1.0) } else { rgb(220, 220, 225, 1.0) }, 6.0),
        }
        let tx = ar.right + 10.0;
        text(&s.title, tf("lcdl"), rf(tx, cy - 19.0, mid.right, cy - 3.0), text_c);
        text(&s.artist, tf("lcdsubl"), rf(tx, cy - 3.0, mid.right, cy + 11.0), gray);
        let (pos, len) = (pos_secs(), len_secs().max(s.secs));
        let bar_r = rf(tx, cy + 15.0, mid.right, cy + 17.5);
        fill(bar_r, if dark { rgb(255, 255, 255, 0.15) } else { rgb(0, 0, 0, 0.10) }, 1.25);
        if len > 0.0 {
            fill(rf(bar_r.left, bar_r.top, bar_r.left + (bar_r.right - bar_r.left) * (pos / len).clamp(0.0, 1.0) as f32, bar_r.bottom), gray, 1.25);
        }
        hit(6, 0, rf(bar_r.left, bar_r.top - 6.0, bar_r.right, bar_r.bottom + 6.0));
    } else {
        text("\u{EC4F}", tf("iconbig"), mid, off);
    }
    text("\u{E8FD}", tf("icons"), rf(cap.right - 140.0, cy - 15.0, cap.right - 112.0, cy + 15.0), text_c);
    let vol = rf(cap.right - 84.0, cy - 1.5, cap.right - 24.0, cy + 1.5);
    text("\u{E767}", tf("icons"), rf(vol.left - 26.0, cy - 12.0, vol.left - 4.0, cy + 12.0), text_c);
    fill(vol, if dark { rgb(255, 255, 255, 0.15) } else { rgb(0, 0, 0, 0.12) }, 1.5);
    fill(rf(vol.left, vol.top, vol.left + (vol.right - vol.left) * a().volume, vol.bottom), gray, 1.5);
    hit(7, 0, rf(vol.left - 4.0, cy - 10.0, vol.right + 4.0, cy + 10.0));
}

fn paint() {
    if !begin_paint() {
        return;
    }
    a().hits.clear();
    let dark = dark();
    let sz = size();
    let sz2 = (sz.width, sz.height);
    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 pink = rgb(250, 45, 72, 1.0);
    let linha = if dark { rgb(255, 255, 255, 0.07) } else { rgb(0, 0, 0, 0.06) };
    clear(if dark { rgb(30, 30, 30, 1.0) } else { rgb(255, 255, 255, 1.0) });
    let gg = bar() > 0.0;
    let (sb, tb, rowh) = (a().sb, a().tb, a().rowh);
    let mut x = sb + 20.0;
    let w_ = sz.width - 20.0;
    push_clip(rf(sb, tb, sz.width, sz.height));
    let mut y = tb + if gg { 30.0 } else { 14.0 } - a().scroll;
    let view = a().view;
    let mut head = view_title(view as usize);
    if view == 1 && !a().artist_sel.is_empty() {
        head = a().artist_sel.clone();
    }
    if view == 2 && !a().album_sel.is_empty() {
        head = a().album_sel.clone();
    }
    let dentro = (view == 1 && !a().artist_sel.is_empty()) || (view == 2 && !a().album_sel.is_empty());
    if gg {
        if dentro {
            let back = rf(x, y - 20.0, x + 160.0, y + 4.0);
            text(&format!("‹ {}", if view == 1 { tr("Artistas") } else { tr("Álbuns") }), tf("row"), back, pink);
            hit(8, 0, back);
            y += 14.0;
        }
    } else if dentro {
        let back = rf(x, y, x + 24.0, y + 34.0);
        text("‹", tf("head"), back, pink);
        hit(8, 0, back);
        text(&head, tf("head"), rf(x + 26.0, y, w_, y + 34.0), text_c);
    } else {
        text(&head, tf("head"), rf(x, y, w_, y + 34.0), text_c);
    }
    if !gg {
        y += 46.0;
    }
    if view == 2 && a().album_sel.is_empty() {
        let (cell, gap) = (if gg { 200.0 } else { 170.0 }, 22.0);
        if gg {
            x = sb + 33.0;
        }
        let cols = (((w_ - x + gap) / (cell + gap)) as i32).max(1);
        let al = albums();
        for (i, nome) in al.iter().enumerate() {
            let i = i as i32;
            let cx = x + (i % cols) as f32 * (cell + gap);
            let cy = y + (i / cols) as f32 * (cell + 52.0);
            let r = rf(cx, cy, cx + cell, cy + cell);
            if r.bottom > tb - 200.0 && r.top < sz.height + 100.0 {
                let first = a().songs.iter().position(|s| &s.album == nome);
                match first.and_then(art) {
                    Some(b) => unsafe { app2d::rt().DrawBitmap(&b, Some(&r), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None) },
                    None => {
                        fill(r, if dark { rgb(58, 58, 60, 1.0) } else { rgb(229, 229, 234, 1.0) }, 8.0);
                        text("\u{EC4F}", tf("iconbig"), r, gray);
                    }
                }
                text(nome, tf("row"), rf(cx, cy + cell + 6.0, cx + cell, cy + cell + 24.0), text_c);
                let artista = first.map(|f| a().songs[f].artist.clone()).unwrap_or_default();
                text(&artista, tf("small"), rf(cx, cy + cell + 24.0, cx + cell, cy + cell + 42.0), gray);
            }
            hit(3, i, r);
        }
    } else if view == 1 && a().artist_sel.is_empty() {
        for (i, ar) in artists().iter().enumerate() {
            let r = rf(x, y, w_, y + 44.0);
            circle(pt(x + 20.0, y + 22.0), 18.0, if dark { rgb(72, 72, 74, 1.0) } else { rgb(209, 209, 214, 1.0) }, true, 1.5);
            let ini = ar.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or("?".into());
            text(&ini, tf("rowr"), rf(x + 2.0, y, x + 38.0, y + 44.0), text_c);
            text(ar, tf("row"), rf(x + 52.0, y, w_, y + 44.0), text_c);
            fill(rf(x + 52.0, y + 44.0, w_, y + 45.0), linha, 0.0);
            hit(4, i as i32, r);
            y += 46.0;
        }
    } else {
        let ct = x + 30.0;
        let ca = x + (w_ - x) * 0.45;
        let cb = x + (w_ - x) * 0.68;
        let cd = w_ - 50.0;
        text(&tr("Título"), tf("small"), rf(ct, y, ca, y + 20.0), gray);
        text(&tr("Artista"), tf("small"), rf(ca, y, cb, y + 20.0), gray);
        text(&tr("Álbum"), tf("small"), rf(cb, y, cd, y + 20.0), gray);
        y += 24.0;
        let tocando_i = tocando();
        let rows = a().rows.clone();
        for (k, &si) in rows.iter().enumerate() {
            let r = rf(x, y, w_, y + rowh);
            if r.bottom > tb && r.top < sz.height {
                let s = a().songs[si].clone();
                let sel = k as i32 == a().sel_row;
                if sel {
                    fill(r, pink, 6.0);
                } else if k % 2 == 1 {
                    fill(r, linha, 6.0);
                }
                let tc = if sel { rgb(255, 255, 255, 1.0) } else { text_c };
                let sc_ = if sel { rgb(255, 255, 255, 0.85) } else { gray };
                if Some(si) == tocando_i {
                    text("\u{E767}", tf("icon"), rf(x + 4.0, y, x + 26.0, y + rowh), if sel { tc } else { pink });
                }
                text(&s.title, tf("row"), rf(ct, y, ca - 10.0, y + rowh), tc);
                text(&s.artist, tf("row"), rf(ca, y, cb - 10.0, y + rowh), sc_);
                text(&s.album, tf("row"), rf(cb, y, cd - 10.0, y + rowh), sc_);
                if s.secs > 0.0 {
                    text(&mmss(s.secs), tf("rowr"), rf(cd, y, w_ - 8.0, y + rowh), sc_);
                }
            }
            hit(2, k as i32, r);
            y += rowh;
        }
        if rows.is_empty() {
            text(&if a().scanning { tr("Lendo a biblioteca…") } else { tr("Nenhuma música na pasta Música.") }, tf("row"), rf(sb, tb + 80.0, sz.width, tb + 160.0), gray);
        }
    }
    pop_clip();
    if gg {
        paint_side_golden(sz2, dark, text_c, gray, pink);
        paint_bar_golden(sz2, dark, text_c, gray, &head);
        paint_player_golden(sz2, dark, text_c, gray, pink);
        end_paint();
        return;
    }
    fill(rf(0.0, tb, sb, sz.height), sidebar_color(), 0.0);
    text(&tr("Biblioteca"), tf("small"), rf(16.0, tb + 12.0, sb, tb + 30.0), gray);
    for i in 0..4 {
        let r = rf(8.0, tb + 36.0 + i as f32 * 32.0, sb - 8.0, tb + 64.0 + i as f32 * 32.0);
        if i as i32 == view {
            fill(r, if dark { rgb(255, 255, 255, 0.12) } else { rgb(0, 0, 0, 0.08) }, 7.0);
        }
        text(ICONS[i], tf("icon"), rf(r.left + 4.0, r.top, r.left + 28.0, r.bottom), pink);
        text(&view_title(i), tf("side"), rf(r.left + 34.0, r.top, r.right, r.bottom), text_c);
        hit(1, i as i32, r);
    }
    fill(rf(0.0, 0.0, sz.width, tb), if dark { rgb(44, 44, 46, 1.0) } else { rgb(246, 246, 248, 1.0) }, 0.0);
    fill(rf(0.0, tb - 1.0, sz.width, tb), if dark { rgb(0, 0, 0, 0.5) } else { rgb(0, 0, 0, 0.1) }, 0.0);
    let cy = tb / 2.0;
    let xs = [24.0, 60.0, 100.0, 140.0, 176.0];
    for (b, bx) in botoes().iter().zip(xs) {
        let r = rf(bx - 16.0, cy - 16.0, bx + 16.0, cy + 16.0);
        text(b.g, tf(if b.big { "iconbig" } else { "icon" }), r, if b.on { pink } else { text_c });
        hit(5, b.id, r);
    }
    let lx = 220.0f32.max(sz.width / 2.0 - 260.0);
    let lw = 520.0f32.min(sz.width - lx - 180.0);
    let lcd = rf(lx, 10.0, lx + lw, tb - 10.0);
    fill(lcd, if dark { rgb(58, 58, 60, 1.0) } else { rgb(232, 232, 236, 1.0) }, 6.0);
    if let Some(i) = tocando() {
        let s = a().songs[i].clone();
        let ar = rf(lcd.left, lcd.top, lcd.left + (lcd.bottom - lcd.top), lcd.bottom);
        match art(i) {
            Some(b) => unsafe { app2d::rt().DrawBitmap(&b, Some(&ar), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None) },
            None => fill(ar, if dark { rgb(72, 72, 74, 1.0) } else { rgb(209, 209, 214, 1.0) }, 6.0),
        }
        let tx = ar.right + 10.0;
        text(&s.title, tf("lcd"), rf(tx, lcd.top + 2.0, lcd.right - 10.0, lcd.top + 20.0), text_c);
        text(&format!("{} — {}", s.artist, s.album), tf("lcdsub"), rf(tx, lcd.top + 18.0, lcd.right - 10.0, lcd.top + 34.0), gray);
        let (pos, len) = (pos_secs(), len_secs().max(s.secs));
        let bar_r = rf(tx + 34.0, lcd.bottom - 9.0, lcd.right - 44.0, lcd.bottom - 6.0);
        fill(bar_r, if dark { rgb(255, 255, 255, 0.15) } else { rgb(0, 0, 0, 0.12) }, 1.5);
        if len > 0.0 {
            fill(rf(bar_r.left, bar_r.top, bar_r.left + (bar_r.right - bar_r.left) * (pos / len).clamp(0.0, 1.0) as f32, bar_r.bottom), gray, 1.5);
        }
        text(&mmss(pos), tf("lcdsub"), rf(tx, lcd.bottom - 16.0, tx + 32.0, lcd.bottom), gray);
        text(&mmss(len), tf("lcdsub"), rf(lcd.right - 40.0, lcd.bottom - 16.0, lcd.right - 4.0, lcd.bottom), gray);
        hit(6, 0, rf(bar_r.left, bar_r.top - 6.0, bar_r.right, bar_r.bottom + 6.0));
    } else {
        text("\u{EC4F}", tf("iconbig"), lcd, gray);
    }
    let vol = rf(sz.width - 150.0, cy - 2.0, sz.width - 30.0, cy + 2.0);
    text("\u{E767}", tf("icon"), rf(vol.left - 28.0, cy - 12.0, vol.left - 4.0, cy + 12.0), gray);
    fill(vol, if dark { rgb(255, 255, 255, 0.15) } else { rgb(0, 0, 0, 0.12) }, 2.0);
    let vx = vol.left + (vol.right - vol.left) * a().volume;
    fill(rf(vol.left, vol.top, vx, vol.bottom), gray, 2.0);
    circle(pt(vx, cy), 6.0, rgb(255, 255, 255, 1.0), true, 1.5);
    hit(7, 0, rf(vol.left - 4.0, cy - 10.0, vol.right + 4.0, cy + 10.0));
    end_paint();
}

fn set_volume(v: f32) {
    a().volume = v.clamp(0.0, 1.0);
    if let Some(p) = &a().player {
        let _ = p.SetVolume(a().volume as f64);
    }
}

extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    unsafe {
        match m {
            WM_PAINT => return wm_paint(h, paint),
            WM_ERASEBKGND => return LRESULT(1),
            WM_SIZE => {
                on_size(l);
                return LRESULT(0);
            }
            WM_DPICHANGED => {
                on_dpi(w_, l);
                return LRESULT(0);
            }
            WM_SETTINGCHANGE => {
                invalidate();
                return LRESULT(0);
            }
            WM_TIMER => {
                if a().pos >= 0 {
                    invalidate();
                }
                return LRESULT(0);
            }
            WM_SCAN => {
                let mut nv = *Box::from_raw(l.0 as *mut Vec<Song>);
                // a música de agora, pelo caminho: os índices mudam quando a varredura acha ou perde um arquivo
                let tocou = a().queue.get(a().pos as usize).map(|&i| a().songs[i].path.clone());
                let qp: Vec<String> = a().queue.iter().map(|&i| a().songs[i].path.clone()).collect();
                let op: Vec<String> = a().orig.iter().map(|&i| a().songs[i].path.clone()).collect();
                for s in &a().songs {
                    if !nv.iter().any(|n| n.path.eq_ignore_ascii_case(&s.path)) {
                        nv.push(s.clone());
                    }
                }
                a().songs = nv;
                a().queue = qp.iter().filter_map(|p| a().songs.iter().position(|s| s.path.eq_ignore_ascii_case(p))).collect();
                // issue #2: a ordem de antes do aleatório também é da fila antiga; sem remapear, desligar o botão ia para outra música (ou para fora da lista)
                a().orig = op.iter().filter_map(|p| a().songs.iter().position(|s| s.path.eq_ignore_ascii_case(p))).collect();
                a().pos = tocou.and_then(|p| a().queue.iter().position(|&i| a().songs[i].path.eq_ignore_ascii_case(&p))).map(|i| i as i32).unwrap_or(-1);
                a().scanning = false;
                build_rows();
                invalidate();
                return LRESULT(0);
            }
            WM_ART => {
                let d = *Box::from_raw(l.0 as *mut ArtData);
                let b = d.img.and_then(|(w0, h0, px)| app2d::s().rt.as_ref().and_then(|r| bitmap_bgra(r, w0, h0, &px)));
                a().art.insert(d.album, b);
                invalidate();
                return LRESULT(0);
            }
            WM_ENDED => {
                if a().repeat == 2 {
                    play_index(a().pos);
                } else {
                    next(1);
                }
                return LRESULT(0);
            }
            WM_SKIP => {
                if (w_.0 as isize) < 0 && pos_secs() > 3.0 {
                    seek(0.0);
                } else {
                    next(w_.0 as isize as i32);
                }
                invalidate();
                return LRESULT(0);
            }
            WM_COPYDATA => {
                let cd = &*(l.0 as *const COPYDATASTRUCT);
                if cd.dwData == 0x4D555343 && cd.cbData >= 2 {
                    let v = std::slice::from_raw_parts(cd.lpData as *const u16, cd.cbData as usize / 2);
                    play_file(&from_w(v));
                }
                if IsIconic(h).as_bool() {
                    let _ = ShowWindow(h, SW_RESTORE);
                }
                let _ = SetForegroundWindow(h);
                return LRESULT(1);
            }
            WM_MOUSEWHEEL => {
                a().scroll = (a().scroll - wheel_delta(w_) / 120.0 * 80.0).max(0.0);
                invalidate();
                return LRESULT(0);
            }
            WM_LBUTTONDOWN | WM_LBUTTONDBLCLK => {
                let s_ = sc();
                let (x, y) = (get_x_lparam(l) as f32 / s_, get_y_lparam(l) as f32 / s_);
                let dbl = m == WM_LBUTTONDBLCLK;
                for ht in a().hits.clone().iter().rev() {
                    if !in_rect(&ht.r, x, y) {
                        continue;
                    }
                    let a = a();
                    match ht.kind {
                        1 => {
                            a.view = ht.arg;
                            a.artist_sel.clear();
                            a.album_sel.clear();
                            a.scroll = 0.0;
                            a.sel_row = -1;
                            build_rows();
                        }
                        8 => {
                            if a.view == 1 {
                                a.artist_sel.clear();
                            } else {
                                a.album_sel.clear();
                            }
                            a.scroll = 0.0;
                            a.sel_row = -1;
                            build_rows();
                        }
                        20 => {
                            let s0 = a.search.clone();
                            field_open(rf(ht.r.left + 30.0, ht.r.top + 9.0, ht.r.right - 10.0, ht.r.bottom - 9.0), &s0, 12.0, false, |q, key| {
                                let a = self::a();
                                a.search = if key == VK_ESCAPE.0 as i32 { String::new() } else { q };
                                a.scroll = 0.0;
                                a.sel_row = -1;
                                build_rows();
                                invalidate();
                            });
                            return LRESULT(0);
                        }
                        21 => {
                            if let Ok(mm) = CreatePopupMenu() {
                                let nm = ["Ordem Padrão", "Título", "Artista", "Álbum"];
                                for (k, t) in nm.iter().enumerate() {
                                    append_menu(mm, MF_STRING | if a.sort_by == k as i32 { MF_CHECKED } else { MF_UNCHECKED }, 100 + k, &tr(t));
                                }
                                let scr = to_screen(h, (ht.r.left * s_) as i32, (ht.r.bottom * s_) as i32);
                                let c = TrackPopupMenu(mm, TPM_RETURNCMD, scr.x, scr.y, 0, h, None).0;
                                let _ = DestroyMenu(mm);
                                if c >= 100 {
                                    a.sort_by = c - 100;
                                    build_rows();
                                }
                            }
                        }
                        2 => {
                            a.sel_row = ht.arg;
                            if dbl {
                                let r = a.rows.clone();
                                play_from(&r, ht.arg as usize);
                            }
                        }
                        3 => {
                            a.album_sel = albums()[ht.arg as usize].clone();
                            a.scroll = 0.0;
                            a.sel_row = -1;
                            build_rows();
                            if dbl && !a.rows.is_empty() {
                                let r = a.rows.clone();
                                play_from(&r, 0);
                            }
                        }
                        4 => {
                            a.artist_sel = artists()[ht.arg as usize].clone();
                            a.scroll = 0.0;
                            a.sel_row = -1;
                            build_rows();
                        }
                        5 => match ht.arg {
                            0 => alterna_aleatorio(),
                            1 => {
                                if pos_secs() > 3.0 {
                                    seek(0.0)
                                } else {
                                    next(-1)
                                }
                            }
                            2 => toggle(),
                            3 => next(1),
                            _ => a.repeat = (a.repeat + 1) % 3,
                        },
                        6 => {
                            let len = len_secs();
                            if len > 0.0 {
                                let f = ((x - ht.r.left) / (ht.r.right - ht.r.left)) as f64;
                                seek(f.clamp(0.0, 1.0) * len);
                            }
                        }
                        7 => set_volume((x - ht.r.left - 4.0) / (ht.r.right - ht.r.left - 8.0)),
                        _ => continue,
                    }
                    invalidate();
                    return LRESULT(0);
                }
                return LRESULT(0);
            }
            WM_KEYDOWN => {
                let ctrl = key_down(VK_CONTROL.0);
                let k = w_.0 as u16;
                if k == VK_SPACE.0 {
                    toggle();
                } else if ctrl && k == VK_RIGHT.0 {
                    next(1);
                } else if ctrl && k == VK_LEFT.0 {
                    next(-1);
                } else if ctrl && k == VK_UP.0 {
                    set_volume(a().volume + 0.1);
                } else if ctrl && k == VK_DOWN.0 {
                    set_volume(a().volume - 0.1);
                } else if ctrl && k == 'W' as u16 {
                    let _ = DestroyWindow(h);
                } else if k == VK_RETURN.0 && a().sel_row >= 0 {
                    let r = a().rows.clone();
                    play_from(&r, a().sel_row as usize);
                } else if (k == VK_UP.0 || k == VK_DOWN.0) && !a().rows.is_empty() {
                    a().sel_row = (a().sel_row + if k == VK_UP.0 { -1 } else { 1 }).clamp(0, a().rows.len() as i32 - 1);
                }
                invalidate();
                return LRESULT(0);
            }
            WM_DESTROY => {
                if let Some(p) = &a().player {
                    let _ = p.Close();
                }
                PostQuitMessage(0);
                return LRESULT(0);
            }
            _ => {}
        }
        DefWindowProcW(h, m, w_, l)
    }
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let arg = args.get(1).filter(|a| !a.starts_with("--")).cloned().unwrap_or_default();
    if !app2d::modo_foto() {
        if let Some(other) = find_window("MusicaJanela") {
            unsafe {
                if !arg.is_empty() {
                    let t = wz(&arg);
                    let cd = COPYDATASTRUCT { dwData: 0x4D555343, cbData: (t.len() * 2) as u32, lpData: t.as_ptr() as *mut _ };
                    let mut r = 0usize;
                    SendMessageTimeoutW(other, WM_COPYDATA, WPARAM(0), LPARAM(&cd as *const _ as isize), SMTO_ABORTIFHUNG, 3000, Some(&mut r));
                } else {
                    if IsIconic(other).as_bool() {
                        let _ = ShowWindow(other, SW_RESTORE);
                    }
                    let _ = SetForegroundWindow(other);
                }
            }
            return;
        }
    }
    if !app2d::init() {
        std::process::exit(1);
    }
    *A.get() = Some(App { sb: 200.0, tb: 70.0, rowh: 28.0, scanning: true, view: 3, sel_row: -1, pos: -1, volume: 0.8, ..Default::default() });
    if let Some(v) = arg_valor("--visao") {
        a().view = v.parse().unwrap_or(3);
    }
    let disp = if has_font("SF Pro Display") { "SF Pro Display".to_string() } else { family() };
    let ic = icon_family();
    use DWRITE_TEXT_ALIGNMENT_CENTER as C;
    use DWRITE_TEXT_ALIGNMENT_LEADING as L;
    let f = |s: f32, w_: DWRITE_FONT_WEIGHT, al: DWRITE_TEXT_ALIGNMENT, fam: Option<&str>| fmt_full(s, w_, al, false, fam);
    let n = DWRITE_FONT_WEIGHT_NORMAL;
    let sb_ = DWRITE_FONT_WEIGHT_SEMI_BOLD;
    let t = &mut a().tf;
    for (k, v) in [
        ("side", f(13.0, n, L, None)),
        ("head", f(26.0, DWRITE_FONT_WEIGHT_BOLD, L, Some(&disp))),
        ("row", f(13.0, n, L, None)),
        ("rowr", f(13.0, n, C, None)),
        ("small", f(11.5, n, L, None)),
        ("lcd", f(12.5, sb_, C, None)),
        ("lcdsub", f(11.0, n, C, None)),
        ("icon", f(15.0, n, C, Some(&ic))),
        ("iconbig", f(24.0, n, C, Some(&ic))),
        ("sec", f(11.0, sb_, L, None)),
        ("sideb", f(13.0, sb_, L, None)),
        ("titleg", f(13.0, DWRITE_FONT_WEIGHT_BOLD, L, None)),
        ("icons", f(14.0, n, C, Some(&ic))),
        ("lcdl", f(12.0, sb_, L, None)),
        ("lcdsubl", f(11.0, n, L, None)),
    ] {
        t.insert(k, v);
    }
    set_bar_wanted(52.0);
    let aq = semaforo::aqua();
    let Some(h) = create_main("MusicaJanela", &tr("Música"), proc_, if aq { 1145 } else { 1150 }, if aq { 735 } else { 760 }) else { std::process::exit(1) };
    if bar() > 0.0 {
        a().tb = 52.0;
    }
    // o player do Windows (WinRT)
    let hw = h.0 as usize;
    let player = (|| -> Result<MediaPlayer> {
        let p = MediaPlayer::new()?;
        p.SetVolume(a().volume as f64)?;
        p.MediaEnded(&TypedEventHandler::new(move |_, _| {
            unsafe {
                let _ = PostMessageW(HWND(hw as *mut _), WM_ENDED, WPARAM(0), LPARAM(0));
            }
            Ok(())
        }))?;
        let cm = p.CommandManager()?;
        cm.NextBehavior()?.SetEnablingRule(MediaCommandEnablingRule::Always)?;
        cm.PreviousBehavior()?.SetEnablingRule(MediaCommandEnablingRule::Always)?;
        cm.NextReceived(&TypedEventHandler::new(move |_, a_: &Option<MediaPlaybackCommandManagerNextReceivedEventArgs>| {
            if let Some(a_) = a_ {
                a_.SetHandled(true)?;
            }
            unsafe {
                let _ = PostMessageW(HWND(hw as *mut _), WM_SKIP, WPARAM(1), LPARAM(0));
            }
            Ok(())
        }))?;
        cm.PreviousReceived(&TypedEventHandler::new(move |_, a_: &Option<MediaPlaybackCommandManagerPreviousReceivedEventArgs>| {
            if let Some(a_) = a_ {
                a_.SetHandled(true)?;
            }
            unsafe {
                let _ = PostMessageW(HWND(hw as *mut _), WM_SKIP, WPARAM(usize::MAX), LPARAM(0));
            }
            Ok(())
        }))?;
        Ok(p)
    })();
    a().player = player.ok();
    scan();
    unsafe {
        SetTimer(h, 1, 500, None);
    }
    show(h, SW_SHOWNORMAL);
    if !arg.is_empty() && !modo_foto() {
        play_file(&arg);
    }
    std::process::exit(run());
}