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
11.1 KB
Raw Blame
// ---- as fontes das respostas (pedido de 02/12/2026: "ele está falando os links; manda as notícias em miniaturas com os
// links azuis e clicáveis, e ignora as fontes sem ler"). Com a busca na web, o Claude Code fecha a resposta com
// "Sources: • [título](url) • ..." e às vezes põe [título](url) no meio do texto. fontes() separa: o texto limpo (o que
// aparece no balão e é falado) e a lista (título, url). Embaixo do balão, cada fonte vira um cartão com a miniatura da
// notícia (a og:image da página, buscada aos poucos), o título e o site em azul; clicar abre no navegador.
// Incluído no ilha_painel.rs.

/// o texto para falar: sem links, fontes e marcação (a fala em partes da Siri usa isto em cada frase)
pub fn limpa_fala(t: &str) -> String {
    fontes(t).0
}
/// (texto limpo, [(título, url)])
fn fontes(t: &str) -> (String, Vec<(String, String)>) {
    let mut links: Vec<(String, String)> = Vec::new();
    // o bloco "Sources:" / "Fontes:" no fim sai inteiro
    let baixo = t.to_lowercase();
    let mut corpo = t.to_string();
    for chave in ["sources:", "fontes:", "fuentes:", "sources :", "quellen:"] {
        if let Some(k) = baixo.rfind(chave) {
            // só quando é mesmo o fim (o resto é quase todo links)
            let resto = &t[k..];
            if resto.contains("](http") || resto.contains("http") {
                corpo = t[..k].to_string();
                links.extend(links_md(resto));
                break;
            }
        }
    }
    // [título](url) no meio do texto: fica o título, o link vai para a lista
    let mut limpo = String::new();
    let mut rest = corpo.as_str();
    while let Some(a) = rest.find('[') {
        let Some(b) = rest[a..].find("](").map(|x| x + a) else { break };
        let Some(c) = rest[b..].find(')').map(|x| x + b) else { break };
        let url = &rest[b + 2..c];
        if !url.starts_with("http") {
            limpo.push_str(&rest[..=a]);
            rest = &rest[a + 1..];
            continue;
        }
        limpo.push_str(&rest[..a]);
        let tit = rest[a + 1..b].to_string();
        limpo.push_str(&tit);
        links.push((tit, url.to_string()));
        rest = &rest[c + 1..];
    }
    limpo.push_str(rest);
    // URLs soltas também saem do texto falado
    let mut final_ = String::new();
    for palavra in limpo.split_inclusive(char::is_whitespace) {
        let p = palavra.trim();
        let p2 = p.trim_matches(|c: char| matches!(c, '(' | ')' | '<' | '>' | ',' | '.'));
        if p2.starts_with("http://") || p2.starts_with("https://") {
            links.push((String::new(), p2.to_string()));
            if palavra.ends_with(char::is_whitespace) {
                final_.push(' ');
            }
            continue;
        }
        final_.push_str(palavra);
    }
    // os restos de lista ("•", "*", "-") e espaços
    let final_ = final_.replace("**", "").replace(" •", "").replace("• ", "");
    let final_ = final_.trim().trim_end_matches(|c: char| c == '•' || c == '-' || c == '*' || c.is_whitespace()).to_string();
    // sem repetir a mesma página
    let mut vistos = std::collections::HashSet::new();
    links.retain(|(_, u)| vistos.insert(u.trim_end_matches('/').to_string()));
    (final_, links)
}
fn links_md(s: &str) -> Vec<(String, String)> {
    let mut v = Vec::new();
    let mut rest = s;
    while let Some(a) = rest.find('[') {
        let Some(b) = rest[a..].find("](").map(|x| x + a) else { break };
        let Some(c) = rest[b..].find(')').map(|x| x + b) else { break };
        let url = rest[b + 2..c].trim();
        if url.starts_with("http") {
            v.push((rest[a + 1..b].trim().to_string(), url.to_string()));
        }
        rest = &rest[c + 1..];
    }
    // sem markdown: as URLs soltas
    if v.is_empty() {
        for p in s.split_whitespace() {
            let p = p.trim_matches(|c: char| matches!(c, '(' | ')' | '<' | '>' | ',' | '•'));
            if p.starts_with("http") {
                v.push((String::new(), p.to_string()));
            }
        }
    }
    v
}
/// o site de uma URL ("g1.globo.com")
fn dominio(u: &str) -> String {
    let s = u.split("//").nth(1).unwrap_or(u);
    s.split('/').next().unwrap_or(s).trim_start_matches("www.").to_string()
}

