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
10.3 KB
Raw Blame
//! Modo foto do porte: desenha a tela do Shell (papel de parede, barra de menus, Dock e painéis) num PNG, sem criar
//! janela, sem ganchos, sem esconder a barra do Windows e sem gravar nada (ajustes.txt, dock.txt, log).
//!
//! WacOSShell --foto=<png> [--tema=sequoia|tahoe|golden|leopard] [--escuro|--claro] [--tamanho=LxA] [--escala=N]
//!            [--painel=<nome>]
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::System::Com::*;
use comum::windows::Win32::UI::HiDpi::*;
use comum::*;

use crate::{apps, backdrop, dock, menubar, shell, ui};

fn val<'a>(args: &'a [String], k: &str) -> Option<&'a str> {
    args.iter().find_map(|a| a.strip_prefix(k))
}
pub fn rodar(out: &str, args: &[String]) -> Result<()> {
    unsafe {
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
        let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
    }
    shell::set_foto();
    // o tema da foto fica na memória (nada do ajustes.txt é gravado)
    let mut trocas: Vec<(&str, &str)> = Vec::new();
    if let Some(t) = val(args, "--tema=") {
        let (lg, gg, leo) = match t {
            "golden" => ("1", "1", "0"),
            "tahoe" => ("1", "0", "0"),
            "leopard" => ("0", "0", "1"),
            _ => ("0", "0", "0"),
        };
        trocas.extend([("liquid_glass", lg), ("golden_gate", gg), ("leopard", leo)]);
    }
    if args.iter().any(|a| a == "--escuro") {
        trocas.push(("tema", "escuro"));
    }
    if args.iter().any(|a| a == "--claro") {
        trocas.push(("tema", "claro"));
    }
    // --ajuste=chave=valor (pode repetir): troca um ajuste só na memória, para fotografar uma opção (logo_barra, barra_altura...)
    for a in args {
        if let Some((k, v)) = a.strip_prefix("--ajuste=").and_then(|x| x.split_once('=')) {
            trocas.push((k, v));
        }
    }
    shell::settings_foto(&trocas);
    // --ajuste=idioma=<código> fotografa noutro idioma
    if let Some((_, l)) = trocas.iter().find(|(k, _)| *k == "idioma") {
        comum::idioma::set(comum::idioma::from_code(l));
    }
    let st = backdrop::current();
    semaforo::forcar(semaforo::Estado { grafite: shell::setting("destaque", "azul").starts_with("grafite"), aqua: st.golden, liquid: st.liquid, leopard: st.leopard });
    if !ui::init() {
        return Err(E_FAIL.into());
    }
    let (w, h) = val(args, "--tamanho=").and_then(|t| t.split_once('x')).and_then(|(a, b)| Some((a.parse::<f32>().ok()?, b.parse::<f32>().ok()?))).unwrap_or((1440.0, 900.0));
    let sc: f32 = val(args, "--escala=").and_then(|v| v.parse().ok()).unwrap_or(1.0);
    ui::foto_begin((w * sc) as u32, (h * sc) as u32, sc)?;
    let dc = ui::foto().unwrap().dc.clone();
    // o papel de parede (cobrindo a tela, como o "Preencher" do Windows)
    unsafe {
        dc.SetTransform(&mat::ident());
        dc.Clear(Some(&col(0.12, 0.14, 0.2, 1.0)));
        if let Some(img) = ui::load_photo(&menubar::papel_de_parede(), 3840) {
            if let Some(bmp) = ui::bitmap(&dc.cast()?, img.w, img.h, &img.px) {
                let (pw, ph) = (w * sc, h * sc);
                let k = (pw / img.w as f32).max(ph / img.h as f32);
                let (dw, dh) = (img.w as f32 * k, img.h as f32 * k);
                let dst = rf((pw - dw) / 2.0, (ph - dh) / 2.0, (pw + dw) / 2.0, (ph + dh) / 2.0);
                // o papel desenhado em tela inteira vira a fonte do vidro (o backdrop desfoca a mesma imagem)
                if let Ok(full) = dc.CreateBitmap(D2D_SIZE_U { width: pw as u32, height: ph as u32 }, None, 0, &D2D1_BITMAP_PROPERTIES1 { pixelFormat: D2D1_PIXEL_FORMAT { format: comum::windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 96.0, dpiY: 96.0, bitmapOptions: D2D1_BITMAP_OPTIONS_TARGET, ..Default::default() }) {
                    let old = dc.GetTarget().ok();
                    dc.SetTarget(&full);
                    dc.DrawBitmap(&bmp, Some(&dst), 1.0, D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC, None, None);
                    if let Some(o) = old {
                        dc.SetTarget(&o);
                    }
                    dc.DrawBitmap(&full, None, 1.0, D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR, None, None);
                    backdrop::foto_fundo(&dc, &full.cast()?);
                } else {
                    dc.DrawBitmap(&bmp, Some(&dst), 1.0, D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC, None, None);
                }
            }
        }
    }
    // --mesa: os ícones da Área de Trabalho (lê a pasta e o mesa.txt, nunca grava)
    if args.iter().any(|a| a == "--mesa") {
        crate::mesa::foto((w * sc).round() as i32, (h * sc).round() as i32, sc);
    }
    // os widgets da mesa (casas e tamanhos do ajustes.txt, tempo do tempo.json; só leitura): --painel=widgets[:todos]
    if let Some(p) = val(args, "--painel=").filter(|p| *p == "widgets" || p.starts_with("widgets:")) {
        crate::widgets::foto(w, h, 25.0, 80.0, p == "widgets:todos");
    }
    apps::load(&format!("{}\\{}", shell::dir(), nomes::EXE_FINDER));
    let tela = RECT { left: 0, top: 0, right: (w * sc) as i32, bottom: (h * sc) as i32 };
    let mouse = val(args, "--mouse=").and_then(|v| v.parse().ok());
    // o Launchpad cobre a tela inteira (a barra some) e o Dock fica por cima: --painel=launchpad[:tremendo|<texto>]
    let painel = val(args, "--painel=").unwrap_or("");
    let launchpad = painel == "launchpad" || painel.starts_with("launchpad:");
    if launchpad {
        let extra = painel.split_once(':').map(|x| x.1).unwrap_or("");
        crate::launchpad::foto(w, h, if extra == "tremendo" { "" } else { extra }, extra == "tremendo");
    }
    dock::foto(tela, sc, mouse);
    // um painel aberto por cima: --painel=central[:wifi|bluetooth|foco|tela|som|editar]
    if let Some(p) = val(args, "--painel=") {
        let (nome, extra) = p.split_once(':').unwrap_or((p, ""));
        if nome == "notificacoes" || nome == "banner" {
            crate::notificacoes::foto(w, h, nome == "banner");
        } else if nome == "central" {
            crate::central::foto(w, if extra.is_empty() || extra == "editar" { None } else { Some(extra) }, extra == "editar");
        } else if nome == "boot" {
            crate::boot::foto(w, h, extra.parse::<f32>().unwrap_or(0.4));
        } else if nome == "sobre" {
            crate::sobre::foto(w, h);
        } else if nome == "novidades" {
            crate::novidades::foto(w, h, extra.parse::<usize>().unwrap_or(1).max(1) - 1); // --painel=novidades:<1..7>
        } else if nome == "menucontexto" {
            // o menu de contexto do Mac (comum::ctxmenu, o mesmo dos apps), com itens como os da mesa
            use comum::ctxmenu::{Dot, Item};
            let itens = vec![
                Item::new(tr("Nova Pasta"), 1),
                Item::sep(),
                Item::new(tr("Obter Informações"), 2),
                Item::new(tr("Alterar Fundo da Mesa…"), 3),
                Item::sep(),
                Item::new(tr("Usar Pilhas"), 4).checked(true),
                Item::new(tr("Ordenar Por"), 5).sub(vec![Item::new(tr("Nome"), 51)]),
                Item::new(tr("Limpar"), 6).shortcut("Ctrl+L"),
                Item::new(tr("Mostrar Opções de Visualização"), 7).disabled(extra == "desativado"),
                Item::sep(),
                Item { dots: [0xFF3B30, 0xFF9500, 0xFFCC00, 0x28CD41, 0x007AFF, 0xAF52DE, 0x8E8E93].iter().enumerate().map(|(i, c)| Dot { id: 100 + i as i32, rgb: *c, on: i == 4 }).collect(), ..Default::default() },
                Item::new(tr("Etiquetas"), 8),
            ];
            let k = ui::foto_scale();
            let mut s = ui::GpuSurface { foto_pos: (w * k * 0.30, h * k * 0.22), ..Default::default() };
            if let Some(dc) = ui::gpu_begin(&mut s, (300.0 * k) as i32, (400.0 * k) as i32, k) {
                unsafe { comum::ctxmenu::draw_on(&dc.cast().unwrap(), 0.0, 0.0, &itens, ui::dark(), 2, 1.0) };
                ui::gpu_end(&mut s);
            }
        } else if nome == "quicklook" {
            crate::quicklook::foto(w, h, extra);
        } else if nome == "missioncontrol" {
            crate::missioncontrol::foto(w, h, extra == "aberta");
        } else if nome == "bloqueio" {
            crate::bloqueio::foto(w, h, extra);
        } else if nome == "alerta" {
            crate::alertas::foto(w, h, extra == "tres");
        } else if nome == "menu" {
            crate::menus::foto(w, h);
        } else if nome == "progresso" {
            crate::progresso::foto(w, h);
        } else if nome == "siri" {
            crate::siri::foto(w, h, extra == "campo");
        } else if nome == "pilhas" {
            crate::pilhas::foto(w, h, extra);
        } else if nome == "dashboard" {
            crate::dashboard::foto(w, h, extra == "barra");
        } else if nome == "tempo" {
            crate::tempo::foto(w, h);
        } else if nome == "espacos" {
            crate::espacos::foto(w, h);
        } else if nome == "som" {
            crate::som::foto(w, h, extra == "aviso");
        } else if nome == "nota" {
            crate::notarapida::foto(w, h);
        } else if nome == "seletor" {
            crate::seletor::foto(w, h);
        } else if nome == "spotlight" {
            // --painel=spotlight[:apps|arquivos|acoes|circulos|<texto buscado>]
            let modo = match extra {
                "apps" => 1,
                "arquivos" => 2,
                "acoes" => 3,
                _ => 0,
            };
            let busca = if modo > 0 || extra == "circulos" { "" } else { extra };
            crate::spotlight::foto(w, h, busca, modo, extra == "circulos");
        }
    }
    // a barra por último: o item do painel aberto fica aceso
    if !launchpad && !painel.starts_with("boot") && painel != "espacos" && painel != "tempo" && !painel.starts_with("bloqueio") && !painel.starts_with("missioncontrol") {
        menubar::foto(w);
    }
    // a Ilha Dinâmica fica acima da barra: --painel=ilha[:notch|ilha|aviso[:parada|musica|aberta|timer|volume|aviso|ola|sistema]]
    if painel == "ilha" || painel.starts_with("ilha:") {
        let mut partes = painel.split(':').skip(1);
        let estilo = partes.next().unwrap_or("notch");
        let modo = partes.next().unwrap_or("musica");
        crate::ilha::foto(w, estilo, modo);
    }
    ui::foto_end(out)
}