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
61.8 KB
Raw Blame
//! siri.cpp: a Siri (issue #39): pergunta pelo Spotlight ("Perguntar à Siri") ou pelo ícone da barra, e a resposta num
//! painel de vidro no alto da tela, com o brilho colorido do Apple Intelligence. Não há servidor do WacOS: a pergunta vai
//! direto do PC para o serviço escolhido nos Ajustes (Gemini, Groq, OpenAI, Ollama local, os CLIs...), com a chave do
//! usuário (comum::siri). A chamada roda numa thread; a resposta de uma pergunta antiga é descartada. Esc ou clicar fora
//! fecha; Ctrl+C copia; digitar depois da resposta faz outra pergunta; o microfone dita (voz.rs).
#![allow(dead_code)]

use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Mutex;

use comum::siri::{self as sr, Formato, PROVEDORES};
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::*;
use comum::windows::Win32::System::Com::{CoInitializeEx, CoUninitialize, COINIT_MULTITHREADED};
use comum::windows::Win32::UI::Input::KeyboardAndMouse::*;
use comum::windows::Win32::UI::WindowsAndMessaging::*;
use comum::*;

use crate::{anim, apps, backdrop, liquid, log, shell, spotlight, ui, voz};

const WM_SIRI_FIM: u32 = WM_APP + 70;
const WM_SIRI_FRAME: u32 = WM_APP + 71;
const WM_SIRI_VOZ: u32 = WM_APP + 72;
const T_PONTOS: usize = 1;
const T_CURSOR: usize = 2;
const T_TESTE: usize = 9;
const PAD: f32 = 20.0;
const ORB: f32 = 30.0;
const R: f32 = 22.0;
/// folga em volta do painel para o brilho (os cliques nela atravessam)
const M: f32 = 28.0;

static NUM: AtomicI32 = AtomicI32::new(0);

