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
4.5 KB
Raw Blame
//! Porte de src\comum\simbolos.h: SF Symbols (icones\simbolos\*.svg, um caminho só com M L Q Z e Y invertido)
//! viram ID2D1PathGeometry (com cache) e são preenchidos na cor do pincel, centralizados na caixa.

use std::collections::HashMap;
use std::path::PathBuf;

use windows::core::Interface;
use windows::Win32::Graphics::Direct2D::Common::*;
use windows::Win32::Graphics::Direct2D::*;

use crate::{mat, pt, Global, RectF};

struct Sym {
    geo: ID2D1PathGeometry,
}

static DIR: Global<Option<PathBuf>> = Global::new(None);
static CACHE: Global<Option<HashMap<(usize, String), Option<Sym>>>> = Global::new(None);

/// pasta com os .svg (padrão: icones\simbolos da instalação)
pub fn dir() -> PathBuf {
    DIR.get().get_or_insert_with(|| crate::install_dir().join("icones").join("simbolos")).clone()
}
pub fn set_dir(p: PathBuf) {
    *DIR.get() = Some(p);
}

fn attr(t: &str, chave: &str) -> f32 {
    t.find(chave)
        .map(|p| {
            let s = &t[p + chave.len()..];
            let fim = s.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).unwrap_or(s.len());
            s[..fim].parse().unwrap_or(0.0)
        })
        .unwrap_or(0.0)
}

unsafe fn carregar(f: &ID2D1Factory, nome: &str) -> Option<Sym> {
    let t = std::fs::read_to_string(dir().join(format!("{nome}.svg"))).ok()?;
    let w = attr(&t, "width='");
    let h = attr(&t, "height='");
    let d = t.find(" d='")?;
    if w <= 0.0 || h <= 0.0 {
        return None;
    }
    let fim = t[d + 4..].find('\'')? + d + 4;
    let path = &t[d + 4..fim];
    let geo = f.CreatePathGeometry().ok()?;
    let sink = geo.Open().ok()?;
    sink.SetFillMode(D2D1_FILL_MODE_WINDING);
    let b = path.as_bytes();
    let mut i = 0usize;
    let num = |i: &mut usize| -> f32 {
        while *i < b.len() && matches!(b[*i], b' ' | b',' | b'\n' | b'\r' | b'\t') {
            *i += 1;
        }
        let ini = *i;
        if *i < b.len() && (b[*i] == b'-' || b[*i] == b'+') {
            *i += 1;
        }
        while *i < b.len() && (b[*i].is_ascii_digit() || b[*i] == b'.' || b[*i] == b'e' || b[*i] == b'E') {
            *i += 1;
        }
        path[ini..*i].parse().unwrap_or(0.0)
    };
    let ponto = |i: &mut usize| {
        let x = num(i);
        let y = num(i);
        pt(x, h - y)
    };
    let mut aberto = false;
    while i < b.len() {
        match b[i] {
            b'M' => {
                i += 1;
                if aberto {
                    sink.EndFigure(D2D1_FIGURE_END_OPEN);
                }
                sink.BeginFigure(ponto(&mut i), D2D1_FIGURE_BEGIN_FILLED);
                aberto = true;
            }
            b'L' => {
                i += 1;
                sink.AddLine(ponto(&mut i));
            }
            b'Q' => {
                i += 1;
                let a = ponto(&mut i);
                let c = ponto(&mut i);
                sink.AddQuadraticBezier(&D2D1_QUADRATIC_BEZIER_SEGMENT { point1: a, point2: c });
            }
            b'Z' => {
                i += 1;
                if aberto {
                    sink.EndFigure(D2D1_FIGURE_END_CLOSED);
                }
                aberto = false;
            }
            _ => i += 1,
        }
    }
    if aberto {
        sink.EndFigure(D2D1_FIGURE_END_OPEN);
    }
    sink.Close().ok()?;
    Some(Sym { geo })
}

/// Desenha o símbolo centralizado em `caixa` (mantendo a proporção). false se o .svg não existir.
pub unsafe fn draw(rt: &ID2D1RenderTarget, nome: &str, caixa: RectF, b: &ID2D1Brush) -> bool {
    if nome.is_empty() {
        return false;
    }
    let Ok(f) = rt.GetFactory() else { return false };
    // uma geometria por fábrica (geometria de uma fábrica não serve em outra)
    let chave = (f.as_raw() as usize, nome.to_string());
    let cache = CACHE.get().get_or_insert_with(HashMap::new);
    let s = cache.entry(chave).or_insert_with(|| carregar(&f, nome));
    let Some(s) = s else { return false };
    let Ok(g) = s.geo.GetBounds(None) else { return false };
    let gw = (g.right - g.left).max(1.0);
    let gh = (g.bottom - g.top).max(1.0);
    let bw = caixa.right - caixa.left;
    let bh = caixa.bottom - caixa.top;
    let k = (bw / gw).min(bh / gh);
    let x = caixa.left + (bw - gw * k) / 2.0 - g.left * k;
    let y = caixa.top + (bh - gh * k) / 2.0 - g.top * k;
    let mut old = mat::ident();
    rt.GetTransform(&mut old);
    let m = mat::mul(&mat::mul(&mat::scale(k, k, 0.0, 0.0), &mat::trans(x, y)), &old);
    rt.SetTransform(&m);
    rt.FillGeometry(&s.geo, b, None);
    rt.DrawGeometry(&s.geo, b, 1.0, None);
    rt.SetTransform(&old);
    true
}