A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! launchpad.cpp: o Launchpad do Sequoia (medido no vídeo de referência, tela de 1080): papel de parede desfocado
//! cobrindo a tela, campo de busca no topo, grade de 7 × 5 apps com o nome embaixo, bolinhas de página e o Dock por
//! cima. Os apps vêm de shell:AppsFolder, lidos numa thread. Páginas deslizam numa mola; segurar um ícone faz a grade
//! tremer com o "×" que tira o app. No Tahoe não há Launchpad: abre o Spotlight no modo Aplicativos (as categorias
//! daqui são as fichas de lá). Leopard: sem campo até digitar, nomes em Lucida negrito com sombra.
//! Abrir e fechar são do compositor do Windows (DirectComposition): o papel de parede desfocado é uma camada parada e a
//! grade entra com mola e some sozinha, na placa de vídeo (launchpad_motor=composicao, o padrão); o outro motor é quadro
//! a quadro.
#![allow(dead_code)]
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
use comum::ctxmenu::{self, Item as MItem};
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::{BeginPaint, ClientToScreen, EndPaint, GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTOPRIMARY, PAINTSTRUCT};
use comum::windows::Win32::Graphics::DirectComposition::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::System::SystemInformation::GetTickCount64;
use comum::windows::Win32::UI::Input::Ime::ISC_SHOWUICOMPOSITIONWINDOW;
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;
use crate::composicao::Composicao;
use crate::{anim, apps, dock, liquid, log, menubar, shell, spotlight, ui};
static DESCEU: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[derive(Clone, Default)]
struct LApp {
name: String,
/// o que vem depois de shell:AppsFolder\ (AUMID ou caminho)
parsing: String,
w: u32,
h: u32,
px: Vec<u8>,
/// ícone do pacote do macOS
mac: bool,
/// app nosso sem atalho no Menu Iniciar: parsing é o caminho do exe (issue #174)
proprio: bool,
}
fn exe_de(p: &str) -> String {
if p.to_lowercase().ends_with(".exe") {
p.into()
} else {
String::new()
}
}
fn nome_de(a: &LApp) -> String {
apps::nome_visivel(&a.name, &exe_de(&a.parsing))
}
const WM_LP_READY: u32 = WM_APP + 20;
const WM_LP_FRAME: u32 = WM_APP + 21;
const COLS: usize = 7;
const ROWS: usize = 5;
const PER_PAGE: usize = COLS * ROWS;
const ANIM_MS: f64 = 220.0;
const SPRING_MS: f64 = 650.0;
const T_LP_CLOSE: usize = 9;
// ---- compositor
struct Cp {
/// por baixo da grade (que é a superfície de cima)
ct: IDCompositionTarget,
cback: IDCompositionVisual,
back_fx: IDCompositionEffectGroup,
fg_fx: IDCompositionEffectGroup,
fg_sc: IDCompositionScaleTransform,
back_surf: Option<IDCompositionSurface>,
back_key: String,
}
static CP: Global<Option<Cp>> = Global::new(None);
/// esta abertura usa o compositor
static COMP_ON: Global<bool> = Global::new(false);
fn comp_init() -> bool {
if CP.get().is_some() {
return true;
}
let Some(cd) = ui::comp() else { return false };
let r = unsafe {
(|| -> Result<Cp> {
let ct = cd.CreateTargetForHwnd(s().wnd, false)?;
let cback = cd.CreateVisual()?;
let (back_fx, fg_fx, fg_sc) = (cd.CreateEffectGroup()?, cd.CreateEffectGroup()?, cd.CreateScaleTransform()?);
cback.SetEffect(&back_fx)?;
ct.SetRoot(&cback)?;
Ok(Cp { ct, cback, back_fx, fg_fx, fg_sc, back_surf: None, back_key: String::new() })
})()
};
match r {
Ok(c) => {
*CP.get() = Some(c);
true
}
Err(_) => {
log!("launchpad: sem compositor");
false
}
}
}
fn motor_composicao() -> bool {
shell::setting("launchpad_motor", "composicao") == "composicao"
}
/// o papel de parede desfocado numa camada parada: refeito só se o papel (ou a tela) mudar
fn comp_backdrop(wpx: i32, hpx: i32) {
let Some(cp) = CP.get().as_mut() else { return };
let path = menubar::papel_de_parede();
let mut key = format!("{path}|{wpx}x{hpx}");
if let Ok(md) = std::fs::metadata(&path) {
if let Ok(t) = md.modified() {
key += &format!("|{:?}", t);
}
}
if cp.back_surf.is_some() && key == cp.back_key {
return;
}
let t0 = anim::now();
cp.back_surf = ui::comp_surface(wpx, hpx, &|dc: &ID2D1DeviceContext| unsafe { draw_backdrop(dc, &path, wpx as f32, hpx as f32) });
cp.back_key = key;
if let Some(sf) = &cp.back_surf {
unsafe {
let _ = cp.cback.SetContent(sf);
}
}
log!("launchpad: fundo desfocado refeito em {:.1} ms", anim::now() - t0);
}
/// abrir: aparece com a curva do Mac (220 ms) e a grade assenta numa mola leve (de 110 % para 100 %); fechar: some
/// suave (220 ms) e a grade cresce um pouco
fn comp_animate(closing: bool) {
let Some(cp) = CP.get().as_ref() else { return };
const K: usize = 24;
let d = (if closing { ANIM_MS } else { SPRING_MS } / 1000.0) as f32;
let (mut op, mut z) = (vec![0f32; K], vec![0f32; K]);
for k in 0..K {
let t = d * k as f32 / (K - 1) as f32;
let (ease, zoom_k) = if closing {
let e = 1.0 - anim::ease_in_out((t * 1000.0 / ANIM_MS as f32).min(1.0));
(e, e)
} else {
(anim::ease((t * 1000.0 / ANIM_MS as f32).min(1.0)), anim::spring(t, 0.42, 0.86))
};
op[k] = ease;
z[k] = 1.10 - 0.10 * zoom_k;
}
if !closing {
op[K - 1] = 1.0;
z[K - 1] = 1.0;
}
unsafe {
let mut rc = RECT::default();
let _ = GetClientRect(s().wnd, &mut rc);
let _ = cp.fg_sc.SetCenterX2(rc.right as f32 / 2.0);
let _ = cp.fg_sc.SetCenterY2(rc.bottom as f32 / 2.0);
if let Some(a) = ui::comp_curve(&op, d) {
let _ = cp.back_fx.SetOpacity(&a);
}
if let Some(a) = ui::comp_curve(&op, d) {
let _ = cp.fg_fx.SetOpacity(&a);
}
if let Some(a) = ui::comp_curve(&z, d) {
let _ = cp.fg_sc.SetScaleX(&a);
}
if let Some(a) = ui::comp_curve(&z, d) {
let _ = cp.fg_sc.SetScaleY(&a);
}
if let Some(c) = ui::comp() {
let _ = c.Commit();
}
}
}
const T_LP_HOLD: usize = 10;
/// a lista lida na thread; a janela troca em WM_LP_READY
struct Lista {
ready: bool,
pending: Option<Vec<LApp>>,
}
static LISTA: Mutex<Lista> = Mutex::new(Lista { ready: false, pending: None });
static SCANNING: AtomicBool = AtomicBool::new(false);
static SCAN_AGAIN: AtomicBool = AtomicBool::new(false);
static SEM_REAPROVEITAR: AtomicBool = AtomicBool::new(false);
static SCANNED_AT: AtomicU64 = AtomicU64::new(0);
static WND: std::sync::atomic::AtomicIsize = std::sync::atomic::AtomicIsize::new(0);
struct S {
wnd: HWND,
s: ui::GpuSurface,
all: Vec<LApp>,
bmps: Vec<Option<ID2D1Bitmap>>,
bmp_rt: usize,
style_key: String,
view: Vec<usize>,
page: usize,
press: i32,
query: String,
opened_at: f64,
closing_at: f64,
open: bool,
closing: bool,
page_from: f32,
page_at: f64,
jiggle: bool,
jiggle_at: f64,
cat: i32,
backdrop: Option<ID2D1Bitmap1>,
fmt_k: f32,
tf: Option<(IDWriteTextFormat, IDWriteTextFormat, IDWriteTextFormat)>,
ime: Composicao,
/// modo foto: tamanho da tela (DIP)
foto: Option<(f32, f32)>,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
SS.get().get_or_insert_with(|| S {
wnd: HWND::default(),
s: ui::GpuSurface::default(),
all: Vec::new(),
bmps: Vec::new(),
bmp_rt: 0,
style_key: String::new(),
view: Vec::new(),
page: 0,
press: -1,
query: String::new(),
opened_at: 0.0,
closing_at: 0.0,
open: false,
closing: false,
page_from: 0.0,
page_at: 0.0,
jiggle: false,
jiggle_at: 0.0,
cat: 0,
backdrop: None,
fmt_k: 0.0,
tf: None,
ime: Composicao::default(),
foto: None,
})
}
fn page_now() -> f32 {
let st = s();
if st.page_at <= 0.0 {
return st.page as f32;
}
let t = ((anim::now() - st.page_at) / 1000.0) as f32;
if t > 0.7 {
st.page_at = 0.0;
return st.page as f32;
}
st.page_from + (st.page as f32 - st.page_from) * anim::spring(t, 0.32, 0.9)
}
fn sliding() -> bool {
s().page_at > 0.0 && anim::now() - s().page_at < 700.0
}
/// troca sem animação (busca, categoria, abrir)
fn settle() {
let st = s();
st.page_from = st.page as f32;
st.page_at = 0.0;
}
fn split_bar(t: &str) -> Vec<String> {
t.split('|').filter(|x| !x.is_empty()).map(String::from).collect()
}
fn hidden(name: &str) -> bool {
split_bar(&shell::setting("launchpad_ocultos", "")).iter().any(|n| n == name)
}
/// Ferramentas do próprio Windows na lista de apps (System32, SysWOW64, Windows; Microsoft.Windows.*; pacotes do
/// editor cw5n1h2txyewy e os atalhos gerados das Ferramentas do Windows). Os apps comuns da Microsoft ficam.
pub fn app_do_sistema(name: &str, parsing: &str) -> bool {
let p = parsing.to_lowercase();
if p.contains("wacos") {
return false;
}
for pre in ["{1ac14e77-02e7-4e5d-b744-2eb1ae5198b7}", "{d65231b0-b2f1-4857-a4ce-a8e7c6ea7d27}", "{f38bf404-1d43-42f2-9305-67de0b28fc23}", "c:\\windows\\"] {
if p.starts_with(pre) {
return true;
}
}
if p.starts_with("microsoft.windows.") && !p.contains('!') {
return true;
}
if p.contains("_cw5n1h2txyewy!") {
return true;
}
let n = name.to_lowercase();
const W: &[&str] = &[
"ferramentas do windows", "windows tools", "painel de controle", "control panel", "windows powershell ise", "recuperação", "recovery drive",
"unidade de recuperação", "windows media player legacy", "internet explorer", "odbc", "iscsi", "desfragmentar", "defragment", "limpeza de disco",
"disk cleanup", "windows fax", "teclado virtual", "on-screen keyboard", "narrador", "narrator", "lupa", "magnifier", "executar", "run",
"task scheduler", "agendador de tarefas", "computer management", "gerenciamento do computador", "performance monitor", "monitor de desempenho",
"event viewer", "visualizador de eventos", "resource monitor", "monitor de recursos", "local security policy", "política de segurança local",
"hyper-v manager", "gerenciador do hyper-v", "task manager", "gerenciador de tarefas", "windows memory diagnostic", "diagnóstico de memória do windows",
];
W.contains(&n.as_str())
}
/// tirado do painel pelo usuário ou do sistema (launchpad_sem_sistema)
pub fn escondido(name: &str, parsing: &str) -> bool {
hidden(name) || (shell::setting("launchpad_sem_sistema", "1") == "1" && app_do_sistema(name, parsing))
}
pub fn ocultar(name: &str) {
if hidden(name) {
return;
}
let cur = shell::setting("launchpad_ocultos", "");
shell::set_setting("launchpad_ocultos", &if cur.is_empty() { name.to_string() } else { format!("{cur}|{name}") });
log!("launchpad: \"{name}\" oculto");
}
/// atalhos que não são apps (desinstaladores, manuais, sites)
fn skip(n: &str) -> bool {
let l = n.to_lowercase();
["uninstall", "desinstalar", "remover ", "readme", "leia-me", "read me", "website", "manual", "documentation", "documentação", "help", "ajuda", "release notes", "license", "licença"].iter().any(|w| l.contains(w))
}
/// thread de fundo: lista os apps e já carrega os ícones
fn loader() {
let mut found: Vec<LApp> = Vec::new();
unsafe {
let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
if let Ok(folder) = SHCreateItemFromParsingName::<_, _, IShellItem>(w!("shell:AppsFolder"), None) {
if let Ok(en) = folder.BindToHandler::<_, IEnumShellItems>(None, &BHID_EnumItems) {
let mut it = [None];
while en.Next(&mut it, None).is_ok() {
let Some(item) = it[0].take() else { break };
let (Ok(name), Ok(parse)) = (item.GetDisplayName(SIGDN_NORMALDISPLAY), item.GetDisplayName(SIGDN_PARENTRELATIVEPARSING)) else { continue };
let a = LApp { name: from_w(name.as_wide()), parsing: from_w(parse.as_wide()), ..Default::default() };
CoTaskMemFree(Some(name.0 as *const _));
CoTaskMemFree(Some(parse.0 as *const _));
if !skip(&a.name) {
found.push(a);
}
}
}
}
}
// issue #174: rodando direto do zip (sem o WacOSSetup) não há atalhos no Menu Iniciar e os nossos apps sumiam do
// Launchpad. Os que faltam entram pelo exe da pasta do Shell.
{
let dir = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf())).unwrap_or_default();
const NOSSOS: [(&str, &str); 18] = [
("WacOSFinder", "Finder"), ("WacOSSettings", "System Settings"), ("WacOSActivityMonitor", "Activity Monitor"),
("WacOSTerminal", "Terminal"), ("WacOSCalculator", "Calculator"), ("WacOSNotes", "Notes"),
("WacOSScreenshot", "Screenshot"), ("WacOSPreview", "Preview"), ("WacOSReminders", "Reminders"),
("WacOSCalendar", "Calendar"), ("WacOSTextEdit", "TextEdit"), ("WacOSClock", "Clock"),
("WacOSWeather", "Weather"), ("WacOSContacts", "Contacts"), ("WacOSPhotos", "Photos"),
("WacOSTimeMachine", "Time Machine"), ("WacOSMusic", "Music"), ("WacOSQuickTime", "QuickTime Player"),
];
for (exe, nome) in NOSSOS {
let caminho = dir.join(format!("{exe}.exe"));
if !caminho.exists() {
continue;
}
let low = format!("{exe}.exe").to_lowercase();
if !found.iter().any(|a| a.parsing.to_lowercase().ends_with(&low)) {
found.push(LApp { name: nome.to_string(), parsing: caminho.to_string_lossy().into_owned(), proprio: true, ..Default::default() });
}
}
}
found.sort_by_key(|a| a.name.to_lowercase());
found.dedup_by(|a, b| a.name.eq_ignore_ascii_case(&b.name));
// tamanho em que os ícones aparecem (108 de 1080 da altura da tela, com folga): guardar a 256 px custava ~90 MB
let keep = ((unsafe { GetSystemMetrics(SM_CYSCREEN) } as f32 * 0.1 * 1.15).ceil() as u32).clamp(96, 256);
// nova leitura: os ícones de quem já estava na lista são reaproveitados (menos quando um ícone próprio mudou)
let reload = {
let l = LISTA.lock().unwrap();
let reaproveita = !SEM_REAPROVEITAR.swap(false, Ordering::Relaxed);
let old: &Vec<LApp> = match &l.pending {
Some(p) => p,
None => &s().all,
};
if reaproveita && s().foto.is_none() {
let by: std::collections::HashMap<&str, &LApp> = old.iter().map(|o| (o.parsing.as_str(), o)).collect();
for a in found.iter_mut() {
if let Some(o) = by.get(a.parsing.as_str()).filter(|o| !o.px.is_empty()) {
a.w = o.w;
a.h = o.h;
a.px = o.px.clone();
a.mac = o.mac;
}
}
}
l.ready
};
let foto = s().foto.is_some();
for a in found.iter_mut() {
if !a.px.is_empty() || (foto && escondido(&a.name, &a.parsing)) {
continue;
}
let png = apps::pack_icon_by_name(&a.name, &exe_de(&a.parsing));
if let Some(mut i) = if png.is_empty() { None } else { ui::load_png(&png) } {
ui::downscale(&mut i, keep);
(a.w, a.h, a.px, a.mac) = (i.w, i.h, i.px, true);
continue;
}
if let Some(mut i) = ui::shell_image(&format!("shell:AppsFolder\\{}", a.parsing), 256, false) {
ui::trim_to_square(&mut i);
ui::downscale(&mut i, keep);
(a.w, a.h, a.px) = (i.w, i.h, i.px);
}
}
let n = found.len();
{
let mut l = LISTA.lock().unwrap();
l.pending = Some(found);
l.ready = true;
}
SCANNED_AT.store(unsafe { GetTickCount64() }, Ordering::Relaxed);
log!("launchpad: {n} apps{}", if reload { " (lista atualizada)" } else { "" });
let h = WND.load(Ordering::Relaxed);
if h != 0 {
unsafe {
let _ = PostMessageW(HWND(h as *mut _), WM_LP_READY, WPARAM(0), LPARAM(0));
}
}
unsafe { CoUninitialize() };
}
/// lê a lista de novo numa thread; pedidos durante uma leitura fazem mais uma no fim
fn scan() {
SCAN_AGAIN.store(true, Ordering::Relaxed);
if SCANNING.swap(true, Ordering::Relaxed) {
return;
}
std::thread::spawn(|| {
while SCAN_AGAIN.swap(false, Ordering::Relaxed) {
loader();
}
SCANNING.store(false, Ordering::Relaxed);
});
}
/// a lista nova entra aqui, na thread que cria e desenha os bitmaps
fn take_pending() {
let st = s();
if let Some(p) = LISTA.lock().unwrap().pending.take() {
st.bmps = vec![None; p.len()];
st.all = p;
st.press = -1;
}
}
// ---- categorias (as fichas do Apps do Tahoe): o Windows não diz a categoria de um app; sai do nome. 0 = todos
const CATS: [&str; 9] = ["Todos", "Produtividade", "Criatividade", "Utilitários", "Desenvolvimento", "Entretenimento", "Social", "Jogos", "Outros"];
const NCATS: i32 = 9;
const WORDS: [&[&str]; 8] = [
&[],
&["word", "excel", "powerpoint", "outlook", "onenote", "office", "teams", "notion", "notas", "notes", "calendário", "calendar", "mail", "acrobat", "pdf", "to do", "todo", "zoom", "chrome", "edge", "firefox", "opera", "brave", "vivaldi", "navegador"],
&[
"photoshop", "illustrator", "premiere", "after effects", "lightroom", "blender", "gimp", "krita", "paint", "ableton", " live ", "fl studio", "audacity", " obs", "davinci", "figma", "canva", "capcut", "reaper", "fotos", "photos", "câmera",
"camera", "clipchamp", "cubase", "studio one", "inkscape", "affinity", "vegas", "sony", "izotope", "native instruments", "serum", "splice",
],
&[
"terminal", "powershell", "prompt", "calculadora", "calculator", "monitor", "gerenciador", "ajustes", "settings", "configura", "painel de controle", "control panel", "7-zip", "winrar", "finder", "bloco de notas", "notepad",
"ferrament", "tool", "captura", "snipping", "relógio", "clock", "defender", "segurança", "update", "driver", "nvidia", "amd ", "intel", "realtek", "logitech", "bluetooth", "disco", "backup", "onedrive", "dropbox",
"google drive", "vpn", "utilit", "mapa de caracteres", "lupa", "teclado",
],
&["visual studio", "vs code", " code", "git", "python", "node", "android studio", "intellij", "pycharm", "docker", "wsl", "ubuntu", "claude", "cursor", "postman", "sql", "unity", "unreal", "godot", "java", "developer", "sdk"],
&["spotify", "netflix", "prime video", "youtube", "vlc", "música", "music", " tv", "filmes", "movies", "media player", "twitch", "deezer", "disney", "plex", "kindle", "podcast"],
&["discord", "whatsapp", "telegram", "instagram", "facebook", "messenger", "twitter", " x ", "signal", "skype", "slack", "reddit"],
&["steam", "epic games", "xbox", "game", "jogo", "minecraft", "roblox", "battle.net", "riot", "valorant", "league of", "ea app", "ubisoft", "gog", "solitaire", "paciência", "fortnite"],
];
fn category_of(name: &str) -> i32 {
let n = format!(" {} ", name.to_lowercase());
for (k, ws) in WORDS.iter().enumerate().skip(1) {
if ws.iter().any(|w| n.contains(w)) {
return k as i32;
}
}
NCATS - 1
}
pub fn category(name: &str) -> i32 {
category_of(name)
}
pub fn category_count() -> i32 {
NCATS
}
pub fn category_name(k: i32) -> String {
if (0..NCATS).contains(&k) {
tr(CATS[k as usize])
} else {
String::new()
}
}
fn filter() {
let st = s();
let q = st.query.to_lowercase();
let cats = liquid::on() && st.cat > 0;
st.view = (0..st.all.len())
.filter(|&i| {
let a = &st.all[i];
!(cats && category_of(&a.name) != st.cat) && !escondido(&a.name, &a.parsing) && (q.is_empty() || a.name.to_lowercase().contains(&q))
})
.collect();
st.page = st.page.min(pages() - 1);
settle();
}
fn pages() -> usize {
s().view.len().div_ceil(PER_PAGE).max(1)
}
/// geometria em DIPs: no vídeo (1080 de altura), colunas a cada 216, linhas a cada 166, primeira linha em 140,
/// ícones de 108 (com a margem do ícone do Mac), nome 67 abaixo do centro, busca de 300 × 30 em y = 29, bolinhas em 930
#[derive(Clone, Copy)]
struct Geo {
w: f32,
h: f32,
k: f32,
step: f32,
row_step: f32,
icon: f32,
top: f32,
left: f32,
}
fn layout() -> Geo {
let st = s();
let (w, h) = match st.foto {
Some(t) => t,
None => unsafe {
let mut rc = RECT::default();
let _ = GetClientRect(st.wnd, &mut rc);
let sc = ui::scale(st.wnd);
(rc.right as f32 / sc, rc.bottom as f32 / sc)
},
};
let k = h / 1080.0;
let step = 216.0 * k;
// launchpad_icones (issue #40): 1 grande (padrão), 0,85 médio, 0,7 pequeno; a grade fica
let tam = shell::setting("launchpad_icones", "1").replace(',', ".").parse::<f32>().unwrap_or(1.0).clamp(0.6, 1.0);
Geo { w, h, k, step, row_step: 166.0 * k, icon: 108.0 * k * tam, top: (if liquid::on() { 178.0 } else { 140.0 }) * k, left: w / 2.0 - step * (COLS - 1) as f32 / 2.0 }
}
fn cell_center(g: &Geo, k: usize) -> Ponto {
pt(g.left + (k % COLS) as f32 * g.step, g.top + (k / COLS) as f32 * g.row_step)
}
fn search_rect(g: &Geo) -> RectF {
if liquid::on() {
return rf(g.w / 2.0 - 240.0 * g.k, 24.0 * g.k, g.w / 2.0 + 240.0 * g.k, 64.0 * g.k);
}
rf(g.w / 2.0 - 150.0 * g.k, 29.0 * g.k, g.w / 2.0 + 150.0 * g.k, 59.0 * g.k)
}
fn dots_y(g: &Geo) -> f32 {
930.0 * g.k
}
fn hit_icon(g: &Geo, p: Ponto) -> i32 {
let st = s();
let first = st.page * PER_PAGE;
for k in 0..PER_PAGE.min(st.view.len().saturating_sub(first)) {
let c = cell_center(g, k);
if (p.x - c.x).abs() < g.step * 0.4 && p.y > c.y - g.icon * 0.5 && p.y < c.y + 80.0 * g.k {
return (first + k) as i32;
}
}
-1
}
fn make_formats(k: f32) {
let st = s();
if st.fmt_k == k && st.tf.is_some() {
return;
}
let label = ui::format(14.0 * k, DWRITE_FONT_WEIGHT_NORMAL, false, DWRITE_TEXT_ALIGNMENT_CENTER);
unsafe {
let dots = ui::dw().CreateEllipsisTrimmingSign(&label).ok();
let t = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
let _ = label.SetTrimming(&t, dots.as_ref());
}
st.tf = Some((label, ui::fmt(14.0 * k, DWRITE_FONT_WEIGHT_NORMAL), ui::format(13.0 * k, DWRITE_FONT_WEIGHT_NORMAL, true, DWRITE_TEXT_ALIGNMENT_LEADING)));
st.fmt_k = k;
}
/// pílulas das categorias (Tahoe), centradas abaixo da busca
fn cat_rects(g: &Geo) -> Vec<RectF> {
make_formats(g.k);
let tfs = s().tf.as_ref().unwrap().1.clone();
let (gap, h, y) = (8.0 * g.k, 30.0 * g.k, 80.0 * g.k);
let w: Vec<f32> = CATS.iter().map(|c| ui::text_width(&tfs, &tr(c)) + 30.0 * g.k).collect();
let total: f32 = w.iter().sum::<f32>() + gap * (w.len() - 1) as f32;
let mut x = g.w / 2.0 - total / 2.0;
w.iter()
.map(|&wi| {
let r = rf(x, y, x + wi, y + h);
x += wi + gap;
r
})
.collect()
}
/// papel de parede desfocado e escurecido, desenhado em `dc` (wpx × hpx)
unsafe fn draw_backdrop(dc: &ID2D1DeviceContext, path: &str, wpx: f32, hpx: f32) {
let mut base = Default::default();
dc.GetTransform(&mut base);
dc.FillRectangle(&rf(0.0, 0.0, wpx, hpx), &dc.CreateSolidColorBrush(&col(0.08, 0.12, 0.28, 1.0), None).unwrap()); // sem papel: o azul do vídeo
let img = if path.is_empty() { None } else { ui::load_photo(path, 2560) };
if let Some(i) = img {
if let Some(src) = ui::bitmap(&dc.cast().unwrap(), i.w, i.h, &i.px) {
let s_ = (wpx / i.w as f32).max(hpx / i.h as f32); // cobre a tela inteira
if let Ok(blur) = dc.CreateEffect(&CLSID_D2D1GaussianBlur) {
blur.SetInput(0, &src, true);
let _ = blur.SetValue(D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION.0 as u32, D2D1_PROPERTY_TYPE_FLOAT, &(45.0f32 / s_).to_le_bytes());
let _ = blur.SetValue(D2D1_GAUSSIANBLUR_PROP_BORDER_MODE.0 as u32, D2D1_PROPERTY_TYPE_ENUM, &(D2D1_BORDER_MODE_HARD.0 as u32).to_le_bytes());
dc.SetTransform(&mat::mul(&mat::mul(&mat::scale(s_, s_, 0.0, 0.0), &mat::trans((wpx - i.w as f32 * s_) / 2.0, (hpx - i.h as f32 * s_) / 2.0)), &base));
if let Ok(out) = blur.GetOutput() {
dc.DrawImage(&out, None, None, D2D1_INTERPOLATION_MODE_LINEAR, D2D1_COMPOSITE_MODE_SOURCE_OVER);
}
dc.SetTransform(&base);
}
}
}
if let Ok(br) = dc.CreateSolidColorBrush(&col(0.0, 0.0, 0.0, 0.22), None) {
dc.FillRectangle(&rf(0.0, 0.0, wpx, hpx), &br);
}
}
/// papel de parede desfocado do tamanho da tela (feito ao abrir)
fn build_backdrop(wpx: i32, hpx: i32) {
let st = s();
st.backdrop = None;
let Some(dc) = ui::gpu() else { return };
unsafe {
let props = 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, colorContext: std::mem::ManuallyDrop::new(None) };
let Ok(b) = dc.CreateBitmap(D2D_SIZE_U { width: wpx as u32, height: hpx as u32 }, None, 0, &props) else { return };
dc.SetTarget(&b);
dc.SetDpi(96.0, 96.0);
dc.BeginDraw();
dc.SetTransform(&mat::ident());
draw_backdrop(&dc, &menubar::papel_de_parede(), wpx as f32, hpx as f32);
let _ = dc.EndDraw(None, None);
dc.SetTarget(None);
st.backdrop = Some(b);
}
}
/// os ícones viram bitmaps no alvo de desenho atual; estilo dos ícones (Tahoe) ou cor de destaque mudou: refeitos
fn bmp(rt: &ID2D1RenderTarget, i: usize) -> Option<ID2D1Bitmap> {
let st = s();
let k = ui::chave_alvo(rt);
let sk = ui::icon_style_key();
if st.bmp_rt != k || st.style_key != sk || st.bmps.len() != st.all.len() {
st.bmps = vec![None; st.all.len()];
st.bmp_rt = k;
st.style_key = sk;
}
if st.bmps[i].is_none() && !st.all[i].px.is_empty() {
let a = &st.all[i];
let mut c = a.px.clone();
dock::cela(a.w, a.h, &mut c); // issue #45: o quadrado cinza, como no Dock
let sty = ui::icon_style();
if sty != "padrao" {
ui::style_icon(a.w, a.h, &mut c, &sty);
}
st.bmps[i] = ui::bitmap(rt, a.w, a.h, &c);
}
st.bmps[i].clone()
}
pub fn paint() {
let st = s();
if !st.open {
return;
}
let g = layout();
let k = if st.foto.is_some() { ui::foto_scale() } else { ui::scale(st.wnd) };
let Some(dc) = ui::gpu_begin(&mut st.s, (g.w * k).round() as i32, (g.h * k).round() as i32, k) else { return };
unsafe { paint_on(&dc, &g) };
ui::gpu_end(&mut st.s);
}
unsafe fn paint_on(dc: &ID2D1DeviceContext, g: &Geo) {
let st = s();
let rt: ID2D1RenderTarget = dc.cast().unwrap();
make_formats(g.k);
let (tf_label, tf_search, tf_icon) = st.tf.clone().unwrap();
let now = anim::now();
// abrir: aparece com a curva do Mac e os ícones assentam numa mola leve; fechar: some suave
let (mut ease, mut zoom_k);
if st.closing {
let t = ((now - st.closing_at) / ANIM_MS).min(1.0) as f32;
ease = 1.0 - anim::ease_in_out(t);
zoom_k = ease;
} else {
let t = ((now - st.opened_at) / 1000.0) as f32;
ease = anim::ease((t * 1000.0 / ANIM_MS as f32).min(1.0));
zoom_k = anim::spring(t, 0.42, 0.86);
}
if st.foto.is_some() || *COMP_ON.get() {
// o compositor anima a camada inteira (opacidade e escala): a grade é desenhada parada
ease = 1.0;
zoom_k = 1.0;
}
let mut base = Default::default();
dc.GetTransform(&mut base);
if st.foto.is_some() {
draw_backdrop(dc, &menubar::papel_de_parede(), g.w, g.h);
} else {
dc.Clear(Some(&col(0.0, 0.0, 0.0, 0.0)));
if let Some(b) = &st.backdrop {
dc.DrawBitmap(b, Some(&rf(0.0, 0.0, g.w, g.h)), ease, D2D1_INTERPOLATION_MODE_LINEAR, None, None);
}
}
let lp = D2D1_LAYER_PARAMETERS1 { contentBounds: rf(-1e7, -1e7, 1e7, 1e7), geometricMask: std::mem::ManuallyDrop::new(None), maskAntialiasMode: D2D1_ANTIALIAS_MODE_PER_PRIMITIVE, maskTransform: mat::ident(), opacity: ease, opacityBrush: std::mem::ManuallyDrop::new(None), layerOptions: D2D1_LAYER_OPTIONS1_NONE };
dc.PushLayer(&lp, None);
let z = 1.10 - 0.10 * zoom_k; // os ícones chegam um pouco maiores e assentam
dc.SetTransform(&mat::mul(&mat::scale(z, z, g.w / 2.0, g.h / 2.0), &base));
let mut zb = Default::default();
dc.GetTransform(&mut zb);
let Ok(br) = dc.CreateSolidColorBrush(&col(1.0, 1.0, 1.0, 1.0), None) else {
dc.PopLayer();
return;
};
let txt = |t: &str, tf: &IDWriteTextFormat, r: RectF, c: Cor| {
br.SetColor(&c);
dc.DrawText(&w(t), tf, &r, &br, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
};
// busca
let sr = search_rect(g);
let tahoe = liquid::on();
let leo_vazio = liquid::leopard() && st.query.is_empty();
let rad = if tahoe { (sr.bottom - sr.top) / 2.0 } else { 7.0 * g.k };
if tahoe {
liquid::tile(&rt, sr, rad, true, 1.2);
for (i, cr) in cat_rects(g).iter().enumerate() {
let pr = (cr.bottom - cr.top) / 2.0;
if i as i32 == st.cat {
br.SetColor(&col(1.0, 1.0, 1.0, 0.30));
dc.FillRoundedRectangle(&comum::rr(*cr, pr, pr), &br);
liquid::rim(&rt, *cr, pr, true, 0.9, 1.0, -1.0, -1.0);
} else {
liquid::tile(&rt, *cr, pr, true, 0.6);
}
let n = tr(CATS[i]);
let tw = ui::text_width(&tf_search, &n);
let cx = (cr.left + cr.right) / 2.0;
txt(&n, &tf_search, rf(cx - tw / 2.0, cr.top, cx + tw / 2.0 + 4.0, cr.bottom), col(1.0, 1.0, 1.0, if i as i32 == st.cat { 1.0 } else { 0.85 }));
}
} else if !leo_vazio {
br.SetColor(&col(1.0, 1.0, 1.0, 0.08));
dc.FillRoundedRectangle(&comum::rr(sr, rad, rad), &br);
br.SetColor(&col(1.0, 1.0, 1.0, 0.20));
dc.DrawRoundedRectangle(&comum::rr(sr, rad, rad), &br, 1.0, None);
}
if !leo_vazio {
let shown = if st.query.is_empty() { tr(if tahoe { "Buscar apps" } else { "Buscar" }) } else { st.query.clone() };
let (tw, gw) = (ui::text_width(&tf_search, &shown), 20.0 * g.k);
let tx = if tahoe {
sr.left + 16.0 * g.k
} else if st.query.is_empty() {
(sr.left + sr.right) / 2.0 - (tw + gw) / 2.0
} else {
sr.left + 10.0 * g.k
};
let c = col(1.0, 1.0, 1.0, if st.query.is_empty() { 0.50 } else { 0.92 });
txt("\u{E721}", &tf_icon, rf(tx, sr.top, tx + gw, sr.bottom), c);
txt(&shown, &tf_search, rf(tx + gw, sr.top, sr.right - 8.0, sr.bottom), c);
}
let ready = LISTA.lock().unwrap().ready || !st.all.is_empty();
if !ready {
txt(&tr("Carregando apps…"), &tf_label, rf(0.0, g.h / 2.0 - 20.0, g.w, g.h / 2.0 + 20.0), col(1.0, 1.0, 1.0, 0.6));
} else {
let px = page_now();
let p0 = px.floor().max(0.0) as usize;
let p1 = (px.ceil() as usize).min(pages() - 1);
thread_local!(static TF_LEO: IDWriteTextFormat = {
let f = ui::format_face("Lucida Sans Unicode", 12.0, DWRITE_FONT_WEIGHT_BOLD);
unsafe {
let _ = f.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
let _ = f.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
let d = ui::dw().CreateEllipsisTrimmingSign(&f).ok();
let t = DWRITE_TRIMMING { granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER, delimiter: 0, delimiterCount: 0 };
let _ = f.SetTrimming(&t, d.as_ref());
}
f
});
for pg in p0..=p1 {
let dx = (pg as f32 - px) * g.w; // a página desliza inteira
let first = pg * PER_PAGE;
for k in 0..PER_PAGE.min(st.view.len().saturating_sub(first)) {
let ai = st.view[first + k];
let mut c = cell_center(g, k);
c.x += dx;
if c.x < -g.step || c.x > g.w + g.step {
continue;
}
let art = if st.all[ai].mac { g.icon } else { g.icon * 0.80 };
let dr = rf(c.x - art / 2.0, c.y - art / 2.0, c.x + art / 2.0, c.y + art / 2.0);
if st.jiggle {
// balança uns 2 graus, cada um no seu ritmo
let tt = ((now - st.jiggle_at) / 1000.0) as f32;
let ang = 2.0 * (tt * 6.2832 * 3.4 + k as f32 * 1.7).sin();
dc.SetTransform(&mat::mul(&mat::rot(ang, c.x, c.y), &zb));
}
if let Some(b) = bmp(&rt, ai) {
// PR #518 (Enesuygurs): tremendo, a tela inteira é redesenhada a cada quadro e o cúbico de alta
// qualidade em ~35 ícones girados engasgava em notebook com duas GPUs; girando, o linear não se vê
dc.DrawBitmap(&b, Some(&dr), 1.0, if st.jiggle { D2D1_INTERPOLATION_MODE_LINEAR } else { D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC }, None, None);
}
if st.jiggle {
let r = 12.0 * g.k;
let xc = pt(dr.left + art * 0.12, dr.top + art * 0.12);
br.SetColor(&col(0.30, 0.30, 0.32, 0.95));
dc.FillEllipse(&ell(xc, r, r), &br);
br.SetColor(&col(1.0, 1.0, 1.0, 0.95));
dc.DrawEllipse(&ell(xc, r, r), &br, 1.2 * g.k, None);
let q = r * 0.42;
dc.DrawLine(pt(xc.x - q, xc.y - q), pt(xc.x + q, xc.y + q), &br, 2.0 * g.k, None);
dc.DrawLine(pt(xc.x - q, xc.y + q), pt(xc.x + q, xc.y - q), &br, 2.0 * g.k, None);
}
if (first + k) as i32 == st.press {
br.SetColor(&col(0.0, 0.0, 0.0, 0.35));
dc.FillRoundedRectangle(&comum::rr(dr, art * 0.2, art * 0.2), &br);
}
let lr = rf(c.x - g.step / 2.0 + 6.0, c.y + 57.0 * g.k, c.x + g.step / 2.0 - 6.0, c.y + 77.0 * g.k);
let nome = nome_de(&st.all[ai]);
if liquid::leopard() {
// Mac OS X: Lucida negrito com a sombra escura do Lion
let tf = TF_LEO.with(|t| t.clone());
txt(&nome, &tf, rf(lr.left, lr.top + 1.5, lr.right, lr.bottom + 1.5), col(0.0, 0.0, 0.0, 0.75));
txt(&nome, &tf, lr, col(1.0, 1.0, 1.0, 0.98));
} else {
txt(&nome, &tf_label, rf(lr.left, lr.top + 1.0, lr.right, lr.bottom + 1.0), col(0.0, 0.0, 0.0, 0.35));
txt(&nome, &tf_label, lr, col(1.0, 1.0, 1.0, 0.96));
}
if st.jiggle {
dc.SetTransform(&zb);
}
}
}
if st.view.is_empty() {
txt(&tr("Nenhum resultado"), &tf_label, rf(0.0, g.h / 2.0 - 20.0, g.w, g.h / 2.0 + 20.0), col(1.0, 1.0, 1.0, 0.6));
}
let n = pages();
if n > 1 {
let (y, x0) = (dots_y(g), g.w / 2.0 - (n - 1) as f32 * 12.0 * g.k);
for i in 0..n {
let on = (1.0 - (i as f32 - px).abs()).max(0.0); // a bolinha acende acompanhando o deslize
br.SetColor(&col(1.0, 1.0, 1.0, 0.35 + 0.55 * on));
dc.FillEllipse(&ell(pt(x0 + i as f32 * 24.0 * g.k, y), 4.0 * g.k, 4.0 * g.k), &br);
}
}
}
dc.SetTransform(&base);
dc.PopLayer();
}
fn close() {
let st = s();
let mut q = std::mem::take(&mut st.query);
st.ime.cancela(st.wnd, &mut q);
st.query = q;
if !st.open || st.closing {
return;
}
st.jiggle = false; // PR #518 (Enesuygurs): fechar também sai do modo tremendo (o relógio de quadros não fica ligado)
st.closing = true;
st.closing_at = anim::now();
if *COMP_ON.get() {
ui::frame_clock(st.wnd, WM_LP_FRAME, false);
comp_animate(true);
unsafe {
SetTimer(st.wnd, T_LP_CLOSE, ANIM_MS as u32 + 10, None);
}
return;
}
ui::frame_clock(st.wnd, WM_LP_FRAME, true);
}
fn launch(i: usize) {
let st = s();
if i >= st.all.len() {
return;
}
if st.all[i].proprio {
// app nosso sem atalho: o exe direto
unsafe {
ShellExecuteW(None, w!("open"), &HSTRING::from(st.all[i].parsing.as_str()), None, None, SW_SHOWNORMAL);
}
log!("launchpad: abrindo {}", st.all[i].name);
close();
return;
}
let target = format!("shell:AppsFolder\\{}", st.all[i].parsing);
log!("launchpad: abrindo {}", st.all[i].name);
if shell::open_calculator(&target) || apps::launch_no_occlusion(&target, "", "") || apps::activate_packaged(&target, "") {
close();
return;
}
unsafe {
let tw = wz(&target);
let mut pidl = std::ptr::null_mut();
if SHParseDisplayName(pc(&tw), None, &mut pidl, 0, None).is_ok() {
let pasta = wz(&shell::pasta_do_app(&target)); // jogos que só abrem da pasta deles (issue #38)
let mut se = SHELLEXECUTEINFOW { cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32, fMask: SEE_MASK_IDLIST, lpIDList: pidl as *mut _, nShow: SW_SHOWNORMAL.0, ..Default::default() };
if pasta.len() > 1 {
se.lpDirectory = pc(&pasta);
}
let _ = ShellExecuteExW(&mut se);
CoTaskMemFree(Some(pidl as *const _));
}
}
close();
}
fn lp_pt(l: LPARAM) -> Ponto {
let k = ui::scale(s().wnd);
pt(get_x_lparam(l) as f32 / k, get_y_lparam(l) as f32 / k)
}
/// PR #518 (Enesuygurs): o aperto longo que ligou o modo tremendo ainda não foi solto (o soltar dele não é um clique)
static JIGGLE_SOLTAR: AtomicBool = AtomicBool::new(false);
/// PR #518: tremendo, um quadro sim, um não
static PULA: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
/// PR #500 (Cstan0824): a soma dos passos da roda/touchpad no gesto atual
struct Roda {
x: i32,
y: i32,
at: u64,
usado: bool,
}
static RODA: Global<Roda> = Global::new(Roda { x: 0, y: 0, at: 0, usado: false });
/// onde o botão (ou o dedo) desceu e se já virou arrasto de página (issue #505; a mesma ideia do PR #501 de Cstan0824)
static ARRASTE: Global<Option<(Ponto, bool)>> = Global::new(None);
fn go_page(p: i32) {
let st = s();
let p = p.clamp(0, pages() as i32 - 1) as usize;
if p == st.page {
return;
}
st.page_from = page_now();
st.page_at = anim::now();
st.page = p;
ui::frame_clock(st.wnd, WM_LP_FRAME, true);
}
fn screen_pt(h: HWND, l: LPARAM) -> POINT {
let mut sp = POINT { x: get_x_lparam(l), y: get_y_lparam(l) };
unsafe {
let _ = ClientToScreen(h, &mut sp);
}
sp
}
/// botão direito: num app, o menu do shell do Windows (no visual do Mac) com Ocultar/Alterar Ícone/Restaurar/Renomear;
/// no fundo, Ocultar Apps do Sistema e Trazer de Volta
fn right_click(h: HWND, l: LPARAM) {
let st = s();
if st.jiggle {
st.jiggle = false; // PR #518 (Enesuygurs): o botão direito também sai do modo tremendo (antes era ignorado)
paint();
return;
}
let g = layout();
let hit = hit_icon(&g, lp_pt(l));
let sp = screen_pt(h, l);
if hit < 0 {
let sem = shell::setting("launchpad_sem_sistema", "1") == "1";
let mut items = vec![MItem::new(tr("Ocultar Apps do Sistema"), 1).checked(sem)];
let hid = split_bar(&shell::setting("launchpad_ocultos", ""));
if !hid.is_empty() {
let mut sub: Vec<MItem> = hid.iter().take(40).enumerate().map(|(k, n)| MItem::new(n.clone(), 100 + k as i32)).collect();
sub.push(MItem::sep());
sub.push(MItem::new(tr("Trazer Todos"), 99));
items.push(MItem::new(tr("Trazer de Volta"), 0).sub(sub));
}
let id = ctxmenu::show_items(h, sp, &items);
match id {
1 => shell::set_setting("launchpad_sem_sistema", if sem { "0" } else { "1" }),
99 => shell::set_setting("launchpad_ocultos", ""),
_ if id >= 100 && ((id - 100) as usize) < hid.len() => {
let mut v = hid;
v.remove((id - 100) as usize);
shell::set_setting("launchpad_ocultos", &v.join("|"));
}
_ => {}
}
if id != 0 {
filter();
}
paint();
return;
}
let i = st.view[hit as usize];
let (name, exe) = (st.all[i].name.clone(), exe_de(&st.all[i].parsing));
// ícone próprio (como o Obter Informações do Mac): escolher outro ou voltar ao original
let mut extra = vec![MItem::new(tr("Ocultar do Launchpad"), 2).icon(0xED1A), MItem::new(tr("Alterar Ícone…"), 3).icon(0xEB9F)];
if apps::has_custom_icon(&name, &exe) {
extra.push(MItem::new(tr("Restaurar Ícone Original"), 4).icon(0xE7A7));
}
extra.push(MItem::new(tr("Renomear…"), 5).icon(0xE8AC)); // pedido no Discord
// issue #556: fixar no Dock direto do Launchpad, sem abrir o app antes
let parsing = st.all[i].parsing.clone();
let no_dock = apps::list().iter().any(|a| a.pinned && (a.id == format!("aumid:{}", parsing.to_lowercase()) || (!exe.is_empty() && a.exe.eq_ignore_ascii_case(&exe))));
if !no_dock {
extra.push(MItem::new(tr("Manter no Dock"), 6).icon(0xE718));
}
let path = format!("shell:AppsFolder\\{}", st.all[i].parsing);
ctxmenu::extra_next(extra);
let shift = unsafe { GetKeyState(VK_SHIFT.0 as i32) } < 0;
let res = ctxmenu::show(h, sp, "shell:AppsFolder", &[path], shift);
ctxmenu::extra_next(Vec::new());
log!("launchpad: menu de {name}{}", if res.chosen { " (comando escolhido)" } else { "" });
if res.chosen && res.extra == 0 {
close();
return;
}
match res.extra {
2 => {
ocultar(&name);
filter();
paint();
}
3 => {
close();
apps::choose_icon(&name, &exe);
}
4 => apps::restore_icon(&name, &exe),
5 => {
close();
apps::renomear(&name, &exe);
}
6 => {
let ok = apps::pin_apps_folder(&parsing, &name);
log!("launchpad: {name} {} no Dock", if ok { "fixado" } else { "não pôde ser fixado" });
if ok {
dock::update();
}
}
_ => {}
}
}
fn query_changed() {
let st = s();
st.page = 0;
filter();
paint();
}
unsafe extern "system" fn proc_(h: HWND, m: u32, wp: WPARAM, mut l: LPARAM) -> LRESULT {
if matches!(m, WM_INITMENUPOPUP | WM_DRAWITEM | WM_MEASUREITEM | WM_MENUCHAR) {
// o menu do shell do app precisa das mensagens do dono
if let Some(r) = ctxmenu::forward_owner_msg(m, wp, l) {
return r;
}
}
let st = s();
match m {
WM_PAINT => {
let mut ps = PAINTSTRUCT::default();
BeginPaint(h, &mut ps);
let _ = EndPaint(h, &ps);
paint();
return LRESULT(0);
}
WM_LP_READY => {
take_pending();
filter();
paint();
return LRESULT(0);
}
WM_TIMER => {
if wp.0 == T_LP_CLOSE {
let _ = KillTimer(h, T_LP_CLOSE);
if st.closing {
st.closing = false;
st.open = false;
let _ = ShowWindow(h, SW_HIDE);
}
return LRESULT(0);
}
if wp.0 == T_LP_HOLD {
// segurou o ícone: modo tremendo
let _ = KillTimer(h, T_LP_HOLD);
if st.press >= 0 && !st.jiggle && !liquid::on() {
st.jiggle = true;
JIGGLE_SOLTAR.store(true, Ordering::Relaxed); // PR #518: o soltar deste aperto não é um clique
st.jiggle_at = anim::now();
st.press = -1;
ui::frame_clock(h, WM_LP_FRAME, true);
paint();
}
}
return LRESULT(0);
}
WM_LP_FRAME => {
ui::frame_ack(h, WM_LP_FRAME);
// PR #518 (Enesuygurs, issue #505): mensagem postada passa na frente do clique e da tecla. Tremendo, a tela
// leva mais que um quadro para desenhar e o próximo quadro já estava na fila: o clique nunca era lido e o
// Launchpad parecia travado. Com clique ou tecla esperando, este quadro fica para depois.
if (GetQueueStatus(QS_MOUSEBUTTON | QS_KEY) >> 16) != 0 {
return LRESULT(0);
}
// tremendo: um quadro sim, um não (o balanço é lento; metade do trabalho da GPU)
if st.jiggle && !st.closing && PULA.fetch_add(1, Ordering::Relaxed) & 1 == 1 {
return LRESULT(0);
}
let now = anim::now();
if st.closing && now - st.closing_at >= ANIM_MS {
ui::frame_clock(h, WM_LP_FRAME, false);
st.closing = false;
st.open = false;
let _ = ShowWindow(h, SW_HIDE);
return LRESULT(0);
}
if !st.closing && now - st.opened_at >= 650.0 && !sliding() && !st.jiggle {
ui::frame_clock(h, WM_LP_FRAME, false); // a mola assenta
}
paint();
return LRESULT(0);
}
WM_ACTIVATE => {
if wp.0 & 0xFFFF == WA_INACTIVE as usize {
if st.open && !st.closing {
log!("launchpad: perdeu o foco, fechando");
// pedido de 02/12/2026: um Win que o gancho não viu abriu o Iniciar/Pesquisa do Windows por cima do
// Launchpad; quem apertou Win queria fechar o nosso, então fecha o do Windows também (Esc)
let mut to = HWND(l.0 as *mut std::ffi::c_void);
if to.0.is_null() {
to = GetForegroundWindow();
}
let mut pid = 0u32;
GetWindowThreadProcessId(to, Some(&mut pid));
let exe = crate::apps::exe_of_pid(pid).to_lowercase();
if exe.ends_with("startmenuexperiencehost.exe") || exe.ends_with("searchhost.exe") {
log!("launchpad: o Win foi ao Windows com o Launchpad aberto; fechando o Iniciar também");
crate::spotlight::fecha_iniciar_windows();
}
}
close();
}
return LRESULT(0);
}
WM_LBUTTONDOWN => {
DESCEU.store(true, std::sync::atomic::Ordering::Relaxed);
*ARRASTE.get() = Some((lp_pt(l), false));
let g = layout();
st.press = if st.jiggle { -1 } else { hit_icon(&g, lp_pt(l)) };
if st.press >= 0 {
SetTimer(h, T_LP_HOLD, 650, None);
}
SetCapture(h);
paint();
return LRESULT(0);
}
WM_MOUSEMOVE => {
// issue #505: arrastar para o lado (dedo no tablet, ou o mouse) troca de página, como no Mac
if GetCapture() == h && !st.jiggle {
if let Some((p0, false)) = *ARRASTE.get() {
let p = lp_pt(l);
let (dx, dy) = (p.x - p0.x, p.y - p0.y);
if dx.abs() > 60.0 && dx.abs() > dy.abs() * 1.5 {
*ARRASTE.get() = Some((p0, true));
let _ = KillTimer(h, T_LP_HOLD);
st.press = -1;
go_page(st.page as i32 + if dx < 0.0 { 1 } else { -1 });
paint();
}
}
}
return LRESULT(0);
}
WM_LBUTTONUP => {
let _ = ReleaseCapture();
let _ = KillTimer(h, T_LP_HOLD);
if matches!(ARRASTE.get().take(), Some((_, true))) {
// foi um arrasto de página: não abre app nem fecha o Launchpad
DESCEU.store(false, std::sync::atomic::Ordering::Relaxed);
st.press = -1;
paint();
return LRESULT(0);
}
// issue #313: o botão desceu nesta janela? Senão o clique só a ativou, e o soltar já abre o app
let sem_descer = !DESCEU.swap(false, std::sync::atomic::Ordering::Relaxed);
let g = layout();
let p = lp_pt(l);
if st.jiggle && JIGGLE_SOLTAR.swap(false, Ordering::Relaxed) {
// PR #518: soltou o aperto longo que ligou o modo: fica tremendo
st.press = -1;
paint();
return LRESULT(0);
}
if st.jiggle {
// tremendo: o "×" tira o app; clique fora de um ícone sai do modo
let first = st.page * PER_PAGE;
let mut removed = None;
for k in 0..PER_PAGE.min(st.view.len().saturating_sub(first)) {
let ai = st.view[first + k];
let c = cell_center(&g, k);
let art = if st.all[ai].mac { g.icon } else { g.icon * 0.80 };
let (xx, yy) = (c.x - art / 2.0 + art * 0.12, c.y - art / 2.0 + art * 0.12);
if (p.x - xx).hypot(p.y - yy) < 16.0 * g.k {
removed = Some(ai);
}
}
if let Some(r) = removed {
let name = st.all[r].name.clone();
ocultar(&name);
filter();
} else {
// PR #518 (Enesuygurs): fora do "×", qualquer clique sai do modo (antes só fora dos ícones: com a
// tela cheia de ícones nada respondia e o Launchpad parecia travado, issue #505)
st.jiggle = false;
log!("launchpad: saiu do modo tremendo (clique)");
}
st.press = -1;
paint();
return LRESULT(0);
}
let hit = hit_icon(&g, p);
let pr = st.press;
st.press = -1;
let sr = search_rect(&g);
let cat = if liquid::on() { cat_rects(&g).iter().position(|r| p.x >= r.left && p.x < r.right && p.y >= r.top && p.y < r.bottom) } else { None };
if let Some(c) = cat {
st.cat = c as i32;
st.page = 0;
filter();
} else if hit >= 0 && (hit == pr || (pr < 0 && sem_descer)) {
launch(st.view[hit as usize]);
return LRESULT(0);
} else if !(p.x >= sr.left && p.x < sr.right && p.y >= sr.top && p.y < sr.bottom) {
// bolinhas trocam de página; qualquer outro lugar vazio fecha
let n = pages();
let (y, x0) = (dots_y(&g), g.w / 2.0 - (n - 1) as f32 * 12.0 * g.k);
let mut dot = false;
for i in 0..n {
if n > 1 && (p.x - (x0 + i as f32 * 24.0 * g.k)).abs() < 10.0 * g.k && (p.y - y).abs() < 10.0 * g.k {
go_page(i as i32);
dot = true;
}
}
if !dot && hit < 0 {
close();
}
}
paint();
return LRESULT(0);
}
WM_RBUTTONUP => {
right_click(h, l);
return LRESULT(0);
}
WM_CONTEXTMENU => return LRESULT(0),
WM_MOUSEWHEEL | WM_MOUSEHWHEEL => {
// PR #500 (Cstan0824): o touchpad manda muitos passos pequenos (e de lado, com dois dedos): soma até um
// passo inteiro e troca uma página por gesto. A roda não avisa quando o gesto acaba: uma pausa de 250 ms
// separa os gestos e a inércia fica na mesma página
let d = ((wp.0 >> 16) as u16 as i16) as i32;
if d == 0 {
return LRESULT(0);
}
let r = RODA.get();
let agora = GetTickCount64();
if agora.saturating_sub(r.at) >= 250 {
(r.x, r.y, r.usado) = (0, 0, false);
}
r.at = agora;
if r.usado {
return LRESULT(0);
}
let lado = m == WM_MOUSEHWHEEL;
let delta = if lado {
r.x += d;
r.x
} else {
r.y -= d;
r.y
};
if delta.abs() < WHEEL_DELTA as i32 {
return LRESULT(0);
}
r.usado = true;
go_page(st.page as i32 + if delta > 0 { 1 } else { -1 });
paint();
return LRESULT(0);
}
WM_KEYDOWN => {
let vk = VIRTUAL_KEY(wp.0 as u16);
if crate::shell::win_no_painel(vk.0) {
close(); // a tecla Windows com o Launchpad aberto: fecha (o Iniciar não abre)
return LRESULT(0);
}
if vk == VK_ESCAPE && st.jiggle {
st.jiggle = false;
} else if vk == VK_ESCAPE {
if !st.query.is_empty() {
st.query.clear();
filter();
} else {
close();
}
} else if vk == VK_RIGHT || vk == VK_NEXT {
go_page(st.page as i32 + 1);
} else if vk == VK_LEFT || vk == VK_PRIOR {
go_page(st.page as i32 - 1);
} else if vk == VK_RETURN && !st.view.is_empty() && !st.query.is_empty() {
// Enter na busca: abre o primeiro resultado
launch(st.view[(st.page * PER_PAGE).min(st.view.len() - 1)]);
return LRESULT(0);
}
paint();
return LRESULT(0);
}
WM_IME_SETCONTEXT => l = LPARAM(l.0 & !(ISC_SHOWUICOMPOSITIONWINDOW as isize)),
WM_IME_STARTCOMPOSITION | WM_IME_COMPOSITION | WM_IME_ENDCOMPOSITION => {
let mut mudou = false;
let mut q = std::mem::take(&mut st.query);
let tratou = st.ime.trata(h, m, l, &mut q, &mut mudou);
st.query = q;
if tratou {
if mudou {
query_changed();
}
return LRESULT(0);
}
}
WM_CHAR => {
if wp.0 == 8 {
st.query.pop();
} else if wp.0 >= 32 {
if let Some(c) = char::from_u32(wp.0 as u32) {
st.query.push(c);
}
} else {
return LRESULT(0);
}
query_changed();
return LRESULT(0);
}
_ => {}
}
DefWindowProcW(h, m, wp, l)
}
pub fn create(hi: HINSTANCE) -> bool {
let st = s();
unsafe {
RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("ShellLaunchpad"), hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() });
st.wnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP, w!("ShellLaunchpad"), w!("Launchpad"), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
}
if st.wnd.0.is_null() {
return false;
}
WND.store(st.wnd.0 as isize, Ordering::Relaxed);
unsafe {
// issue #505 (tablet): sem isto, segurar o dedo virava clique direito do Windows (o quadrado de "segurar" e um
// menu) e o Launchpad parecia travado; agora segurar faz a grade tremer, como no Mac. Sem os "flicks" também.
let _ = SetPropW(st.wnd, w!("MicrosoftTabletPenServiceProperty"), HANDLE(0x0001_0001 as *mut _));
}
apps::ours().push(st.wnd);
st.s.hwnd = st.wnd;
ui::gpu_soltar_escondida(&mut st.s); // escondido há 2 min: solta os buffers da tela cheia
scan();
true
}
pub fn rescan() {
scan();
}
pub fn icons_changed() {
SEM_REAPROVEITAR.store(true, Ordering::Relaxed);
scan();
}
pub fn is_open() -> bool {
s().open && !s().closing
}
/// antes da primeira abertura: o fundo desfocado (o papel de parede borrado, a parte cara do Launchpad)
pub fn warm() {
let st = s();
if liquid::on() || st.open || st.wnd.0.is_null() || st.foto.is_some() || !motor_composicao() || !comp_init() {
return;
}
let r = unsafe {
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
let _ = GetMonitorInfoW(MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY), &mut mi);
mi.rcMonitor
};
comp_backdrop(r.right - r.left, r.bottom - r.top);
}
pub fn toggle() {
let st = s();
// Tahoe: o Launchpad virou "Apps", o Spotlight no modo Aplicativos
if liquid::on() && !st.open {
spotlight::open_mode(1);
return;
}
log!("launchpad: Toggle (aberto={} fechando={})", st.open as i32, st.closing as i32);
if st.open && !st.closing {
close();
return;
}
let r = unsafe {
let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
let _ = GetMonitorInfoW(MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY), &mut mi);
mi.rcMonitor
};
unsafe {
let _ = KillTimer(st.wnd, T_LP_CLOSE); // abrindo de novo no meio do fechar
}
*COMP_ON.get() = !liquid::on() && motor_composicao() && comp_init();
if *COMP_ON.get() {
st.backdrop = None;
comp_backdrop(r.right - r.left, r.bottom - r.top);
} else {
build_backdrop(r.right - r.left, r.bottom - r.top);
}
st.query.clear();
st.page = 0;
settle();
st.jiggle = false;
*RODA.get() = Roda { x: 0, y: 0, at: 0, usado: false }; // PR #500: o gesto começa do zero
*ARRASTE.get() = None;
st.cat = 0;
let at = SCANNED_AT.load(Ordering::Relaxed);
if at != 0 && unsafe { GetTickCount64() } - at > 5 * 60 * 1000 {
scan();
}
take_pending();
filter();
st.open = true;
DESCEU.store(false, std::sync::atomic::Ordering::Relaxed);
st.closing = false;
st.opened_at = anim::now();
if *COMP_ON.get() {
// a grade pronta (parada) e as curvas entregues antes de a janela aparecer: o primeiro quadro já é o certo
unsafe {
let _ = SetWindowPos(st.wnd, HWND_TOPMOST, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOACTIVATE);
}
paint();
if let (Some(v), Some(cp)) = (&s().s.visual, CP.get().as_ref()) {
unsafe {
let _ = v.SetEffect(&cp.fg_fx);
let _ = v.SetTransform(&cp.fg_sc);
}
}
comp_animate(false);
unsafe {
let _ = SetWindowPos(st.wnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
let _ = SetForegroundWindow(st.wnd);
let _ = SetFocus(st.wnd);
}
dock::raise();
return;
}
unsafe {
if let Some(v) = &s().s.visual {
let _ = v.SetEffect(None::<&IDCompositionEffect>);
let _ = v.SetTransform(None::<&IDCompositionTransform>);
}
if let Some(cp) = CP.get().as_ref() {
let _ = cp.back_fx.SetOpacity2(0.0); // a camada do compositor fica de fora
}
if let Some(c) = ui::comp() {
let _ = c.Commit();
}
}
unsafe {
let _ = SetWindowPos(st.wnd, HWND_TOPMOST, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_SHOWWINDOW);
let _ = SetForegroundWindow(st.wnd);
let _ = SetFocus(st.wnd);
}
dock::raise(); // o Dock continua por cima
paint();
ui::frame_clock(st.wnd, WM_LP_FRAME, true);
}
/// modo foto: o Launchpad aberto cobrindo a tela (`busca` digitada; `tremendo` = modo de editar)
pub fn foto(tela_w: f32, tela_h: f32, busca: &str, tremendo: bool) {
let st = s();
st.foto = Some((tela_w, tela_h));
loader();
take_pending();
st.query = busca.into();
st.page = 0;
filter();
st.open = true;
DESCEU.store(false, std::sync::atomic::Ordering::Relaxed);
st.jiggle = tremendo;
st.jiggle_at = anim::now() - 130.0;
st.s.foto_pos = (0.0, 0.0);
paint();
}