// ---------------------------------------------------------------- a pergunta (thread)
/// os modelos insistem em Markdown: tira o que fica feio em texto puro
fn limpa(t: &str) -> String {
    let mut t = t.to_string();
    for m in ["**", "__", "`"] {
        t = t.replace(m, "");
    }
    let mut o = String::new();
    for l in t.split('\n') {
        let mut l = l.trim_start_matches('#');
        if let Some(r) = l.strip_prefix("* ").or_else(|| l.strip_prefix("- ")) {
            o.push_str("• ");
            l = r;
        }
        o.push_str(l.trim_start_matches(' ').trim_end_matches('\r'));
        o.push('\n');
    }
    o.trim().to_string()
}
/// o modelo não existe mais (ou nunca existiu) para esta conta
fn modelo_sumiu(status: u32, msg: &str) -> bool {
    if status != 400 && status != 404 {
        return false;
    }
    let l = msg.to_lowercase();
    ["no longer available", "not found", "does not exist", "not supported", "decommissioned", "deprecated", "invalid model", "unknown model", "model_not_found", "is not a valid model"].iter().any(|w_| l.contains(w_))
}
/// Gemini sem cota para a pesquisa no Google (issue #42): pergunta de novo sem a pesquisa e lembra até o Shell reiniciar
static SEM_BUSCA: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// outro modelo da lista para esta pergunta: estável, da mesma família (Flash no Gemini)
fn reserva(lista: &[String], atual: &str, gemini: bool) -> String {
    let mut alt = String::new();
    for m in lista {
        if m == atual || ["lite", "preview", "omni", "exp", "latest"].iter().any(|x| m.contains(x)) {
            continue;
        }
        if !gemini || m.contains("flash") {
            return m.clone();
        }
        if alt.is_empty() {
            alt = m.clone();
        }
    }
    alt
}
/// O que a Siri precisa saber do PC (issue #38: perguntou a hora e ela inventou 14:37 às 23:56): a data e a hora daqui,
/// com o fuso, e o tempo da cidade do widget (o mesmo que a mesa mostra). Vai junto com cada pergunta.
fn contexto() -> String {
    use comum::windows::Win32::Globalization::{GetDateFormatEx, GetTimeFormatEx, ENUM_DATE_FORMATS_FLAGS, TIME_FORMAT_FLAGS};
    use comum::windows::Win32::System::SystemInformation::GetLocalTime;
    use comum::windows::Win32::System::Time::{GetTimeZoneInformation, TIME_ZONE_INFORMATION};
    unsafe {
        let st = GetLocalTime();
        let (mut data, mut hora) = ([0u16; 120], [0u16; 40]);
        let loc = wz("en-US");
        let nd = GetDateFormatEx(pc(&loc), ENUM_DATE_FORMATS_FLAGS(0), Some(&st), pc(&wz("dddd, MMMM d, yyyy")), Some(&mut data), None);
        let nh = GetTimeFormatEx(pc(&loc), TIME_FORMAT_FLAGS(0), Some(&st), pc(&wz("HH:mm")), Some(&mut hora));
        let txt = |b: &[u16], n: i32| if n > 0 { from_w(&b[..n as usize - 1]) } else { String::new() };
        let mut tz = TIME_ZONE_INFORMATION::default();
        let z = GetTimeZoneInformation(&mut tz);
        let bias = -(tz.Bias + if z == 2 { tz.DaylightBias } else { 0 }) as i64; // 2 = TIME_ZONE_ID_DAYLIGHT
        let mut s = format!(
            "Current local date and time on the user's PC: {}, {} (UTC{}{:02}:{:02}).",
            txt(&data, nd),
            txt(&hora, nh),
            if bias < 0 { '-' } else { '+' },
            bias.abs() / 60,
            bias.abs() % 60
        );
        let t = crate::widgets::resumo_tempo();
        if !t.is_empty() {
            s.push(' ');
            s.push_str(&t);
        }
        s
    }
}
/// o executável do Codex. Primeiro o CLI que vem dentro do app Codex (Microsoft Store, o mais novo instalado): em 01/12/2026
/// o "codex" não estava no PATH e a cópia velha em %USERPROFILE%\.codex\.sandbox-bin (0.160) recusava o modelo padrão da
/// conta ("gpt-6.2-astra ... not supported"), então a Ilha não respondia; o do app (0.171) responde. Depois o do PATH,
/// o do npm e, por último, a cópia do .sandbox-bin.
pub fn acha_codex() -> Option<String> {
    let mut do_app: Vec<std::path::PathBuf> = std::fs::read_dir(r"C:\Program Files\WindowsApps")
        .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("OpenAI.Codex_"))).collect())
        .unwrap_or_default();
    // o nome traz a versão (OpenAI.Codex_26.1120.6357.0_x64__...): a maior primeiro
    do_app.sort_by_key(|p| {
        let n = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
        n.trim_start_matches("OpenAI.Codex_").split('_').next().unwrap_or("").split('.').map(|x| x.parse::<u64>().unwrap_or(0)).collect::<Vec<_>>()
    });
    if let Some(p) = do_app.iter().rev().map(|d| d.join("app").join("resources").join("codex.exe")).find(|p| p.is_file()) {
        return Some(p.to_string_lossy().into_owned());
    }
    let no_path = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).any(|d| ["codex.exe", "codex.cmd", "codex.bat"].iter().any(|n| d.join(n).is_file()))).unwrap_or(false);
    if no_path {
        return Some("codex".into());
    }
    let home = std::env::var_os("USERPROFILE").map(std::path::PathBuf::from)?;
    let candidatos = [home.join("AppData").join("Roaming").join("npm").join("codex.cmd"), home.join(".codex").join(".sandbox-bin").join("codex.exe")];
    candidatos.iter().find(|p| p.is_file()).map(|p| p.to_string_lossy().into_owned())
}
/// os modelos que a conta do Codex pode usar (o próprio Codex guarda em %USERPROFILE%\.codex\models_cache.json):
/// (id, nome), só os visíveis na lista
pub fn modelos_codex() -> Vec<(String, String)> {
    // guardado por 30 s: o seletor do Chat pergunta a cada quadro (02/12/2026: reler o arquivo de 586 KB pesava)
    static CACHE: std::sync::Mutex<Option<(u64, Vec<(String, String)>)>> = std::sync::Mutex::new(None);
    let agora = unsafe { comum::windows::Win32::System::SystemInformation::GetTickCount64() };
    if let Some((t, v)) = CACHE.lock().unwrap().as_ref() {
        if agora - t < 30000 {
            return v.clone();
        }
    }
    let v = modelos_codex_le();
    *CACHE.lock().unwrap() = Some((agora, v.clone()));
    v
}
fn modelos_codex_le() -> Vec<(String, String)> {
    let Some(home) = std::env::var_os("USERPROFILE") else { return Vec::new() };
    let Ok(t) = std::fs::read_to_string(std::path::PathBuf::from(home).join(".codex").join("models_cache.json")) else { return Vec::new() };
    let campo = |obj: &str, k: &str| -> Option<String> {
        let i = obj.find(&format!("\"{k}\""))?;
        let r = &obj[i + k.len() + 2..];
        let r = &r[r.find('"')? + 1..];
        Some(r[..r.find('"')?].to_string())
    };
    let mut v = Vec::new();
    // cada modelo começa no seu "slug"
    let partes: Vec<&str> = t.split("\"slug\"").skip(1).collect();
    for p in partes {
        let obj = format!("\"slug\"{p}");
        let (Some(id), vis) = (campo(&obj, "slug"), campo(&obj, "visibility").unwrap_or_default()) else { continue };
        if vis != "list" || !id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_')) {
            continue;
        }
        let nome = campo(&obj, "display_name").unwrap_or_else(|| id.clone());
        v.push((id, nome));
    }
    v
}
/// o Claude Code está instalado (o "claude" no PATH ou em %USERPROFILE%\.local\bin)
pub fn tem_claude() -> bool {
    let no_path = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).any(|d| ["claude.exe", "claude.cmd"].iter().any(|n| d.join(n).is_file()))).unwrap_or(false);
    no_path || std::env::var_os("USERPROFILE").map(|h| std::path::PathBuf::from(h).join(".local").join("bin").join("claude.exe").is_file()).unwrap_or(false)
}
/// o comando do CLI com o modelo escolhido (siri_modelo): "--model" no Claude Code, "-m" no Codex; sem modelo (ou um
/// que não é desse CLI), o padrão da conta do app
fn comando_cli(pv: &sr::Provedor) -> String {
    comando_cli_modelo(pv, None)
}
/// o comando com outro modelo no lugar do escolhido (o rápido das perguntas simples)
fn comando_cli_modelo(pv: &sr::Provedor, outro: Option<&str>) -> String {
    let m = outro.map(|x| x.to_string()).unwrap_or_else(|| shell::setting("siri_modelo", ""));
    let seguro = !m.is_empty() && m.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_'));
    if let Some(resto) = pv.caminho.strip_prefix("codex ") {
        let exe = acha_codex().unwrap_or_else(|| "codex".into());
        // com espaço no caminho, o cmd /c precisa das aspas de fora
        let exe_q = if exe.contains(' ') { format!("\"{exe}\"") } else { exe };
        let modelo = if seguro && !m.starts_with("claude") && !matches!(m.as_str(), "opus" | "sonnet" | "haiku" | "fable") { format!("-m {m} ") } else { String::new() };
        // --search: a busca na web do Codex (sem ela, perguntas de agora ficavam sem resposta)
        let resto = resto.replacen("exec ", &format!("--search exec {modelo}"), 1);
        // o modo agente: o Codex pode agir no PC (sem a caixa de areia só de leitura)
        let resto = if agente() { resto.replace("--sandbox read-only", "--sandbox danger-full-access") } else { resto };
        let c = format!("{exe_q} {resto}");
        return if c.starts_with('"') { format!("\"{c}\"") } else { c };
    }
    if pv.caminho.starts_with("claude ") {
        // 02/12/2026: no modo -p o Claude Code pede permissão para a busca na web e, sem ninguém para dizer sim, respondia
        // "a permissão para a busca na web foi negada". Só a pesquisa e a leitura de páginas ficam liberadas (nada de
        // comandos nem arquivos)
        let modelo = if seguro && (m.starts_with("claude-") || matches!(m.as_str(), "opus" | "sonnet" | "haiku" | "fable")) { format!("--model {m} ") } else { String::new() };
        if agente() {
            // o modo agente (02/12/2026, "igual você faz aqui"): todas as ferramentas, sem pedir permissão a cada passo;
            // o que for destrutivo ele descreve e pede confirmação na conversa (instruções em pergunta_cli)
            return format!("claude {modelo}--permission-mode bypassPermissions -p");
        }
        return format!("claude {modelo}--allowedTools WebSearch,WebFetch -p");
    }
    pv.caminho.to_string()
}
/// o modo agente da Ilha (ajuste ilha_ia_agente, desligado): o Claude Code / Codex pode rodar comandos, abrir apps e
/// mexer em arquivos para fazer o que a pessoa pede
fn agente() -> bool {
    shell::setting("ilha_ia_agente", "0") == "1"
}
fn pergunta_cli(pv: &sr::Provedor, q: &str, num: i32, proprio: Option<&str>) -> (String, bool) {
    let ag = agente() && proprio.is_some();
    sr::LIMITE_CLI.store(if ag { 600 } else { 180 }, Ordering::Relaxed);
    let instr = match proprio {
        Some(p) if ag => format!("{p}\n\nYou are running on the user's own Windows PC, in agent mode, with permission to run PowerShell commands, open apps and websites, and read, create and edit files in order to do what the user asks (their home folder is {}). Do the task yourself, then answer in one or two short sentences saying what you did. Before anything destructive or hard to undo (deleting or overwriting files, uninstalling, changing system or security settings, sending messages or e-mails, buying or paying, publishing, closing apps with unsaved work), do NOT do it: say exactly what you would do and ask the user to confirm; they will answer in the next message. Never type passwords. When the question needs current information, search the web first. Answer in plain words without links.\n\nUser: ", std::env::var("USERPROFILE").unwrap_or_default()),
        Some(p) => format!("{p}\n\nDo not run commands or edit files yourself. When the question needs current information (news, prices, versions, weather, results), search the web first and answer in plain words without links.\n\nUser: "),
        None => sr::com_instrucoes(&format!("Answer briefly and clearly, in the same language as the question, in plain text without Markdown. Do not run commands or edit files. When the question needs current information, search the web first and answer without links. {}", contexto())) + "\n\nQuestion: ",
    };
    let ultima = std::env::temp_dir().join("WacOS-Siri").join("ultima.txt");
    let _ = std::fs::remove_file(&ultima);
    // outra pergunta feita ou o painel fechado: o CLI é encerrado na hora
    let cancel = move || NUM.load(Ordering::SeqCst) != num;
    // a Ilha com o Claude Code: ele fica aberto entre as perguntas (mais rápido; siri_claude_aberto.rs)
    if proprio.is_some() && pv.caminho.starts_with("claude ") {
        // as perguntas simples vão para o Haiku (bem mais rápido); pedidos ao PC e perguntas longas, para o escolhido
        let cmd = comando_cli_modelo(pv, claude_modelo_para(q));
        if let Some((r, erro)) = claude_pergunta(&cmd, &format!("{instr}{q}"), &cancel, if ag { 600 } else { 180 }) {
            return if r.is_empty() { (String::new(), true) } else { (limpa(&r), erro) };
        }
        log!("siri: o Claude Code aberto não respondeu; abre um só para esta pergunta");
    }
    let (r, codigo, tempo) = sr::roda_cli(&comando_cli(pv), &(instr + q), Some(&cancel));
    if codigo == ERROR_CANCELLED.0 {
        return (String::new(), true); // descartada
    }
    log!("siri: {} -> código {codigo}, {} caracteres{}", pv.nome, r.len(), if tempo { " (passou do tempo)" } else { "" });
    if tempo {
        return (tr("O app demorou demais para responder."), true);
    }
    if codigo == 9009 || codigo == ERROR_FILE_NOT_FOUND.0 {
        return (format!("{} {}", tr("Não achei o app neste PC. Instale e entre na sua conta nele:"), pv.site), true);
    }
    // o Codex grava a última mensagem num arquivo (a saída tem o resto da conversa)
    let mut r = r;
    if let Ok(b) = std::fs::read(&ultima) {
        if !b.is_empty() && b.len() < 1 << 20 {
            r = String::from_utf8_lossy(&b).into_owned();
        }
        let _ = std::fs::remove_file(&ultima);
    }
    if codigo != 0 || r.is_empty() {
        let mut t = limpa(&r);
        if t.chars().count() > 400 {
            t = t.chars().rev().take(400).collect::<Vec<_>>().into_iter().rev().collect();
        }
        return (format!("{}{}", tr("O app não respondeu. Ele está instalado e com a conta entrada?"), if t.is_empty() { String::new() } else { format!("\n\n{t}") }), true);
    }
    (limpa(&r), false)
}
/// (texto, erro)
/// proprio: as instruções de quem chama (a IA da Ilha, `pergunta_ilha`); None = as da Siri
fn pergunta(q: &str, num: i32, proprio: Option<&str>) -> (String, bool) {
    let p = shell::setting("siri_provedor", "0").parse::<usize>().unwrap_or(0).min(PROVEDORES.len() - 1);
    if p == 0 {
        return (tr("Escolha um serviço para a Siri em Ajustes do Sistema > Apple Intelligence e Siri."), true);
    }
    let pv = &PROVEDORES[p];
    if pv.fmt == Formato::Cli {
        return pergunta_cli(pv, q, num, proprio);
    }
    let mut modelo = shell::setting("siri_modelo", pv.modelos.first().copied().unwrap_or(""));
    let chave = if pv.precisa_chave { sr::le_chave(p) } else { String::new() };
    if pv.precisa_chave && chave.is_empty() {
        return (tr("Falta a chave da API. Cole a chave em Ajustes do Sistema > Apple Intelligence e Siri."), true);
    }
    if modelo.is_empty() {
        // LM Studio e afins: o modelo carregado
        let mut e = String::new();
        if let Some(m) = sr::lista_modelos(p, &mut e).into_iter().next() {
            modelo = m;
        }
    }
    let sistema = if let Some(p) = proprio { p.to_string() } else { sr::com_instrucoes(&format!("You are Siri inside WacOS, a macOS-style desktop for Windows. Answer briefly and clearly, in the same language as the question. Use plain text, without Markdown. {}", contexto())) };
    let cab = sr::cabecalhos(pv, &chave);
    drop(chave);
    let mut web = shell::setting("siri_web", "1") != "0";
    if web && pv.fmt == Formato::Gemini && SEM_BUSCA.lock().unwrap().contains(&modelo) {
        web = false; // já se sabe: sem cota para a pesquisa
    }
    let mut tirou_busca = false;
    let mut r = sr::Resposta { status: 0, falha: 0, corpo: String::new() };
    for tentativa in 0..3 {
        let mut caminho = pv.caminho.to_string();
        let body = match pv.fmt {
            Formato::Gemini => {
                caminho = caminho.replace("{m}", &modelo);
                // siri_web (issue #42): o Gemini pesquisa no Google antes de responder
                format!("{{\"systemInstruction\":{{\"parts\":[{{\"text\":{}}}]}},\"contents\":[{{\"role\":\"user\",\"parts\":[{{\"text\":{}}}]}}]{}", sr::jstr(&sistema), sr::jstr(q), if web { ",\"tools\":[{\"google_search\":{}}]}" } else { "}" })
            }
            Formato::Anthropic => format!("{{\"model\":{},\"max_tokens\":1024,\"system\":{},\"messages\":[{{\"role\":\"user\",\"content\":{}}}]}}", sr::jstr(&modelo), sr::jstr(&sistema), sr::jstr(q)),
            // OpenAI e compatíveis (Groq, OpenRouter, Mistral, DeepSeek, xAI, LM Studio) e Ollama
            _ => format!("{{\"model\":{},\"messages\":[{{\"role\":\"system\",\"content\":{}}},{{\"role\":\"user\",\"content\":{}}}]{}", sr::jstr(&modelo), sr::jstr(&sistema), sr::jstr(q), if pv.fmt == Formato::Ollama { ",\"stream\":false}" } else { "}" }),
        };
        r = sr::http(pv, "POST", &caminho, &cab, body.as_bytes(), 60000);
        log!("siri: {} {modelo} -> {} ({} bytes, erro {})", pv.nome, r.status, r.corpo.len(), r.falha);
        if r.falha != 0 || tentativa >= 2 {
            break;
        }
        if web && r.status == 400 && pv.fmt == Formato::Gemini {
            // o modelo não aceita a pesquisa: de novo, sem ela
            let m = sr::erro_do_servico(&r.corpo).to_lowercase();
            if m.contains("search") || m.contains("tool") {
                web = false;
                log!("siri: {modelo} sem a pesquisa na web");
                continue;
            }
        }
        if [503, 500, 529].contains(&r.status) {
            // sobrecarregado: de novo; depois, outro modelo da lista (só nesta pergunta)
            if tentativa == 0 {
                std::thread::sleep(std::time::Duration::from_millis(1500));
                continue;
            }
            let mut e = String::new();
            let alt = reserva(&sr::lista_modelos(p, &mut e), &modelo, pv.fmt == Formato::Gemini);
            if !alt.is_empty() {
                log!("siri: {modelo} sobrecarregado; tentando {alt}");
                modelo = alt;
                continue;
            }
            break;
        }
        // cota zerada deste modelo: tenta o preferido da lista, que costuma estar no plano
        let msg_erro = sr::erro_do_servico(&r.corpo);
        let sem_cota = r.status == 429 && msg_erro.to_lowercase().contains("quota");
        if sem_cota && web && pv.fmt == Formato::Gemini {
            web = false; // primeiro sem a pesquisa, no modelo escolhido (issue #42)
            tirou_busca = true;
            log!("siri: sem cota em {modelo} com a pesquisa na web; de novo sem ela");
            continue;
        }
        if sem_cota {
            let mut e = String::new();
            let lista = sr::lista_modelos(p, &mut e);
            let outro = if lista.first().is_some_and(|m| *m != modelo) { lista[0].clone() } else { reserva(&lista, &modelo, pv.fmt == Formato::Gemini) };
            if !outro.is_empty() {
                log!("siri: sem cota em {modelo}; tentando {outro}");
                modelo = outro;
                continue; // só nesta pergunta: a cota volta amanhã
            }
        }
        if !modelo_sumiu(r.status, &msg_erro) {
            if r.status >= 400 {
                log!("siri: erro do serviço: {}", msg_erro.chars().take(200).collect::<String>());
            }
            break;
        }
        // o modelo saiu do ar: pega a lista atual do serviço, guarda o preferido dela e pergunta de novo
        let mut e = String::new();
        let lista = sr::lista_modelos(p, &mut e);
        if lista.first().is_none_or(|m| *m == modelo) {
            log!("siri: o modelo saiu do ar, mas a lista não trouxe outro ({})", if e.is_empty() { "vazia" } else { &e });
            break;
        }
        log!("siri: {modelo} não existe mais; agora {}", lista[0]);
        modelo = lista[0].clone();
        let junta = lista.join("|");
        let m2 = modelo.clone();
        // pela thread da interface: set_setting grava o ajustes.txt (gravações misturadas não)
        shell::na_interface(Box::new(move || {
            shell::set_setting("siri_modelo", &m2);
            shell::set_setting(&format!("siri_modelos_{p}"), &junta);
        }));
    }
    if tirou_busca && r.falha == 0 && (200..300).contains(&r.status) {
        let mut v = SEM_BUSCA.lock().unwrap();
        if !v.contains(&modelo) {
            v.push(modelo.clone()); // sem a pesquisa deu certo: era só a cota dela
        }
    }
    drop(cab); // a chave ia no cabeçalho
    if r.falha != 0 {
        if pv.porta != 443 {
            return (format!("{} ({})", tr("Não deu para falar com o app neste PC. Ele está aberto?"), pv.nome), true);
        }
        return (tr("Não deu para falar com o serviço. Confira a internet."), true);
    }
    if (200..300).contains(&r.status) {
        let (chave, de) = match pv.fmt {
            Formato::Gemini => ("text", r.corpo.find("\"candidates\"")),
            Formato::Anthropic => ("text", r.corpo.find("\"content\"")),
            _ => ("content", r.corpo.find("\"message\"")),
        };
        if let Some((t, _)) = de.and_then(|d| sr::jle(&r.corpo, chave, d)).filter(|t| !t.0.is_empty()) {
            return (limpa(&t), false);
        }
        return (tr("O serviço respondeu sem texto."), true);
    }
    let mut t = sr::erro_do_servico(&r.corpo);
    if r.status == 429 {
        let l = t.to_lowercase();
        if l.contains("quota") || l.contains("rate") {
            return (format!("{} ({modelo})", tr("Acabou a cota deste modelo no seu plano (o grátis tem limite por minuto e por dia). Espere um pouco ou escolha outro modelo em Ajustes do Sistema > Apple Intelligence e Siri.")), true);
        }
    }
    // as mensagens dos serviços podem ter várias linhas e links: só a primeira frase
    if let Some(n) = t.find('\n') {
        t.truncate(n);
    }
    if t.chars().count() > 240 {
        t = t.chars().take(237).collect::<String>() + "...";
    }
    if !t.is_empty() {
        return (format!("{}{t}", if r.status == 401 || r.status == 403 { tr("Chave recusada pelo serviço.") + " " } else { String::new() }), true);
    }
    (format!("{} ({}).", tr("O serviço recusou a pergunta"), r.status), true)
}