// ---- as miniaturas (a og:image de cada página), buscadas numa thread, uma vez por URL
enum Mini {
    Buscando,
    Nada,
    Pronta(u32, u32, Vec<u8>),
}
static MINIS: Mutex<Option<HashMap<String, Mini>>> = Mutex::new(None);
static MINI_BMP: Global<Option<HashMap<String, Option<ID2D1Bitmap>>>> = Global::new(None);
fn mini_pede(url: &str) {
    {
        let mut g = MINIS.lock().unwrap();
        let m = g.get_or_insert_with(HashMap::new);
        if m.contains_key(url) {
            return;
        }
        m.insert(url.to_string(), Mini::Buscando);
    }
    let url = url.to_string();
    std::thread::spawn(move || {
        let r = (|| {
            let html = http_get(&url)?;
            let h = String::from_utf8_lossy(&html[..html.len().min(400_000)]).to_string();
            // og:image ou twitter:image (o content antes ou depois do property)
            let mut img = None;
            for chave in ["og:image", "twitter:image"] {
                if let Some(k) = h.find(&format!("\"{chave}\"")).or_else(|| h.find(&format!("'{chave}'"))) {
                    let ini = h[..k].rfind('<').unwrap_or(0);
                    let fim = k + h[k..].find('>').unwrap_or(0);
                    let tag = &h[ini..fim];
                    if let Some(c) = tag.find("content=") {
                        let q = tag[c + 8..].chars().next().unwrap_or('"');
                        let v: String = tag[c + 9..].chars().take_while(|ch| *ch != q).collect();
                        if v.starts_with("http") {
                            img = Some(v.replace("&amp;", "&"));
                            break;
                        }
                    }
                }
            }
            let (w, h_, px) = decode_bytes(&http_get(&img?)?)?;
            // reduz para 160 px de largura (a miniatura é pequena)
            let (nw, nh) = if w > 160 { (160u32, (h_ as u64 * 160 / w as u64).max(1) as u32) } else { (w, h_) };
            let mut o = vec![0u8; (nw * nh * 4) as usize];
            for y in 0..nh {
                for x in 0..nw {
                    let (sx, sy) = ((x as u64 * w as u64 / nw as u64) as u32, (y as u64 * h_ as u64 / nh as u64) as u32);
                    let s_ = ((sy * w + sx) * 4) as usize;
                    let d = ((y * nw + x) * 4) as usize;
                    o[d..d + 4].copy_from_slice(&px[s_..s_ + 4]);
                }
            }
            Some((nw, nh, o))
        })();
        let mut g = MINIS.lock().unwrap();
        let m = g.get_or_insert_with(HashMap::new);
        m.insert(url, match r {
            Some((w, h, px)) => Mini::Pronta(w, h, px),
            None => Mini::Nada,
        });
    });
}
/// a miniatura pronta (cria o bitmap uma vez); None = ainda buscando ou sem imagem
fn mini_bmp(dc: &ID2D1DeviceContext, url: &str) -> (Option<ID2D1Bitmap>, bool) {
    let cache = MINI_BMP.get().get_or_insert_with(HashMap::new);
    if let Some(b) = cache.get(url) {
        return (b.clone(), false);
    }
    let mut g = MINIS.lock().unwrap();
    let m = g.get_or_insert_with(HashMap::new);
    match m.get(url) {
        None => {
            drop(g);
            mini_pede(url);
            (None, true)
        }
        Some(Mini::Buscando) => (None, true),
        Some(Mini::Nada) => {
            cache.insert(url.to_string(), None);
            (None, false)
        }
        Some(Mini::Pronta(w, h, px)) => {
            let b = ui::bitmap(&dc.cast().unwrap(), *w, *h, px);
            cache.insert(url.to_string(), b.clone());
            (b, false)
        }
    }
}
/// a altura da fileira de cartões
const CARTOES_H: f32 = 62.0;
/// os cartões das fontes embaixo de um balão (até 3)
unsafe fn cartoes_fontes(dc: &ID2D1DeviceContext, br: &ID2D1SolidColorBrush, x0: f32, y0: f32, larg: f32, links: &[(String, String)], msg: usize) {
    let f = fonts();
    let n = links.len().min(3);
    if n == 0 {
        return;
    }
    let gap = 8.0;
    let cw = ((larg - gap * (n - 1) as f32) / n as f32).min(230.0);
    let azul = tinta(&hexcor(0x4da3ff, 1.0));
    let mut buscando = false;
    for (k, (tit, url)) in links.iter().take(n).enumerate() {
        let r = rf(x0 + k as f32 * (cw + gap), y0, x0 + k as f32 * (cw + gap) + cw, y0 + CARTOES_H);
        let arg = (msg * 8 + k) as i32;
        let q = hq(HitId::Fonte, arg);
        br.SetColor(&tinta(&col(1.0, 1.0, 1.0, 0.06 + 0.06 * q.min(1.0))));
        dc.FillRoundedRectangle(&comum::rr(r, 10.0, 10.0), br);
        // a miniatura (ou a inicial do site)
        let im = rf(r.left + 6.0, r.top + 6.0, r.left + 56.0, r.bottom - 6.0);
        let (bmp, esperando) = mini_bmp(dc, url);
        buscando |= esperando;
        match bmp {
            Some(b) => {
                let bs = b.GetSize();
                // corta no meio para preencher o quadrado
                let (iw, ih) = (im.right - im.left, im.bottom - im.top);
                let k_ = (bs.width / iw).min(bs.height / ih);
                let (sw, sh) = (iw * k_, ih * k_);
                let src = rf((bs.width - sw) / 2.0, (bs.height - sh) / 2.0, (bs.width + sw) / 2.0, (bs.height + sh) / 2.0);
                if let Ok(g) = ui::d2d().CreateRoundedRectangleGeometry(&comum::rr(im, 7.0, 7.0)) {
                    layer_op(dc, 1.0, Some(g.cast().unwrap()), None, INF);
                    let antes = luz_pausa(false);
                    dc.DrawBitmap(&b, Some(&im), 1.0, D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC, Some(&src), None);
                    luz_pausa(antes);
                    dc.PopLayer();
                }
            }
            None => {
                br.SetColor(&alfa(azul, 0.22));
                dc.FillRoundedRectangle(&comum::rr(im, 7.0, 7.0), br);
                let d = dominio(url);
                let ini: String = d.chars().next().map(|c| c.to_uppercase().collect()).unwrap_or_default();
                text(dc, br, &ini, &f.sub_c, im, azul);
            }
        }
        // o título (2 linhas) e o site em azul
        let tx = rf(im.right + 8.0, r.top + 6.0, r.right - 6.0, r.top + 34.0); // duas linhas
        let titulo = if tit.is_empty() { dominio(url) } else { tit.clone() };
        br.SetColor(&tinta(&WHITE));
        dc.DrawText(&w(&titulo), &fonte_q(11.0, DWRITE_FONT_WEIGHT_SEMI_BOLD), &tx, br, D2D1_DRAW_TEXT_OPTIONS_CLIP, DWRITE_MEASURING_MODE_NATURAL);
        text(dc, br, &dominio(url), &f.small, rf(im.right + 8.0, r.bottom - 19.0, r.right - 6.0, r.bottom - 4.0), azul);
        add_hit(HitId::Fonte, r, arg);
    }
    if buscando {
        start_frames();
    }
}
/// clicou num cartão: abre a página
fn fonte_abre(arg: i32) {
    if s().foto.is_some() {
        return;
    }
    let (msg, k) = (arg.max(0) as usize / 8, arg.max(0) as usize % 8);
    if let Some(t) = px().chat_txt_orig.get(msg) {
        if let Some((_, u)) = fontes(t).1.get(k) {
            if u.starts_with("https://") || u.starts_with("http://") {
                shell::abrir(Some("open"), u, "", "", SW_SHOWNORMAL);
            }
        }
    }
}