// ---------------------------------------------------------------- painel
#[derive(Default)]
struct S {
    wnd: HWND,
    back: HWND,
    s: ui::GpuSurface,
    glass: bool,
    in_glass: bool,
    open: bool,
    q: String,
    a: String,
    busy: bool,
    erro: bool,
    pontos: i32,
    scroll: f32,
    content_h: f32,
    open_at: f64,
    answer_at: f64,
    close_at: f64,
    closing: bool,
    teste: bool,
    /// campo de digitar (aberta pelo ícone da barra, ou digitando depois de uma resposta)
    entrada: bool,
    texto: String,
    cursor_on: bool,
    mic: RectF,
    w: f32,
    wpx: i32,
    hpx: i32,
    hh: f32,
    pecas: (i32, i32, bool, f64),
    tf: Option<(IDWriteTextFormat, IDWriteTextFormat)>,
    round: Option<ID2D1StrokeStyle>,
}
static SS: Global<Option<S>> = Global::new(None);
fn s() -> &'static mut S {
    SS.get().get_or_insert_with(|| S { cursor_on: true, w: 560.0, pecas: (-1, -1, false, 0.0), mic: rf(0.0, 0.0, 0.0, 0.0), ..Default::default() })
}
fn sc() -> f32 {
    if s().wnd.0.is_null() {
        1.0
    } else {
        ui::scale(s().wnd)
    }
}
fn altura_texto(t: &str, f: &IDWriteTextFormat, w_: f32) -> f32 {
    unsafe {
        ui::dw().CreateTextLayout(&w(t), f, w_, 10000.0).ok().and_then(|l| {
            let mut m = DWRITE_TEXT_METRICS::default();
            l.GetMetrics(&mut m).ok().map(|_| m.height)
        })
    }
    .unwrap_or(0.0)
}
/// u em [0,1): rosa, roxo, azul, ciano, laranja e de volta ao rosa
fn cor_da_volta(u: f32) -> Cor {
    let c_ = [col(1.0, 0.33, 0.62, 1.0), col(0.68, 0.36, 1.0, 1.0), col(0.26, 0.52, 1.0, 1.0), col(0.30, 0.86, 1.0, 1.0), col(1.0, 0.64, 0.30, 1.0)];
    let u = u - u.floor();
    let f = u * 5.0;
    let (a, b) = (f as usize % 5, (f as usize + 1) % 5);
    let mut k = f - f.floor();
    k = k * k * (3.0 - 2.0 * k); // suave entre as cores
    col(c_[a].r + (c_[b].r - c_[a].r) * k, c_[a].g + (c_[b].g - c_[a].g) * k, c_[a].b + (c_[b].b - c_[a].b) * k, 1.0)
}
/// ponto da borda do retângulo arredondado em u (0..1, sentido horário a partir do meio de cima)
fn ponto_da_borda(r: &RectF, rad: f32, u: f32) -> Ponto {
    let (w_, h) = (r.right - r.left, r.bottom - r.top);
    let arco = std::f32::consts::FRAC_PI_2 * rad;
    let (reto_x, reto_y) = (w_ - 2.0 * rad, h - 2.0 * rad);
    let total = 2.0 * reto_x + 2.0 * reto_y + 4.0 * arco;
    let mut d = (u - u.floor()) * total;
    let canto = |cx: f32, cy: f32, a0: f32, t: f32| {
        let a = a0 + t / rad;
        pt(cx + a.cos() * rad, cy + a.sin() * rad)
    };
    let x0 = r.left + w_ / 2.0;
    let seg = reto_x / 2.0;
    if d < seg {
        return pt(x0 + d, r.top);
    }
    d -= seg;
    if d < arco {
        return canto(r.right - rad, r.top + rad, -std::f32::consts::FRAC_PI_2, d);
    }
    d -= arco;
    if d < reto_y {
        return pt(r.right, r.top + rad + d);
    }
    d -= reto_y;
    if d < arco {
        return canto(r.right - rad, r.bottom - rad, 0.0, d);
    }
    d -= arco;
    if d < reto_x {
        return pt(r.right - rad - d, r.bottom);
    }
    d -= reto_x;
    if d < arco {
        return canto(r.left + rad, r.bottom - rad, std::f32::consts::FRAC_PI_2, d);
    }
    d -= arco;
    if d < reto_y {
        return pt(r.left, r.bottom - rad - d);
    }
    d -= reto_y;
    if d < arco {
        return canto(r.left + rad, r.top + rad, std::f32::consts::PI, d);
    }
    d -= arco;
    pt(r.left + rad + d.min(reto_x / 2.0), r.top)
}
fn set_f32(e: &ID2D1Effect, idx: u32, v: f32) {
    unsafe {
        let _ = e.SetValue(idx, D2D1_PROPERTY_TYPE_FLOAT, &v.to_le_bytes());
    }
}
/// o brilho da borda (como o do Apple Intelligence): um anel colorido que gira, com uma onda de luz correndo, gravado
/// numa lista de comandos e desfocado na GPU (um desfoque largo e suave, outro curto e forte), e o fio nítido por cima
unsafe fn brilho(dc: &ID2D1DeviceContext, bx: RectF, rad: f32, t_ms: f64, forca: f32) {
    if forca <= 0.01 {
        return;
    }
    let st = s();
    let Ok(br) = dc.CreateSolidColorBrush(&col(1.0, 1.0, 1.0, 1.0), None) else { return };
    const N: usize = 144;
    let gira = (t_ms / 2600.0) as f32; // as cores dão uma volta a cada 2,6 s
    if st.round.is_none() {
        st.round = ui::d2d()
            .CreateStrokeStyle(&D2D1_STROKE_STYLE_PROPERTIES { startCap: D2D1_CAP_STYLE_ROUND, endCap: D2D1_CAP_STYLE_ROUND, dashCap: D2D1_CAP_STYLE_ROUND, lineJoin: D2D1_LINE_JOIN_ROUND, miterLimit: 10.0, dashStyle: D2D1_DASH_STYLE_SOLID, dashOffset: 0.0 }, None)
            .ok();
    }
    let pts: Vec<Ponto> = (0..=N).map(|k| ponto_da_borda(&bx, rad, k as f32 / N as f32)).collect();
    let cores: Vec<Cor> = (0..N).map(|k| cor_da_volta((k as f32 + 0.5) / N as f32 * 2.0 + gira)).collect(); // duas voltas de cor
    let ondas: Vec<f32> = (0..N).map(|k| 0.55 + 0.45 * (std::f32::consts::TAU * ((k as f32 + 0.5) / N as f32 - gira * 0.7)).cos()).collect();
    // a luz: o anel grosso numa lista de comandos, desfocado
    if let Ok(cl) = dc.CreateCommandList() {
        let alvo = dc.GetTarget().ok();
        dc.SetTarget(&cl);
        for k in 0..N {
            br.SetColor(&Cor { a: 1.0, ..cores[k] });
            dc.DrawLine(pts[k], pts[k + 1], &br, 7.0 + 5.0 * ondas[k], st.round.as_ref()); // opaco: as pontas se sobrepõem
        }
        dc.SetTarget(alvo.as_ref());
        let _ = cl.Close();
        let mut t = mat::ident();
        dc.GetTransform(&mut t);
        dc.SetTransform(&mat::ident()); // a lista já está no lugar (gravada com a transformação)
        let esc = if t.M11 > 0.0 { t.M11 } else { 1.0 };
        for (desvio, alfa) in [(11.0 * esc, 0.55), (3.5 * esc, 0.45)] {
            if let (Ok(blur), Ok(opa)) = (dc.CreateEffect(&CLSID_D2D1GaussianBlur), dc.CreateEffect(&CLSID_D2D1Opacity)) {
                blur.SetInput(0, &cl, true);
                set_f32(&blur, 0, desvio); // D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION
                let _ = blur.SetValue(1, D2D1_PROPERTY_TYPE_ENUM, &0u32.to_le_bytes()); // otimização: velocidade
                if let Ok(out) = blur.GetOutput() {
                    opa.SetInput(0, &out, true);
                }
                set_f32(&opa, 0, alfa * forca); // D2D1_OPACITY_PROP_OPACITY
                if let Ok(img) = opa.GetOutput() {
                    dc.DrawImage(&img, None, None, D2D1_INTERPOLATION_MODE_LINEAR, D2D1_COMPOSITE_MODE_SOURCE_OVER);
                }
            }
        }
        dc.SetTransform(&t);
    }
    // o fio nítido na borda
    for k in 0..N {
        br.SetColor(&Cor { a: 0.95 * forca * (0.75 + 0.25 * ondas[k]), ..cores[k] });
        dc.DrawLine(pts[k], pts[k + 1], &br, 2.2, None);
    }
}
/// o ícone do Apple Intelligence com o degradê dele, que gira devagar e pulsa enquanto pensa; sem o símbolo, a bolinha
unsafe fn orbe(dc: &ID2D1DeviceContext, c_: Ponto, r: f32, t: f64) {
    let busy = s().busy;
    let rt: ID2D1RenderTarget = dc.cast().unwrap();
    let a = (t / if busy { 900.0 } else { 4000.0 }) as f32 + 2.3;
    let pulso = if busy { 1.0 + 0.06 * (t / 260.0).sin() as f32 } else { 1.0 };
    let rr_ = r * pulso;
    let (p0, p1) = (pt(c_.x + a.cos() * rr_, c_.y + a.sin() * rr_), pt(c_.x - a.cos() * rr_, c_.y - a.sin() * rr_));
    let stops = [(0.0, col(1.0, 0.62, 0.10, 1.0)), (0.3, col(1.0, 0.24, 0.42, 1.0)), (0.55, col(0.74, 0.33, 0.95, 1.0)), (0.8, col(0.40, 0.45, 1.0, 1.0)), (1.0, col(0.15, 0.55, 1.0, 1.0))];
    let ok = linear(&rt, &stops, p0, p1).is_some_and(|lg| simbolo::draw(&rt, "apple.intelligence", rf(c_.x - rr_, c_.y - rr_, c_.x + rr_, c_.y + rr_), &lg.cast().unwrap()));
    if ok {
        return;
    }
    // a bolinha da Siri: as cores giram enquanto pensa, com um brilho que pulsa
    let a = (t / if busy { 700.0 } else { 2400.0 }) as f32;
    let pulso = if busy { 1.0 + 0.07 * (t / 260.0).sin() as f32 } else { 1.0 };
    let rr_ = r * pulso;
    let Ok(br) = dc.CreateSolidColorBrush(&col(0.62, 0.38, 1.0, if busy { 0.22 } else { 0.12 }), None) else { return };
    dc.FillEllipse(&ell(c_, rr_ + 5.0, rr_ + 5.0), &br); // halo
    let stops = [(0.0, col(0.98, 0.36, 0.62, 1.0)), (0.35, col(0.62, 0.38, 1.0, 1.0)), (0.7, col(0.25, 0.62, 1.0, 1.0)), (1.0, col(1.0, 0.62, 0.32, 1.0))];
    if let Some(lg) = linear(&rt, &stops, pt(c_.x + a.cos() * rr_, c_.y + a.sin() * rr_), pt(c_.x - a.cos() * rr_, c_.y - a.sin() * rr_)) {
        dc.FillEllipse(&ell(c_, rr_, rr_), &lg);
    }
    br.SetColor(&col(1.0, 1.0, 1.0, 0.38)); // reflexo em cima, como uma bolha de vidro
    dc.FillEllipse(&ell(pt(c_.x - rr_ * 0.25, c_.y - rr_ * 0.38), rr_ * 0.45, rr_ * 0.25), &br);
    br.SetColor(&col(1.0, 1.0, 1.0, 0.35));
    dc.DrawEllipse(&ell(c_, rr_ - 0.5, rr_ - 0.5), &br, 1.0, None);
}
/// quanto do brilho aparece agora (1 pensando, apagando em 0,9 s depois da resposta)
fn forca_brilho(now: f64) -> f32 {
    let st = s();
    if st.entrada {
        return 0.0;
    }
    if st.busy {
        return 0.85 + 0.15 * (now / 420.0).sin() as f32;
    }
    let k = ((now - st.answer_at) / 900.0) as f32;
    if k >= 1.0 {
        0.0
    } else {
        (1.0 - k) * (1.0 - k)
    }
}
fn digitar_ms() -> f64 {
    let n = s().a.chars().count() as f64;
    n / 110.0f64.max(n / 2.2) * 1000.0
}
fn animando(now: f64) -> bool {
    let st = s();
    if st.entrada && voz::ouvindo() {
        return true;
    }
    st.closing || st.busy || !anim::panel_in(now - st.open_at).done || now - st.answer_at < 950.0f64.max(digitar_ms() + 50.0)
}
fn tfs() -> (IDWriteTextFormat, IDWriteTextFormat) {
    s().tf
        .get_or_insert_with(|| {
            let q = ui::fmt(12.5, DWRITE_FONT_WEIGHT_NORMAL);
            let a = ui::fmt(15.0, DWRITE_FONT_WEIGHT_NORMAL);
            unsafe {
                for f in [&q, &a] {
                    let _ = f.SetWordWrapping(DWRITE_WORD_WRAPPING_WRAP);
                    let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
                }
            }
            (q, a)
        })
        .clone()
}
unsafe fn txt(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, t: &str, tf: &IDWriteTextFormat, r: RectF) {
    dc.DrawText(&w(t), tf, &r, br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT, DWRITE_MEASURING_MODE_NATURAL); // emoji colorido
}
fn paint() {
    let st = s();
    if (!st.open && !st.closing) || st.wnd.0.is_null() {
        return;
    }
    let now = anim::now();
    let k = sc();
    let dark = ui::dark();
    let (tf_q, tf_a) = tfs();
    let ww = st.w;
    let mut text_w = ww - PAD * 2.0 - ORB - 14.0;
    let mut a = if st.busy { format!("{}{}", tr("Pensando"), ".".repeat((st.pontos % 3 + 1) as usize)) } else { st.a.clone() };
    let mut ah = altura_texto(&a, &tf_a, text_w); // a altura do texto inteiro: o painel não cresce aos pulos enquanto ele "digita"
    // a resposta aparece como se fosse digitada (issue #38): ~110 letras por segundo, no máximo 2,2 s
    if !st.busy && !st.entrada && st.answer_at > 0.0 {
        let vel = 110.0f64.max(st.a.chars().count() as f64 / 2.2);
        let n = ((now - st.answer_at) / 1000.0 * vel).max(0.0) as usize;
        if n < a.chars().count() {
            a = a.chars().take(n).collect();
        }
    }
    let mut qh = altura_texto(&st.q, &tf_q, text_w);
    st.content_h = PAD + qh + 8.0 + ah + PAD;
    if st.entrada {
        // só o campo: uma linha (ou mais, se o texto quebrar)
        qh = 0.0;
        ah = altura_texto(if st.texto.is_empty() { "M" } else { &st.texto }, &tf_a, text_w).max(20.0);
        st.content_h = (ORB + PAD * 2.0).max(PAD + ah + PAD + 4.0);
    }
    let _ = qh;
    let mut mi = MONITORINFO { cbSize: std::mem::size_of::<MONITORINFO>() as u32, ..Default::default() };
    unsafe {
        let _ = GetMonitorInfoW(MonitorFromWindow(st.wnd, MONITOR_DEFAULTTONEAREST), &mut mi);
    }
    let max_h = (mi.rcWork.bottom - mi.rcWork.top) as f32 / k * 0.6;
    let h = st.content_h.clamp(ORB + PAD * 2.0, max_h.max(ORB + PAD * 2.0));
    st.scroll = st.scroll.clamp(0.0, (st.content_h - h).max(0.0));
    let (wpx, hpx) = (((ww + 2.0 * M) * k).round() as i32, ((h + 2.0 * M) * k).round() as i32);
    unsafe {
        let mut wr = RECT::default();
        let _ = GetWindowRect(st.wnd, &mut wr);
        if wr.bottom - wr.top != hpx || wr.right - wr.left != wpx {
            let _ = SetWindowPos(st.wnd, None, 0, 0, wpx, hpx, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
            if !st.back.0.is_null() {
                let _ = SetWindowPos(st.back, st.wnd, wr.left, wr.top, wpx, hpx, SWP_NOACTIVATE);
            }
        }
    }
    let mpx = M * k;
    st.wpx = wpx;
    st.hpx = hpx;
    st.hh = h;
    if st.glass && (wpx != st.pecas.0 || hpx != st.pecas.1 || dark != st.pecas.2 || now - st.pecas.3 > 250.0) {
        st.pecas = (wpx, hpx, dark, now);
        backdrop::set_pieces(st.back, wpx as f32, hpx as f32, &[backdrop::Piece { r: rf(mpx, mpx, wpx as f32 - mpx, hpx as f32 - mpx), radius: R * k, ..Default::default() }], if dark { col(0.13, 0.13, 0.14, 0.55) } else { col(0.96, 0.96, 0.97, 0.50) }, 24.0);
    }
    let gdc = if st.glass { backdrop::content_begin(st.back, wpx, hpx, k) } else { None };
    st.in_glass = gdc.is_some();
    let dc = match gdc {
        Some(d) => d,
        None => {
            let Some(d) = ui::gpu_begin(&mut st.s, wpx, hpx, k) else { return };
            d
        }
    };
    unsafe {
        let mut base = mat::ident();
        dc.GetTransform(&mut base);
        dc.SetTransform(&mat::mul(&mat::trans(M, M), &base)); // o painel começa na folga
        if let Ok(br) = dc.CreateSolidColorBrush(&col(1.0, 1.0, 1.0, 1.0), None) {
            let rt: ID2D1RenderTarget = dc.cast().unwrap();
            let bx = rf(0.0, 0.0, ww, h);
            if !st.in_glass {
                brilho(&dc, rf(-1.0, -1.0, ww + 1.0, h + 1.0), R + 1.0, now - st.open_at, forca_brilho(now));
            }
            if !st.glass {
                br.SetColor(&if dark { col(0.16, 0.16, 0.17, 0.95) } else { col(0.96, 0.96, 0.97, 0.95) });
                dc.FillRoundedRectangle(&rr(bx, R, R), &br);
            }
            if liquid::on() {
                liquid::rim0(&rt, bx, R, dark);
            } else {
                br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.14) } else { col(0.0, 0.0, 0.0, 0.12) });
                dc.DrawRoundedRectangle(&rr(rf(0.5, 0.5, ww - 0.5, h - 0.5), R, R), &br, 1.0, None);
            }
            if !st.in_glass {
                orbe(&dc, pt(PAD + ORB / 2.0, PAD + ORB / 2.0), ORB / 2.0, now - st.open_at);
            }
            let x = PAD + ORB + 14.0;
            if st.entrada {
                // o campo: o texto digitado (ou o convite em cinza), o cursor piscando e o microfone à direita
                let y0 = (h - ah) / 2.0;
                let ouvindo = voz::ouvindo();
                let vazio = st.texto.is_empty();
                let t = if vazio { tr(if ouvindo { "Ouvindo…" } else { "Pergunte à Siri…" }) } else { st.texto.clone() };
                let (mx, my) = (ww - PAD - 14.0, h / 2.0);
                st.mic = rf(mx - 16.0, my - 16.0, mx + 16.0, my + 16.0);
                if ouvindo {
                    let kk = 0.5 + 0.5 * (now / 220.0).sin() as f32;
                    br.SetColor(&col(1.0, 0.23, 0.19, 0.18 + 0.14 * kk));
                    dc.FillEllipse(&ell(pt(mx, my), 13.0 + 3.0 * kk, 13.0 + 3.0 * kk), &br);
                }
                br.SetColor(&if ouvindo {
                    col(1.0, 0.27, 0.23, 1.0)
                } else if dark {
                    col(1.0, 1.0, 1.0, 0.75)
                } else {
                    col(0.0, 0.0, 0.0, 0.6)
                });
                if !simbolo::draw(&rt, "microphone.fill", rf(mx - 7.0, my - 10.0, mx + 7.0, my + 10.0), &br.cast().unwrap()) {
                    dc.FillRoundedRectangle(&rr(rf(mx - 4.0, my - 9.0, mx + 4.0, my + 3.0), 4.0, 4.0), &br);
                    dc.DrawLine(pt(mx, my + 6.0), pt(mx, my + 10.0), &br, 1.6, None);
                }
                text_w -= 34.0;
                br.SetColor(&match (vazio, dark) {
                    (true, true) => col(1.0, 1.0, 1.0, 0.38),
                    (true, false) => col(0.0, 0.0, 0.0, 0.35),
                    (false, true) => col(1.0, 1.0, 1.0, 0.95),
                    (false, false) => col(0.0, 0.0, 0.0, 0.88),
                });
                txt(&dc, &br, &t, &tf_a, rf(x, y0, x + text_w, y0 + ah + 4.0));
                if st.cursor_on {
                    // o cursor no fim do texto
                    let (mut cx, mut cy, mut ch) = (x, y0, 18.0);
                    if !vazio {
                        if let Ok(lay) = ui::dw().CreateTextLayout(&w(&st.texto), &tf_a, text_w, 10000.0) {
                            let (mut px, mut py) = (0f32, 0f32);
                            let mut hm = DWRITE_HIT_TEST_METRICS::default();
                            let n = st.texto.encode_utf16().count() as u32;
                            if lay.HitTestTextPosition(n.saturating_sub(1), true, &mut px, &mut py, &mut hm).is_ok() {
                                cx = x + px;
                                cy = y0 + py;
                                ch = hm.height;
                            }
                        }
                    }
                    br.SetColor(&col(0.40, 0.52, 1.0, 1.0));
                    dc.FillRectangle(&rf(cx + 1.0, cy + 1.0, cx + 3.0, cy + ch - 1.0), &br);
                }
            } else {
                dc.PushAxisAlignedClip(&rf(x - 2.0, 8.0, ww - PAD + 2.0, h - 8.0), D2D1_ANTIALIAS_MODE_ALIASED);
                let mut y = PAD - st.scroll;
                let qh = altura_texto(&st.q, &tf_q, text_w);
                br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.55) } else { col(0.0, 0.0, 0.0, 0.5) });
                txt(&dc, &br, &st.q, &tf_q, rf(x, y, x + text_w, y + qh + 4.0));
                y += qh + 8.0;
                // a resposta entra subindo um pouco e aparecendo (0,35 s)
                let kk = if st.busy { 1.0 } else { (((now - st.answer_at) / 350.0) as f32).clamp(0.0, 1.0) };
                let e = 1.0 - (1.0 - kk).powi(3);
                let mut tc = if st.erro {
                    col(1.0, 0.42, 0.38, 1.0)
                } else if dark {
                    col(1.0, 1.0, 1.0, 0.95)
                } else {
                    col(0.0, 0.0, 0.0, 0.88)
                };
                tc.a *= if st.busy { 0.6 } else { e };
                br.SetColor(&tc);
                let dy = (1.0 - e) * 8.0;
                txt(&dc, &br, &a, &tf_a, rf(x, y + dy, x + text_w, y + dy + ah + 4.0));
                dc.PopAxisAlignedClip();
                if st.content_h > h {
                    // barrinha de rolagem fina
                    let bh = 24.0f32.max(h * h / st.content_h);
                    let by = 6.0 + (h - 12.0 - bh) * (st.scroll / (st.content_h - h));
                    br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.3) } else { col(0.0, 0.0, 0.0, 0.25) });
                    dc.FillRoundedRectangle(&rr(rf(ww - 8.0, by, ww - 4.0, by + bh), 2.0, 2.0), &br);
                }
            }
        }
        dc.SetTransform(&base);
    }
    if st.in_glass {
        backdrop::content_end(st.back);
        paint_frente();
    } else {
        ui::gpu_end(&mut st.s);
    }
}
/// a camada da frente (com vidro): o brilho e o ícone; os quadros da animação redesenham só isto
fn paint_frente() {
    let st = s();
    if (!st.open && !st.closing) || st.wnd.0.is_null() || !st.in_glass || st.wpx == 0 {
        return;
    }
    let now = anim::now();
    let Some(gd) = ui::gpu_begin(&mut st.s, st.wpx, st.hpx, sc()) else { return };
    unsafe {
        let mut b2 = mat::ident();
        gd.GetTransform(&mut b2);
        gd.SetTransform(&mat::mul(&mat::trans(M, M), &b2));
        brilho(&gd, rf(-1.0, -1.0, st.w + 1.0, st.hh + 1.0), R + 1.0, now - st.open_at, forca_brilho(now));
        orbe(&gd, pt(PAD + ORB / 2.0, PAD + ORB / 2.0), ORB / 2.0, now - st.open_at);
        gd.SetTransform(&b2);
    }
    ui::gpu_end(&mut st.s);
}
/// o conteúdo (texto) muda neste quadro? Sem vidro, tudo é uma camada só e vai sempre
fn conteudo_mexe(now: f64) -> bool {
    let st = s();
    if !st.in_glass {
        return true;
    }
    if st.entrada {
        return voz::ouvindo(); // o microfone pulsando
    }
    if st.busy {
        return false; // os pontinhos mudam pelo T_PONTOS
    }
    now - st.answer_at < 400.0f64.max(digitar_ms() + 50.0)
}
/// a mola de abrir ou de fechar entregue ao compositor de uma vez (amostrada a cada 10 ms)
fn mola_no_compositor(fechar: bool) {
    let st = s();
    if st.wnd.0.is_null() {
        return;
    }
    let (mut es, mut op) = (Vec::new(), Vec::new());
    for i in 0..400 {
        let mo = if fechar { anim::panel_out(i as f64 * 10.0) } else { anim::panel_in(i as f64 * 10.0) };
        es.push(mo.scale);
        op.push(mo.fade);
        if mo.done {
            break;
        }
    }
    if es.len() < 2 {
        es.push(*es.last().unwrap_or(&1.0));
        op.push(*op.last().unwrap_or(&1.0));
    }
    let mut wr = RECT::default();
    unsafe {
        let _ = GetWindowRect(st.wnd, &mut wr);
    }
    let (cx, cy) = ((wr.right - wr.left) as f32 / 2.0, (wr.bottom - wr.top) as f32 / 2.0);
    ui::gpu_motion_anim(&st.s, cx, cy, &es, &op, 10.0);
    if !st.back.0.is_null() {
        backdrop::fade_anim(st.back, cx, cy, &es, &op, 10.0);
    }
}
fn esconde() {
    let st = s();
    st.closing = false;
    ui::frame_clock(st.wnd, WM_SIRI_FRAME, false);
    unsafe {
        let _ = ShowWindow(st.wnd, SW_HIDE);
        if !st.back.0.is_null() {
            let _ = ShowWindow(st.back, SW_HIDE);
        }
    }
}
fn fecha() {
    let st = s();
    if !st.open {
        return;
    }
    voz::parar();
    st.open = false;
    st.busy = false;
    NUM.fetch_add(1, Ordering::SeqCst); // a resposta que ainda vem é descartada
    unsafe {
        let _ = KillTimer(st.wnd, T_PONTOS);
    }
    if anim::reduce_motion() {
        esconde();
        return;
    }
    st.closing = true;
    st.close_at = anim::now();
    mola_no_compositor(true);
    ui::frame_clock(st.wnd, WM_SIRI_FRAME, true);
}
fn nova_entrada() {
    let st = s();
    st.entrada = true;
    st.texto.clear();
    st.q.clear();
    st.a.clear();
    st.scroll = 0.0;
}
unsafe extern "system" fn proc_(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    let st = s();
    match m {
        WM_SIRI_FIM => {
            let r = Box::from_raw(l.0 as *mut (String, bool));
            if w_.0 as i32 == NUM.load(Ordering::SeqCst) && st.open {
                st.erro = r.1;
                st.a = r.0;
                st.busy = false;
                st.scroll = 0.0;
                st.answer_at = anim::now();
                let _ = KillTimer(h, T_PONTOS);
                paint(); // o brilho apaga e a resposta entra: os quadros continuam
            }
            LRESULT(0)
        }
        WM_LBUTTONUP => {
            // o microfone do campo
            let k = sc();
            let (x, y) = (get_x_lparam(l) as f32 / k - M, get_y_lparam(l) as f32 / k - M);
            if st.entrada && in_rect(&st.mic, x, y) {
                if voz::ouvindo() {
                    voz::parar();
                } else {
                    voz::ouvir(h, WM_SIRI_VOZ);
                    ui::frame_clock(h, WM_SIRI_FRAME, true);
                }
                paint();
            }
            LRESULT(0)
        }
        WM_SIRI_VOZ => {
            // o texto enquanto fala, o final (pergunta sozinha) ou o aviso
            let t = voz::texto(l);
            if !st.open || !st.entrada {
                return LRESULT(0);
            }
            match voz::Tipo::de(w_) {
                voz::Tipo::Parcial => {
                    st.texto = t;
                    paint();
                }
                voz::Tipo::Final => {
                    if !t.is_empty() {
                        let teste = st.teste;
                        perguntar_com(&t, teste); // como a Siri: falou, perguntou
                    } else {
                        paint();
                    }
                }
                _ => {
                    // erro: aparece no painel, em vermelho
                    st.entrada = false;
                    st.q.clear();
                    st.a = t;
                    st.erro = true;
                    st.answer_at = anim::now();
                    let _ = KillTimer(h, T_CURSOR);
                    ui::frame_clock(h, WM_SIRI_FRAME, true);
                    paint();
                }
            }
            LRESULT(0)
        }
        WM_SIRI_FRAME => {
            ui::frame_ack(h, WM_SIRI_FRAME);
            let now = anim::now();
            if st.closing {
                // a mola de fechar é do compositor
                if anim::panel_out(now - st.close_at).done {
                    esconde();
                }
                return LRESULT(0);
            }
            if conteudo_mexe(now) {
                paint();
            } else {
                paint_frente();
            }
            if !animando(now) {
                ui::frame_clock(h, WM_SIRI_FRAME, false);
            }
            LRESULT(0)
        }
        WM_NCHITTEST => {
            // só o painel pega o clique; a folga do brilho deixa passar
            let (x, y) = (get_x_lparam(l), get_y_lparam(l));
            let mut wr = RECT::default();
            let _ = GetWindowRect(h, &mut wr);
            let mpx = (M * sc()).round() as i32;
            let dentro = x >= wr.left + mpx && x < wr.right - mpx && y >= wr.top + mpx && y < wr.bottom - mpx;
            LRESULT(if dentro { HTCLIENT as isize } else { HTTRANSPARENT as isize })
        }
        WM_TIMER => {
            match w_.0 {
                T_TESTE => {
                    let _ = KillTimer(h, T_TESTE);
                    fecha();
                }
                T_CURSOR => {
                    st.cursor_on = !st.cursor_on;
                    if st.entrada {
                        paint();
                    } else {
                        let _ = KillTimer(h, T_CURSOR);
                    }
                }
                T_PONTOS => {
                    st.pontos += 1;
                    paint();
                }
                _ => {}
            }
            LRESULT(0)
        }
        WM_MOUSEWHEEL => {
            st.scroll -= ((w_.0 >> 16) as u16 as i16) as f32 / 120.0 * 48.0;
            paint();
            LRESULT(0)
        }
        WM_CHAR => {
            if !st.open || st.busy {
                return LRESULT(0);
            }
            let ch = w_.0 as u32;
            if ch == 13 {
                // Enter: pergunta
                if st.entrada && !st.texto.is_empty() {
                    let (q, teste) = (st.texto.clone(), st.teste);
                    perguntar_com(&q, teste);
                }
                return LRESULT(0);
            }
            if ch == 8 {
                if st.entrada && st.texto.pop().is_some() {
                    st.cursor_on = true;
                    paint();
                }
                return LRESULT(0);
            }
            let ctrl_sem_alt = GetKeyState(VK_CONTROL.0 as i32) < 0 && GetKeyState(VK_MENU.0 as i32) >= 0;
            if ch >= 32 && ch != 127 && !ctrl_sem_alt {
                if !st.entrada {
                    nova_entrada(); // digitou depois da resposta: outra pergunta
                }
                if st.texto.chars().count() < 2000 {
                    if let Some(c_) = char::from_u32(ch) {
                        st.texto.push(c_);
                    }
                }
                st.cursor_on = true;
                SetTimer(h, T_CURSOR, 530, None);
                paint();
            }
            LRESULT(0)
        }
        WM_KEYDOWN => {
            let vk = VIRTUAL_KEY(w_.0 as u16);
            let ctrl = GetKeyState(VK_CONTROL.0 as i32) < 0;
            if vk.0 == b'V' as u16 && ctrl && !st.busy {
                // colar no campo
                if let Some(t) = clipboard_get_text(h) {
                    let t: String = t.chars().map(|c_| if matches!(c_, '\r' | '\n' | '\t') { ' ' } else { c_ }).collect();
                    if !st.entrada {
                        nova_entrada();
                    }
                    let livre = 2000usize.saturating_sub(st.texto.chars().count());
                    st.texto.extend(t.chars().take(livre));
                }
                paint();
                return LRESULT(0);
            }
            if vk == VK_ESCAPE {
                fecha();
            } else if vk.0 == b'C' as u16 && ctrl {
                if !st.busy && !st.a.is_empty() {
                    let _ = clipboard_set_text(h, &st.a);
                }
            } else if vk == VK_DOWN {
                st.scroll += 40.0;
                paint();
            } else if vk == VK_UP {
                st.scroll -= 40.0;
                paint();
            }
            LRESULT(0)
        }
        WM_ACTIVATE => {
            if loword(w_.0) == WA_INACTIVE && st.open && !st.teste {
                log!("siri: perdeu a frente; fecha");
                fecha();
            }
            LRESULT(0)
        }
        WM_CLOSE => {
            fecha();
            LRESULT(0)
        }
        _ => DefWindowProcW(h, m, w_, l),
    }
}
unsafe extern "system" fn back_proc(h: HWND, m: u32, w_: WPARAM, l: LPARAM) -> LRESULT {
    match m {
        WM_MOUSEACTIVATE => LRESULT(MA_NOACTIVATE as isize),
        WM_NCHITTEST => LRESULT(HTTRANSPARENT as isize),
        _ => DefWindowProcW(h, m, w_, l),
    }
}
fn ready() -> bool {
    let st = s();
    unsafe {
        if !st.wnd.0.is_null() && IsWindow(st.wnd).as_bool() {
            return true;
        }
        let hi = shell::inst();
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(proc_), hInstance: hi, lpszClassName: w!("ShellSiri"), hCursor: LoadCursorW(None, IDC_ARROW).unwrap_or_default(), ..Default::default() });
        RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(back_proc), hInstance: hi, lpszClassName: w!("ShellSiriFundo"), ..Default::default() });
        st.wnd = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP, w!("ShellSiri"), w!("Siri"), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
        st.back = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE | WS_EX_NOREDIRECTIONBITMAP, w!("ShellSiriFundo"), w!(""), WS_POPUP, 0, 0, 10, 10, None, None, hi, None).unwrap_or_default();
        if st.wnd.0.is_null() || st.back.0.is_null() {
            log!("siri: janela não criada");
            return false;
        }
        st.glass = backdrop::attach(st.back);
        if !st.glass {
            let _ = DestroyWindow(st.back);
            st.back = HWND::default();
        }
    }
    apps::ours().push(st.wnd);
    if !st.back.0.is_null() {
        apps::ours().push(st.back);
    }
    st.s.hwnd = st.wnd;
    true
}
/// um serviço de IA escolhido nos Ajustes (com a chave, se ele pede)
pub fn pronta() -> bool {
    let p = shell::setting("siri_provedor", "0").parse::<usize>().unwrap_or(0);
    if p == 0 || p >= PROVEDORES.len() {
        return false;
    }
    !PROVEDORES[p].precisa_chave || sr::arquivo_chave(p).exists()
}
/// mostra o painel (a mola de abrir); já aberto, fica onde está e só muda o conteúdo
fn mostra_painel(teste: bool) {
    let st = s();
    if st.open && unsafe { IsWindowVisible(st.wnd).as_bool() } {
        paint();
        ui::frame_clock(st.wnd, WM_SIRI_FRAME, true);
        return;
    }
    // alinhada ao Spotlight: o mesmo monitor (o do ponteiro), o mesmo centro e o topo do painel na altura do campo dele
    let k = ui::scale(st.wnd);
    st.w = spotlight::largura_campo();
    let (wpx, hpx) = (((st.w + 2.0 * M) * k).round() as i32, ((ORB + PAD * 2.0 + 2.0 * M) * k).round() as i32);
    let sp = spotlight::lugar();
    let (x, y) = ((sp.left + sp.right - wpx) / 2, sp.top - (M * k).round() as i32);
    unsafe {
        let _ = SetWindowPos(st.wnd, HWND_TOPMOST, x, y, wpx, hpx, SWP_NOACTIVATE);
        if !st.back.0.is_null() {
            let _ = SetWindowPos(st.back, st.wnd, x, y, wpx, hpx, SWP_NOACTIVATE);
        }
    }
    st.open = true;
    st.closing = false;
    st.open_at = anim::now();
    st.answer_at = 0.0;
    st.pecas.0 = -1;
    if st.glass {
        backdrop::fade(st.back, 0.0, 0.94, wpx as f32 / 2.0, hpx as f32 / 2.0); // nasce invisível e um pouco menor
    }
    ui::gpu_motion(&st.s, 0.94, wpx as f32 / 2.0, hpx as f32 / 2.0, 0.0);
    paint();
    mola_no_compositor(false);
    unsafe {
        if !st.back.0.is_null() {
            let _ = ShowWindow(st.back, SW_SHOWNOACTIVATE);
        }
        let _ = ShowWindow(st.wnd, if teste { SW_SHOWNOACTIVATE } else { SW_SHOW });
        if teste {
            SetTimer(st.wnd, T_TESTE, 8000, None);
        } else {
            shell::libera_frente();
            let _ = SetForegroundWindow(st.wnd);
            let _ = SetFocus(st.wnd);
        }
    }
    ui::frame_clock(st.wnd, WM_SIRI_FRAME, true); // a mola de abrir, o brilho e a bolinha enquanto pensa
}
/// o ícone da barra: o painel com o campo para digitar (teste: não pega a frente e some em 8 s)
pub fn abrir(teste: bool) {
    if !ready() {
        return;
    }
    let st = s();
    if st.open && st.entrada {
        fecha(); // clicar de novo fecha
        return;
    }
    st.teste = teste;
    nova_entrada();
    st.busy = false;
    st.erro = false;
    NUM.fetch_add(1, Ordering::SeqCst);
    st.cursor_on = true;
    mostra_painel(teste);
    unsafe {
        SetTimer(st.wnd, T_CURSOR, 530, None);
    }
}
pub fn aberta() -> bool {
    s().open
}
pub fn perguntar(q: &str) {
    perguntar_com(q, false);
}
pub fn perguntar_com(q: &str, teste: bool) {
    if q.is_empty() || !ready() {
        return;
    }
    let st = s();
    st.teste = teste;
    if voz::ouvindo() {
        voz::parar();
    }
    st.entrada = false;
    st.texto.clear();
    unsafe {
        let _ = KillTimer(st.wnd, T_CURSOR);
    }
    st.q = q.to_string();
    st.a.clear();
    st.busy = true;
    st.erro = false;
    st.scroll = 0.0;
    st.pontos = 0;
    st.answer_at = 0.0;
    let num = NUM.fetch_add(1, Ordering::SeqCst) + 1;
    mostra_painel(teste);
    unsafe {
        SetTimer(st.wnd, T_PONTOS, 420, None);
    }
    let to = st.wnd.0 as isize;
    let q = q.to_string();
    std::thread::spawn(move || {
        unsafe {
            let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
        }
        let r = pergunta(&q, num, None);
        let b = Box::into_raw(Box::new(r));
        unsafe {
            if PostMessageW(HWND(to as *mut _), WM_SIRI_FIM, WPARAM(num as usize), LPARAM(b as isize)).is_err() {
                drop(Box::from_raw(b)); // janela já fechada: não vaza
            }
            CoUninitialize();
        }
    });
}
/// modo foto: o painel com a pergunta e a resposta (sem perguntar a ninguém; com `campo`, o campo de digitar vazio)
pub fn foto(tela_w: f32, tela_h: f32, campo: bool) {
    let st = s();
    st.w = spotlight::largura_campo();
    st.open = true;
    if campo {
        st.entrada = true;
    } else {
        st.q = tr("Qual a capital da Austrália?");
        st.a = tr("A capital da Austrália é Camberra.");
        st.answer_at = -1.0e9;
    }
    let k = ui::foto_scale();
    // onde o Spotlight fica na foto: no meio, a ~22 % da altura (Tahoe 30 %)
    let top = tela_h * if liquid::on() { 0.30 } else { 0.22 } * k;
    let tf = tfs().1;
    let text_w = st.w - PAD * 2.0 - ORB - 14.0;
    let h = if campo { ORB + PAD * 2.0 } else { PAD + altura_texto(&st.q, &tfs().0, text_w) + 8.0 + altura_texto(&st.a, &tf, text_w) + PAD };
    st.hh = h;
    st.s.foto_pos = ((tela_w / 2.0 - st.w / 2.0 - M) * k, top - M * k);
    foto_paint(h);
}
fn foto_paint(h: f32) {
    let st = s();
    let k = ui::foto_scale();
    let (wpx, hpx) = (((st.w + 2.0 * M) * k).round() as i32, ((h + 2.0 * M) * k).round() as i32);
    let Some(dc) = ui::gpu_begin(&mut st.s, wpx, hpx, k) else { return };
    unsafe {
        let mut base = mat::ident();
        dc.GetTransform(&mut base);
        dc.SetTransform(&mat::mul(&mat::trans(M, M), &base));
        let dark = ui::dark();
        backdrop::foto_vidro(&dc, rf(0.0, 0.0, st.w, h), R, if dark { col(0.13, 0.13, 0.14, 0.55) } else { col(0.96, 0.96, 0.97, 0.50) });
        dc.SetTransform(&base);
    }
    ui::gpu_end(&mut st.s);
    // o resto do desenho pelo caminho de sempre (o brilho cheio, como enquanto pensa)
    st.busy = false;
    st.glass = false;
    st.in_glass = false;
    st.wnd = HWND::default();
    foto_conteudo(h);
}
fn foto_conteudo(h: f32) {
    let st = s();
    let k = ui::foto_scale();
    let (wpx, hpx) = (((st.w + 2.0 * M) * k).round() as i32, ((h + 2.0 * M) * k).round() as i32);
    let Some(dc) = ui::gpu_begin(&mut st.s, wpx, hpx, k) else { return };
    let (tf_q, tf_a) = tfs();
    unsafe {
        let mut base = mat::ident();
        dc.GetTransform(&mut base);
        dc.SetTransform(&mat::mul(&mat::trans(M, M), &base));
        let dark = ui::dark();
        let rt: ID2D1RenderTarget = dc.cast().unwrap();
        brilho(&dc, rf(-1.0, -1.0, st.w + 1.0, h + 1.0), R + 1.0, 1800.0, 0.9);
        if liquid::on() {
            liquid::rim0(&rt, rf(0.0, 0.0, st.w, h), R, dark);
        }
        orbe(&dc, pt(PAD + ORB / 2.0, PAD + ORB / 2.0), ORB / 2.0, 1800.0);
        if let Ok(br) = dc.CreateSolidColorBrush(&col(1.0, 1.0, 1.0, 1.0), None) {
            let x = PAD + ORB + 14.0;
            let text_w = st.w - PAD * 2.0 - ORB - 14.0;
            if st.entrada {
                br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.38) } else { col(0.0, 0.0, 0.0, 0.35) });
                let ah = altura_texto("M", &tf_a, text_w);
                txt(&dc, &br, &tr("Pergunte à Siri…"), &tf_a, rf(x, (h - ah) / 2.0, x + text_w, (h + ah) / 2.0 + 4.0));
            } else {
                let qh = altura_texto(&st.q, &tf_q, text_w);
                br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.55) } else { col(0.0, 0.0, 0.0, 0.5) });
                txt(&dc, &br, &st.q, &tf_q, rf(x, PAD, x + text_w, PAD + qh + 4.0));
                br.SetColor(&if dark { col(1.0, 1.0, 1.0, 0.95) } else { col(0.0, 0.0, 0.0, 0.88) });
                txt(&dc, &br, &st.a, &tf_a, rf(x, PAD + qh + 8.0, x + text_w, h));
            }
        }
        dc.SetTransform(&base);
    }
    ui::gpu_end(&mut st.s);
}

/// A IA da Ilha (ilha.rs): o mesmo caminho da Siri (serviço, chave, modelo, reservas e pesquisa na web dos Ajustes), com as
/// instruções da Ilha. Bloqueia: chamada numa thread. Devolve (texto, erro).
pub fn pergunta_ilha(sistema: &str, q: &str) -> (String, bool) {
    let s = sr::com_instrucoes(&format!("{sistema} {}", contexto()));
    pergunta(q, NUM.load(Ordering::SeqCst), Some(&s))
}
include!("siri_claude_aberto.rs");