Il documento tiene un compositor e il guscio chiede due cose diverse: l'altezza della pagina, una volta, e poi solo la finestra visibile. Su Wikipedia a 700 px la pagina intera è 53,4 MB di immagine e 550-650 ms; sei schermate di scorrimento costano 54-66 tessere, 13-16 MB, e ogni finestra si compone in 33-54 ms senza reimpaginare. Confine C: engine_doc_misura, engine_doc_viewport, engine_doc_tessere. Nel motore render_contenuto_comandi impagina senza rasterizzare: la pagina intera non viene più allocata nemmeno per un istante. Desktop: la finestra interattiva usa il compositor, --render-out resta sulla resa piena (un PNG ha bisogno di tutti i pixel). Nuovo --misura-finestra per rifare il confronto invece di crederci. Sailfish: EngineView è alto quanto la finestra e incollato a contentY, quindi copre sempre la banda che si guarda; contentHeight ora è la pagina intera, non l'immagine. Lo scorrimento si passa in pixel CSS e il motore lo moltiplica per lo zoom. La firma del compositor comprende larghezza, altezza, zoom e impronta dello stato dei moduli: senza quest'ultima, scrivere in un campo non ridisegnava e restava il testo di prima. 4 test nuovi (finestra.rs): la misura è quella della pagina, la finestra mostra il pezzo giusto, scorrere non rifà le tessere, cambiare larghezza le rifà. 141 reftest, CI verde.
1749 lines
69 KiB
Rust
1749 lines
69 KiB
Rust
//! Mosaic desktop: finestra nativa che mostra il raster del motore.
|
||
//!
|
||
//! Non usa Qt né toolkit: `minifb` apre la finestra e fornisce i byte del buffer,
|
||
//! il motore produce RGBA. Comandi: rotella = scroll, Ctrl+rotella o +/− = zoom,
|
||
//! frecce/PgUp/PgDn/Home/End = scorrimento, 0 = zoom iniziale, R = ricarica, Q/Esc = esci.
|
||
//!
|
||
//! Con `--render-out FILE` non apre finestre: renderizza e scrive un PNG (serve alla
|
||
//! verifica in CI e sul server senza display).
|
||
|
||
use std::path::{Path, PathBuf};
|
||
use std::time::Instant;
|
||
|
||
use engine::{pngio, ControlKind, Focusable, FormState, RenderOptions};
|
||
use minifb::{Key, KeyRepeat, MouseButton, MouseMode, Window, WindowOptions};
|
||
|
||
struct Page {
|
||
html: String,
|
||
css: String,
|
||
base_dir: PathBuf,
|
||
/// indirizzo del documento quando arriva dalla rete (M2.6)
|
||
base_url: Option<String>,
|
||
}
|
||
|
||
struct Rendered {
|
||
width: u32,
|
||
height: u32,
|
||
/// immagine piena: serve solo alla modalità senza finestra (`--render-out`).
|
||
/// Con la finestra aperta resta vuota e si compone a tessere.
|
||
rgba: Vec<u8>,
|
||
/// composizione a tessere: c'è quando il guscio disegna una finestra
|
||
compositor: Option<engine::compositor::Compositor>,
|
||
ms: f64,
|
||
focusables: Vec<Focusable>,
|
||
/// albero impaginato: serve a sapere quale nodo sta sotto il puntatore
|
||
layout: engine::layout::LayoutBox,
|
||
}
|
||
|
||
/// Nodo più profondo sotto il punto (px CSS).
|
||
fn nodo_al_punto(b: &engine::layout::LayoutBox, x: f32, y: f32) -> Option<usize> {
|
||
let dentro =
|
||
x >= b.rect.x && x <= b.rect.x + b.rect.w && y >= b.rect.y && y <= b.rect.y + b.rect.h;
|
||
if !dentro {
|
||
return None;
|
||
}
|
||
for figlio in &b.children {
|
||
if let Some(n) = nodo_al_punto(figlio, x, y) {
|
||
return Some(n);
|
||
}
|
||
}
|
||
// i controlli non hanno un box proprio: vivono nelle righe del testo
|
||
for linea in &b.lines {
|
||
for run in &linea.runs {
|
||
if let Some(c) = &run.control {
|
||
let r = engine::layout::Rect::new(run.x, run.baseline - c.above, c.width, c.height);
|
||
if x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h {
|
||
return Some(c.node);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
Some(b.node)
|
||
}
|
||
|
||
/// Centro del box che rappresenta il nodo, se è stato impaginato.
|
||
fn centro_del_nodo(b: &engine::layout::LayoutBox, nodo: usize) -> Option<(f32, f32)> {
|
||
if b.node == nodo && b.rect.w > 0.0 && b.rect.h > 0.0 {
|
||
return Some((b.rect.x + b.rect.w / 2.0, b.rect.y + b.rect.h / 2.0));
|
||
}
|
||
// un controllo (pulsante, campo) sta in una riga, non in un box
|
||
for linea in &b.lines {
|
||
for run in &linea.runs {
|
||
if let Some(c) = &run.control {
|
||
if c.node == nodo {
|
||
return Some((
|
||
run.x + c.width / 2.0,
|
||
run.baseline - c.above + c.height / 2.0,
|
||
));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
for figlio in &b.children {
|
||
if let Some(c) = centro_del_nodo(figlio, nodo) {
|
||
return Some(c);
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
fn nodo_con_id(doc: &engine::dom::Document, id: &str) -> Option<usize> {
|
||
for (i, n) in doc.nodes.iter().enumerate() {
|
||
if let engine::dom::NodeKind::Element(e) = &n.kind {
|
||
if e.attr("id") == Some(id) {
|
||
return Some(i);
|
||
}
|
||
}
|
||
}
|
||
None
|
||
}
|
||
|
||
/// Consegna un evento a un nodo, con la propagazione agli antenati.
|
||
fn eventi_su(
|
||
macchina: &mut engine::script::Macchina,
|
||
contenuto: &mut engine::ContenutoPagina,
|
||
nodo: usize,
|
||
tipo: &str,
|
||
) -> usize {
|
||
let rami = catena_antenati(&contenuto.doc, nodo);
|
||
macchina.evento(&mut contenuto.doc, tipo, &rami, 0.0, 0.0)
|
||
}
|
||
|
||
/// Esegue le `fetch` che gli script hanno accodato e consegna le risposte.
|
||
/// Restituisce vero se qualche callback ha modificato il DOM.
|
||
fn servi_fetch(
|
||
macchina: &mut engine::script::Macchina,
|
||
contenuto: &mut engine::ContenutoPagina,
|
||
client: &engine::net::Client,
|
||
base_url: Option<&str>,
|
||
) -> bool {
|
||
let mut cambiato = false;
|
||
for (id, riferito, metodo, corpo) in macchina.richieste_pendenti() {
|
||
// `fetch('dati.json')` è relativo al documento: si risolve come le altre risorse
|
||
let url = engine::resource::risolvi_url(base_url, &riferito).unwrap_or(riferito);
|
||
let limiti = engine::net::Limiti::default();
|
||
let esito = if metodo == "POST" {
|
||
client.post(&url, corpo.as_deref().unwrap_or(""), &limiti)
|
||
} else {
|
||
client.get(&url, &limiti)
|
||
};
|
||
let (stato, testo) = match esito {
|
||
Ok(r) => match r.text() {
|
||
Ok(t) => (r.status as i32, t),
|
||
Err(e) => {
|
||
eprintln!("mosaic: risposta illeggibile da {}: {}", url, e);
|
||
(-1, String::new())
|
||
}
|
||
},
|
||
Err(e) => {
|
||
eprintln!("mosaic: fetch {} fallita: {}", url, e);
|
||
(-1, String::new())
|
||
}
|
||
};
|
||
// la fetch può scrivere nel DOM: va contata come modifica
|
||
if macchina.consegna_risposta(&mut contenuto.doc, id, stato, &testo) > 0 {
|
||
cambiato = true;
|
||
}
|
||
}
|
||
cambiato
|
||
}
|
||
|
||
/// Ora corrente in millisecondi: è il motore a non doverla conoscere.
|
||
fn adesso_ms() -> u64 {
|
||
std::time::SystemTime::now()
|
||
.duration_since(std::time::UNIX_EPOCH)
|
||
.map(|d| d.as_millis() as u64)
|
||
.unwrap_or(0)
|
||
}
|
||
|
||
/// Fa avanzare i timer della pagina con l'orologio vero. Restituisce vero se
|
||
/// qualche timer ha modificato il DOM (la pagina va ridisegnata).
|
||
fn pompa_timer(
|
||
macchina: &mut engine::script::Macchina,
|
||
contenuto: &mut engine::ContenutoPagina,
|
||
r: Option<&Rendered>,
|
||
form: &mut FormState,
|
||
) -> bool {
|
||
let adesso = adesso_ms();
|
||
let eseguiti = macchina.pompa_timer(&mut contenuto.doc, adesso, 100);
|
||
if eseguiti == 0 {
|
||
return false;
|
||
}
|
||
let mut cambiato = true;
|
||
if let Some(r) = r {
|
||
applica_valori_scritti(macchina, r, form);
|
||
}
|
||
cambiato |= false;
|
||
cambiato
|
||
}
|
||
|
||
/// Applica allo stato dei moduli i valori scritti dagli script
|
||
/// (`campo.value = 'x'`). Restituisce vero se qualcosa è cambiato.
|
||
fn applica_valori_scritti(
|
||
macchina: &mut engine::script::Macchina,
|
||
r: &Rendered,
|
||
form: &mut FormState,
|
||
) -> bool {
|
||
let mut cambiato = false;
|
||
for (nodo, valore) in macchina.preleva_valori_scritti() {
|
||
if let Some(f) = r.focusables.iter().find(|f| f.node == nodo) {
|
||
if form.values.get(&f.key) != Some(&valore) {
|
||
form.values.insert(f.key.clone(), valore);
|
||
cambiato = true;
|
||
}
|
||
}
|
||
}
|
||
cambiato
|
||
}
|
||
|
||
/// Codice di uno `<script src>`: dalla rete se il documento viene da lì,
|
||
/// altrimenti dal disco accanto alla pagina.
|
||
fn carica_script(src: &str, base_dir: &std::path::Path, base_url: Option<&str>) -> Option<String> {
|
||
if let Some(url) = engine::resource::risolvi_url(base_url, src) {
|
||
let limiti = engine::net::Limiti::default();
|
||
match engine::net::get(&url, &limiti) {
|
||
Ok(r) if (200..300).contains(&r.status) => return r.text().ok(),
|
||
Ok(r) => {
|
||
eprintln!("script {}: HTTP {}", url, r.status);
|
||
return None;
|
||
}
|
||
Err(e) => {
|
||
eprintln!("script {}: {}", url, e);
|
||
return None;
|
||
}
|
||
}
|
||
}
|
||
match std::fs::read_to_string(base_dir.join(src)) {
|
||
Ok(c) => Some(c),
|
||
Err(e) => {
|
||
eprintln!("script {}: {}", src, e);
|
||
None
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Esegue gli script della pagina (inline ed esterni) e riporta gli errori.
|
||
fn avvia_script(
|
||
contenuto: &mut engine::ContenutoPagina,
|
||
macchina: &mut engine::script::Macchina,
|
||
base_dir: &std::path::Path,
|
||
base_url: Option<&str>,
|
||
) {
|
||
let caricatore = |src: &str| carica_script(src, base_dir, base_url);
|
||
for e in contenuto.esegui_script_con(macchina, &caricatore) {
|
||
eprintln!("script: {}", e);
|
||
}
|
||
}
|
||
|
||
/// Consegna gli eventi di un clic: `submit` al form se il bersaglio è un
|
||
/// pulsante, poi `click` al nodo con la propagazione agli antenati.
|
||
/// Restituisce quanti gestori hanno reagito.
|
||
fn consegna_eventi_clic(
|
||
macchina: &mut engine::script::Macchina,
|
||
contenuto: &mut engine::ContenutoPagina,
|
||
form: &FormState,
|
||
r: &Rendered,
|
||
cx: f32,
|
||
cy: f32,
|
||
base_url_del_documento: Option<&str>,
|
||
) -> AzioneClic {
|
||
let Some(nodo) = nodo_al_punto(&r.layout, cx, cy) else {
|
||
return AzioneClic::Nessuna(0);
|
||
};
|
||
// `element.value` deve vedere quello che l'utente ha scritto
|
||
let mut valori = std::collections::HashMap::new();
|
||
for f in &r.focusables {
|
||
if let Some(v) = form.values.get(&f.key) {
|
||
valori.insert(f.node, v.clone());
|
||
}
|
||
}
|
||
macchina.imposta_valori(valori);
|
||
let mut gestori = 0;
|
||
if let Some(f) = r.focusables.iter().find(|f| f.node == nodo) {
|
||
if f.kind == ControlKind::Button {
|
||
let bersaglio = antenato_con_tag(&contenuto.doc, nodo, "form").unwrap_or(nodo);
|
||
let rami = catena_antenati(&contenuto.doc, bersaglio);
|
||
gestori += macchina.evento(&mut contenuto.doc, "submit", &rami, cx, cy);
|
||
// senza `preventDefault` l'invio va fatto davvero
|
||
if !macchina.preventuto_default() {
|
||
if let Some(form_node) = antenato_con_tag(&contenuto.doc, nodo, "form") {
|
||
match engine::invio::prepara(
|
||
&contenuto.doc,
|
||
form,
|
||
form_node,
|
||
base_url_del_documento,
|
||
) {
|
||
Ok(richiesta) => return AzioneClic::Invia(richiesta),
|
||
Err(e) => eprintln!("mosaic: invio non preparabile: {}", e),
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
let rami = catena_antenati(&contenuto.doc, nodo);
|
||
gestori += macchina.evento(&mut contenuto.doc, "click", &rami, cx, cy);
|
||
AzioneClic::Nessuna(gestori)
|
||
}
|
||
|
||
/// Esegue l'invio del formulario e sostituisce la pagina con la risposta.
|
||
fn esegui_invio(
|
||
page: &mut Page,
|
||
contenuto: &mut engine::ContenutoPagina,
|
||
macchina: &mut engine::script::Macchina,
|
||
richiesta: &engine::invio::Invio,
|
||
client: &std::rc::Rc<engine::net::Client>,
|
||
) -> Result<(), String> {
|
||
let limiti = engine::net::Limiti::default();
|
||
let risposta = match (&richiesta.corpo, richiesta.metodo.as_str()) {
|
||
// il tipo di contenuto è quello preparato da `invio`: urlencoded, multipart o testo
|
||
(Some(corpo), "POST") => client.post_con(
|
||
&richiesta.url,
|
||
corpo,
|
||
richiesta
|
||
.content_type
|
||
.as_deref()
|
||
.unwrap_or("application/x-www-form-urlencoded"),
|
||
&limiti,
|
||
),
|
||
_ => client.get(&richiesta.url, &limiti),
|
||
}?;
|
||
let testo = risposta.text()?;
|
||
eprintln!(
|
||
"mosaic: invio {} -> HTTP {}",
|
||
richiesta.url, risposta.status
|
||
);
|
||
page.html = testo;
|
||
page.base_url = Some(risposta.url.clone());
|
||
*contenuto = engine::ContenutoPagina::da_html(&page.html);
|
||
contenuto.client = Some(client.clone());
|
||
if let Ok(m) = engine::script::Macchina::nuova() {
|
||
*macchina = m;
|
||
let cartella = page.base_dir.clone();
|
||
let indirizzo = page.base_url.clone();
|
||
avvia_script(contenuto, macchina, &cartella, indirizzo.as_deref());
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// Cosa fare dopo un clic: niente, oppure inviare un formulario.
|
||
enum AzioneClic {
|
||
Nessuna(usize),
|
||
Invia(engine::invio::Invio),
|
||
}
|
||
|
||
/// Primo antenato (o il nodo stesso) con quel nome di elemento.
|
||
fn antenato_con_tag(doc: &engine::dom::Document, nodo: usize, tag: &str) -> Option<usize> {
|
||
let mut corrente = Some(nodo);
|
||
while let Some(n) = corrente {
|
||
if doc.element_name(n) == Some(tag) {
|
||
return Some(n);
|
||
}
|
||
corrente = doc.nodes.get(n).and_then(|x| x.parent);
|
||
}
|
||
None
|
||
}
|
||
|
||
/// Nodo e antenati, dal più profondo alla radice: è l'ordine di propagazione.
|
||
fn catena_antenati(doc: &engine::dom::Document, nodo: usize) -> Vec<usize> {
|
||
let mut out = Vec::new();
|
||
let mut corrente = Some(nodo);
|
||
while let Some(n) = corrente {
|
||
out.push(n);
|
||
corrente = doc.nodes.get(n).and_then(|x| x.parent);
|
||
}
|
||
out
|
||
}
|
||
|
||
fn main() {
|
||
let mut args = std::env::args().skip(1);
|
||
let mut html_path: Option<PathBuf> = None;
|
||
let mut url: Option<String> = None;
|
||
// solo per verifica: disegna la barra degli indirizzi nel PNG senza finestra
|
||
let mut prova_barra: Option<String> = None;
|
||
let mut rete_esterna = false;
|
||
let mut css_path: Option<PathBuf> = None;
|
||
let mut zoom = 1.0f64;
|
||
let mut size = (1100u32, 800u32);
|
||
let mut render_out: Option<PathBuf> = None;
|
||
// stampa quanto costa la pagina intera e quanto la finestra a tessere
|
||
let mut misura_finestra = false;
|
||
// clic da consegnare prima di scrivere il PNG: serve a provare gli eventi
|
||
// senza finestra (il percorso è lo stesso del mouse, non un altro codice)
|
||
let mut clic_nodi: Vec<String> = Vec::new();
|
||
// testo da scrivere in un campo prima del PNG: prova l'evento `input`
|
||
let mut digitazioni: Vec<(String, String)> = Vec::new();
|
||
// attesa prima dello scatto: serve a provare i timer senza finestra
|
||
let mut aspetta: u64 = 0;
|
||
let mut font = default_font();
|
||
|
||
while let Some(a) = args.next() {
|
||
match a.as_str() {
|
||
"--prova-barra" => prova_barra = args.next(),
|
||
"--rete-esterna" => rete_esterna = true,
|
||
"--html" => html_path = args.next().map(PathBuf::from),
|
||
"--url" => url = args.next(),
|
||
"--aspetta" => {
|
||
aspetta = args.next().and_then(|v| v.parse::<u64>().ok()).unwrap_or(0);
|
||
}
|
||
"--digita" => {
|
||
if let Some(v) = args.next() {
|
||
if let Some((id, testo)) = v.split_once('=') {
|
||
digitazioni.push((id.to_string(), testo.to_string()));
|
||
}
|
||
}
|
||
}
|
||
"--clic-nodo" => {
|
||
if let Some(id) = args.next() {
|
||
clic_nodi.push(id);
|
||
}
|
||
}
|
||
"--css" => css_path = args.next().map(PathBuf::from),
|
||
"--zoom" => {
|
||
zoom = args
|
||
.next()
|
||
.and_then(|v| v.parse::<f64>().ok())
|
||
.unwrap_or(1.0)
|
||
.clamp(0.5, 4.0)
|
||
}
|
||
"--size" => {
|
||
if let Some(v) = args.next() {
|
||
if let Some((w, h)) = v.split_once('x') {
|
||
size = (w.parse().unwrap_or(1100), h.parse().unwrap_or(800));
|
||
}
|
||
}
|
||
}
|
||
"--font" => font = args.next().map(PathBuf::from).unwrap_or_else(default_font),
|
||
"--render-out" => render_out = args.next().map(PathBuf::from),
|
||
"--misura-finestra" => misura_finestra = true,
|
||
"--aiuto" | "--help" | "-h" => {
|
||
println!(
|
||
"mosaic-desktop [--html FILE] [--css FILE] [--zoom N] [--size WxH]\n\
|
||
\x20 [--font TTF] [--render-out PNG]\n\
|
||
\x20--url URL apre una pagina: http, https o solo dominio (esempio.it)\n\
|
||
\x20--rete-esterna la rete gira in un processo a parte (mosaic-net)\n\n\
|
||
Rotella: scroll · Ctrl+rotella o +/−: zoom · frecce/PgUp/PgDn/Home/End: scorri\n\
|
||
0: zoom 1.0 · R: ricarica\n\
|
||
Ctrl+L: scrivi un indirizzo (Invio apre, Esc annulla)\n\
|
||
Chiudi: pulsante della finestra, Esc, Q, Ctrl+Q, Ctrl+W"
|
||
);
|
||
return;
|
||
}
|
||
altro => eprintln!("argomento ignorato: {}", altro),
|
||
}
|
||
}
|
||
|
||
let (html_path, css_path) = match (html_path, css_path) {
|
||
(Some(h), c) => (h, c),
|
||
// con --url non serve un file: il documento arriva dalla rete
|
||
(None, c) if url.is_some() => (PathBuf::new(), c),
|
||
(None, _) => {
|
||
eprintln!("serve --html FILE oppure --url URL (o usa --help)");
|
||
std::process::exit(2);
|
||
}
|
||
};
|
||
|
||
let base_dir = html_path
|
||
.parent()
|
||
.map(|p| p.to_path_buf())
|
||
.unwrap_or_else(|| PathBuf::from("."));
|
||
|
||
// client con stato di sessione: cookie e cache vivono quanto la navigazione
|
||
// `--rete-esterna`: la rete vive in un processo a parte (i cookie stanno là)
|
||
let client = std::rc::Rc::new(if rete_esterna {
|
||
let programma = std::env::current_exe()
|
||
.ok()
|
||
.and_then(|e| e.parent().map(|d| d.join("mosaic-net")))
|
||
.unwrap_or_else(|| std::path::PathBuf::from("mosaic-net"));
|
||
match engine::net::Client::con_servizio_esterno(&programma) {
|
||
Ok(c) => {
|
||
eprintln!(
|
||
"mosaic: rete in un processo separato ({})",
|
||
programma.display()
|
||
);
|
||
c
|
||
}
|
||
Err(e) => {
|
||
eprintln!(
|
||
"mosaic: servizio di rete non avviato ({}), resto in processo",
|
||
e
|
||
);
|
||
engine::net::Client::new()
|
||
}
|
||
}
|
||
} else {
|
||
engine::net::Client::new()
|
||
});
|
||
|
||
// l'indirizzo iniziale e quello scritto nella barra passano dalla stessa
|
||
// funzione: così `--url esempio.it` (senza schema) funziona come dalla barra
|
||
let mut page = match match url.as_deref() {
|
||
Some(u) => apri_indirizzo(u, &client),
|
||
None => load(&html_path, css_path.as_deref(), &base_dir, None, &client),
|
||
} {
|
||
Ok(p) => p,
|
||
Err(e) => {
|
||
eprintln!("errore: {}", e);
|
||
std::process::exit(1);
|
||
}
|
||
};
|
||
|
||
// documento vivo: gli eventi modificano questo DOM e la pagina si ridisegna
|
||
// senza ripartire dall'HTML (M2.5b)
|
||
let mut contenuto = engine::ContenutoPagina::da_html(&page.html);
|
||
contenuto.client = Some(client.clone());
|
||
let mut macchina = match engine::script::Macchina::nuova() {
|
||
Ok(m) => m,
|
||
Err(e) => {
|
||
eprintln!("errore: interprete JavaScript non disponibile: {}", e);
|
||
std::process::exit(1);
|
||
}
|
||
};
|
||
avvia_script(
|
||
&mut contenuto,
|
||
&mut macchina,
|
||
&page.base_dir,
|
||
page.base_url.as_deref(),
|
||
);
|
||
|
||
// stato dei moduli: valori digitati e fuoco (vuoto in modalità headless)
|
||
let mut form = FormState::default();
|
||
// stato del tasto del mouse: serve il fronte di discesa, non il livello
|
||
let mut mouse_giu = false;
|
||
// font per misurare il testo: serve a posizionare il cursore dove si clicca
|
||
let metri = engine::FontHolder::load(&font).ok();
|
||
let mut ultimo_clic: Option<(std::time::Instant, f32, f32)> = None;
|
||
|
||
if misura_finestra {
|
||
misura_finestra_e_pagina(&page, &contenuto, size.0, size.1, zoom as f32, &font, &form);
|
||
}
|
||
|
||
// modalità senza finestra: render + PNG, utile su server e in CI
|
||
if let Some(out) = render_out {
|
||
match render_page(&page, &contenuto, size.0, size.1, zoom as f32, &font, &form) {
|
||
Ok(mut r) => {
|
||
if aspetta > 0 {
|
||
let fine = adesso_ms() + aspetta;
|
||
while adesso_ms() < fine {
|
||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||
// `--aspetta` serve proprio a dare tempo alla rete: senza
|
||
// servire le fetch qui, l'attesa non faceva nulla e la
|
||
// pagina restava sulla scritta iniziale
|
||
let mut cambiato = servi_fetch(
|
||
&mut macchina,
|
||
&mut contenuto,
|
||
&client,
|
||
page.base_url.as_deref(),
|
||
);
|
||
if pompa_timer(&mut macchina, &mut contenuto, Some(&r), &mut form) {
|
||
cambiato = true;
|
||
}
|
||
if cambiato {
|
||
if let Ok(nuovo) = render_page(
|
||
&page,
|
||
&contenuto,
|
||
size.0,
|
||
size.1,
|
||
zoom as f32,
|
||
&font,
|
||
&form,
|
||
) {
|
||
r = nuovo;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
for (id, testo) in &digitazioni {
|
||
let Some(nodo) = nodo_con_id(&contenuto.doc, id) else {
|
||
eprintln!("digita: nessun nodo con id {}", id);
|
||
continue;
|
||
};
|
||
let Some(f) = r.focusables.iter().find(|f| f.node == nodo).cloned() else {
|
||
eprintln!("digita: il nodo {} non è un controllo", id);
|
||
continue;
|
||
};
|
||
form.values.insert(f.key.clone(), testo.clone());
|
||
let mut valori = std::collections::HashMap::new();
|
||
for x in &r.focusables {
|
||
if let Some(v) = form.values.get(&x.key) {
|
||
valori.insert(x.node, v.clone());
|
||
}
|
||
}
|
||
macchina.imposta_valori(valori);
|
||
let rami = catena_antenati(&contenuto.doc, nodo);
|
||
let gestori = macchina.evento(&mut contenuto.doc, "input", &rami, 0.0, 0.0);
|
||
eprintln!("digita su {}: {} gestori di input", id, gestori);
|
||
match render_page(&page, &contenuto, size.0, size.1, zoom as f32, &font, &form)
|
||
{
|
||
Ok(nuovo) => r = nuovo,
|
||
Err(e) => eprintln!("errore dopo la digitazione: {}", e),
|
||
}
|
||
}
|
||
|
||
for id in &clic_nodi {
|
||
let Some(nodo) = nodo_con_id(&contenuto.doc, id) else {
|
||
eprintln!("clic: nessun nodo con id {}", id);
|
||
continue;
|
||
};
|
||
let Some((cx, cy)) = centro_del_nodo(&r.layout, nodo) else {
|
||
eprintln!("clic: nodo {} non impaginato", id);
|
||
continue;
|
||
};
|
||
let azione = consegna_eventi_clic(
|
||
&mut macchina,
|
||
&mut contenuto,
|
||
&form,
|
||
&r,
|
||
cx,
|
||
cy,
|
||
page.base_url.as_deref(),
|
||
);
|
||
let mut da_ridisegnare = false;
|
||
match azione {
|
||
AzioneClic::Nessuna(n) => {
|
||
eprintln!("clic su {}: {} gestori", id, n);
|
||
da_ridisegnare =
|
||
applica_valori_scritti(&mut macchina, &r, &mut form) || n > 0;
|
||
}
|
||
AzioneClic::Invia(richiesta) => {
|
||
eprintln!(
|
||
"invio del formulario: {} {}",
|
||
richiesta.metodo, richiesta.url
|
||
);
|
||
match esegui_invio(
|
||
&mut page,
|
||
&mut contenuto,
|
||
&mut macchina,
|
||
&richiesta,
|
||
&client,
|
||
) {
|
||
Ok(()) => da_ridisegnare = true,
|
||
Err(e) => eprintln!("mosaic: invio fallito: {}", e),
|
||
}
|
||
}
|
||
}
|
||
if da_ridisegnare {
|
||
match render_page(
|
||
&page,
|
||
&contenuto,
|
||
size.0,
|
||
size.1,
|
||
zoom as f32,
|
||
&font,
|
||
&form,
|
||
) {
|
||
Ok(nuovo) => r = nuovo,
|
||
Err(e) => eprintln!("errore dopo il clic: {}", e),
|
||
}
|
||
}
|
||
}
|
||
|
||
// le fetch accodate dagli script (anche dopo i clic) vanno eseguite
|
||
for _ in 0..4 {
|
||
if !servi_fetch(
|
||
&mut macchina,
|
||
&mut contenuto,
|
||
&client,
|
||
page.base_url.as_deref(),
|
||
) {
|
||
break;
|
||
}
|
||
match render_page(&page, &contenuto, size.0, size.1, zoom as f32, &font, &form)
|
||
{
|
||
Ok(nuovo) => r = nuovo,
|
||
Err(e) => {
|
||
eprintln!("errore dopo fetch: {}", e);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
if let Some(testo) = &prova_barra {
|
||
let (w, h) = (r.width, r.height);
|
||
let mut buf: Vec<u32> = r
|
||
.rgba
|
||
.chunks_exact(4)
|
||
.map(|p| ((p[0] as u32) << 16) | ((p[1] as u32) << 8) | p[2] as u32)
|
||
.collect();
|
||
disegna_barra(&mut buf, w, h, testo, &metri);
|
||
let mut rgba = Vec::with_capacity(r.rgba.len());
|
||
for pixel in &buf {
|
||
rgba.push((pixel >> 16) as u8);
|
||
rgba.push((pixel >> 8) as u8);
|
||
rgba.push(*pixel as u8);
|
||
rgba.push(255);
|
||
}
|
||
if let Err(e) = pngio::write_rgba(&out, w, h, &rgba) {
|
||
eprintln!("errore scrittura PNG: {}", e);
|
||
std::process::exit(1);
|
||
}
|
||
} else if let Err(e) = pngio::write_rgba(&out, r.width, r.height, &r.rgba) {
|
||
eprintln!("errore scrittura PNG: {}", e);
|
||
std::process::exit(1);
|
||
}
|
||
println!(
|
||
"{{\"png\":\"{}\",\"size\":[{},{}],\"zoom\":{},\"ms\":{:.2},\"barra\":{}}}",
|
||
out.display(),
|
||
r.width,
|
||
r.height,
|
||
zoom,
|
||
r.ms,
|
||
prova_barra.is_some()
|
||
);
|
||
return;
|
||
}
|
||
Err(e) => {
|
||
eprintln!("errore: {}", e);
|
||
std::process::exit(1);
|
||
}
|
||
}
|
||
}
|
||
|
||
// resize: true → la finestra si può ridimensionare e massimizzare come le altre
|
||
let opzioni = WindowOptions {
|
||
resize: true,
|
||
..WindowOptions::default()
|
||
};
|
||
let mut window = match Window::new("Mosaic", size.0 as usize, size.1 as usize, opzioni) {
|
||
Ok(w) => w,
|
||
Err(e) => {
|
||
eprintln!("impossibile aprire la finestra: {} (usa --render-out per il rendering senza display)", e);
|
||
std::process::exit(1);
|
||
}
|
||
};
|
||
window.set_target_fps(60);
|
||
|
||
let mut zoom = zoom as f32;
|
||
// barra degli indirizzi: `None` chiusa, `Some(testo)` aperta e in scrittura
|
||
let mut indirizzo: Option<String> = None;
|
||
let mut rendered: Option<Rendered> = None;
|
||
let mut scroll = 0f32;
|
||
let mut needs_render = true;
|
||
|
||
while window.is_open() {
|
||
// Chiusura: pulsante della finestra (is_open torna falso), Esc, Q, Ctrl+Q, Ctrl+W.
|
||
// `is_key_pressed` intercetta anche il tocco singolo; `is_key_down` copre Q tenuto.
|
||
// Con la barra degli indirizzi aperta questi tasti non chiudono nulla: `q`
|
||
// è una lettera e `Esc` annulla la scrittura.
|
||
let in_scrittura = indirizzo.is_some();
|
||
if !in_scrittura
|
||
&& (window.is_key_pressed(Key::Escape, KeyRepeat::No)
|
||
|| window.is_key_pressed(Key::Q, KeyRepeat::No)
|
||
|| (window.is_key_down(Key::Q)
|
||
&& (window.is_key_down(Key::LeftCtrl) || window.is_key_down(Key::RightCtrl)))
|
||
|| (window.is_key_pressed(Key::W, KeyRepeat::No)
|
||
&& (window.is_key_down(Key::LeftCtrl) || window.is_key_down(Key::RightCtrl))))
|
||
{
|
||
break;
|
||
}
|
||
|
||
let (w, h) = (window.get_size().0 as u32, window.get_size().1 as u32);
|
||
if w == 0 || h == 0 {
|
||
// finestra ridotta a icona: gli eventi vanno comunque letti, altrimenti
|
||
// il clic sul pulsante di chiusura non arriva mai e la finestra resta appesa
|
||
let _ = window.update();
|
||
continue;
|
||
}
|
||
|
||
// --- barra degli indirizzi (Ctrl+L) -------------------------------
|
||
// Aperta, prende tutti i tasti e sospende l'interazione con la pagina:
|
||
// altrimenti scrivere l'indirizzo finirebbe anche nel campo del modulo.
|
||
let ctrl = window.is_key_down(Key::LeftCtrl) || window.is_key_down(Key::RightCtrl);
|
||
if indirizzo.is_none() && ctrl && window.is_key_pressed(Key::L, KeyRepeat::No) {
|
||
indirizzo = Some(
|
||
page.base_url
|
||
.clone()
|
||
.or_else(|| url.clone())
|
||
.unwrap_or_default(),
|
||
);
|
||
}
|
||
if let Some(mut testo) = indirizzo.take() {
|
||
let shift = window.is_key_down(Key::LeftShift);
|
||
let invio = window.is_key_pressed(Key::Enter, KeyRepeat::No);
|
||
let annulla = window.is_key_pressed(Key::Escape, KeyRepeat::No);
|
||
if annulla {
|
||
needs_render = true;
|
||
} else if invio {
|
||
match apri_indirizzo(&testo, &client) {
|
||
Ok(p) => {
|
||
page = p;
|
||
url = page.base_url.clone();
|
||
contenuto = engine::ContenutoPagina::da_html(&page.html);
|
||
macchina = engine::script::Macchina::nuova().unwrap_or_else(|e| {
|
||
eprintln!("mosaic: interprete non disponibile: {}", e);
|
||
macchina
|
||
});
|
||
avvia_script(
|
||
&mut contenuto,
|
||
&mut macchina,
|
||
&page.base_dir,
|
||
page.base_url.as_deref(),
|
||
);
|
||
form = FormState::default();
|
||
scroll = 0.0;
|
||
needs_render = true;
|
||
}
|
||
Err(e) => {
|
||
// la barra resta aperta: l'indirizzo sbagliato si corregge
|
||
eprintln!("mosaic: {}", e);
|
||
indirizzo = Some(testo.clone());
|
||
}
|
||
}
|
||
} else {
|
||
if window.is_key_pressed(Key::Backspace, KeyRepeat::Yes) {
|
||
testo.pop();
|
||
}
|
||
if window.is_key_pressed(Key::Space, KeyRepeat::Yes) {
|
||
testo.push(' ');
|
||
}
|
||
for k in window.get_keys_pressed(KeyRepeat::No) {
|
||
// Ctrl+L e i tasti di servizio non devono finire nel testo
|
||
if k == Key::L && ctrl {
|
||
continue;
|
||
}
|
||
if let Some(c) = key_char(k, shift) {
|
||
testo.push(c);
|
||
}
|
||
}
|
||
indirizzo = Some(testo);
|
||
}
|
||
}
|
||
if let Some(testo) = &indirizzo {
|
||
// mentre si scrive l'indirizzo la pagina non reagisce
|
||
let buf = match &mut rendered {
|
||
Some(r) => blit(r, w, h, &mut scroll),
|
||
None => vec![0x00ff_ffff; (w * h) as usize],
|
||
};
|
||
let mut buf = buf;
|
||
disegna_barra(&mut buf, w, h, testo, &metri);
|
||
if let Err(e) = window.update_with_buffer(&buf, w as usize, h as usize) {
|
||
eprintln!("errore di disegno: {}", e);
|
||
break;
|
||
}
|
||
continue;
|
||
}
|
||
|
||
// zoom: rotella con Ctrl oppure + / -
|
||
if let Some((_, dy)) = window.get_scroll_wheel() {
|
||
let ctrl = window.is_key_down(Key::LeftCtrl) || window.is_key_down(Key::RightCtrl);
|
||
if ctrl {
|
||
let nuovo = (zoom * if dy > 0.0 { 1.1 } else { 1.0 / 1.1 }).clamp(0.5, 4.0);
|
||
if (nuovo - zoom).abs() > 1e-4 {
|
||
zoom = nuovo;
|
||
needs_render = true;
|
||
}
|
||
} else {
|
||
// tre righe di testo, in pixel del dispositivo: a zoom alto la
|
||
// rotella deve muoversi di quanto si vede, non di 60 px fissi
|
||
scroll -= dy * 60.0 * zoom;
|
||
}
|
||
}
|
||
if window.is_key_pressed(Key::Equal, KeyRepeat::Yes)
|
||
|| window.is_key_pressed(Key::NumPadPlus, KeyRepeat::Yes)
|
||
{
|
||
zoom = (zoom * 1.1).clamp(0.5, 4.0);
|
||
needs_render = true;
|
||
}
|
||
if window.is_key_pressed(Key::Minus, KeyRepeat::Yes)
|
||
|| window.is_key_pressed(Key::NumPadMinus, KeyRepeat::Yes)
|
||
{
|
||
zoom = (zoom / 1.1).clamp(0.5, 4.0);
|
||
needs_render = true;
|
||
}
|
||
if window.is_key_pressed(Key::Key0, KeyRepeat::No) {
|
||
zoom = 1.0;
|
||
needs_render = true;
|
||
}
|
||
if window.is_key_pressed(Key::R, KeyRepeat::No) {
|
||
if let Ok(p) = load(
|
||
&html_path,
|
||
css_path.as_deref(),
|
||
&base_dir,
|
||
url.as_deref(),
|
||
&client,
|
||
) {
|
||
page = p;
|
||
contenuto = engine::ContenutoPagina::da_html(&page.html);
|
||
if let Ok(m) = engine::script::Macchina::nuova() {
|
||
macchina = m;
|
||
avvia_script(
|
||
&mut contenuto,
|
||
&mut macchina,
|
||
&page.base_dir,
|
||
page.base_url.as_deref(),
|
||
);
|
||
}
|
||
needs_render = true;
|
||
}
|
||
}
|
||
|
||
// --- clic su un controllo: fuoco e cursore in fondo al testo ---
|
||
let premuto = window.get_mouse_down(MouseButton::Left);
|
||
let clic = premuto && !mouse_giu;
|
||
mouse_giu = premuto;
|
||
if clic {
|
||
if let Some((mx, my)) = window.get_mouse_pos(MouseMode::Clamp) {
|
||
let cx = mx / zoom;
|
||
let cy = (my + scroll) / zoom;
|
||
|
||
// M2.5b/d: eventi al nodo sotto il puntatore, con propagazione;
|
||
// se un gestore ha modificato il DOM la pagina si ridisegna
|
||
if let Some(r) = rendered.as_ref() {
|
||
let azione = consegna_eventi_clic(
|
||
&mut macchina,
|
||
&mut contenuto,
|
||
&form,
|
||
r,
|
||
cx,
|
||
cy,
|
||
page.base_url.as_deref(),
|
||
);
|
||
match azione {
|
||
AzioneClic::Nessuna(n) => {
|
||
if applica_valori_scritti(&mut macchina, r, &mut form) {
|
||
needs_render = true;
|
||
}
|
||
if n > 0 {
|
||
needs_render = true;
|
||
}
|
||
}
|
||
AzioneClic::Invia(richiesta) => {
|
||
eprintln!(
|
||
"invio del formulario: {} {}",
|
||
richiesta.metodo, richiesta.url
|
||
);
|
||
match esegui_invio(
|
||
&mut page,
|
||
&mut contenuto,
|
||
&mut macchina,
|
||
&richiesta,
|
||
&client,
|
||
) {
|
||
Ok(()) => needs_render = true,
|
||
Err(e) => eprintln!("mosaic: invio fallito: {}", e),
|
||
}
|
||
}
|
||
}
|
||
}
|
||
let trovato = rendered.as_ref().and_then(|r| {
|
||
r.focusables.iter().find(|f| {
|
||
cx >= f.rect.x
|
||
&& cx <= f.rect.x + f.rect.w
|
||
&& cy >= f.rect.y
|
||
&& cy <= f.rect.y + f.rect.h
|
||
})
|
||
});
|
||
// 1) una voce dell'elenco aperto ha la precedenza
|
||
let mut scelto = false;
|
||
if let Some(ap) = form.open_select.clone() {
|
||
if let Some(f) = rendered
|
||
.as_ref()
|
||
.and_then(|r| r.focusables.iter().find(|f| f.key == ap))
|
||
.cloned()
|
||
{
|
||
if let Some(pp) = f.popup {
|
||
if cx >= pp.x && cx <= pp.x + pp.w && cy >= pp.y && cy <= pp.y + pp.h {
|
||
let riga = ((cy - pp.y) / f.row_height.max(1.0)).floor() as usize;
|
||
if let Some((_, valore)) = f.options.get(riga) {
|
||
let valore = valore.clone();
|
||
form.values.insert(f.key.clone(), valore);
|
||
form.open_select = None;
|
||
form.select_highlight = None;
|
||
needs_render = true;
|
||
scelto = true;
|
||
}
|
||
} else {
|
||
// clic fuori: si chiude senza scegliere
|
||
form.open_select = None;
|
||
form.select_highlight = None;
|
||
needs_render = true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if !scelto {
|
||
if let Some(f) = trovato.cloned() {
|
||
let ora = std::time::Instant::now();
|
||
let doppio = ultimo_clic
|
||
.map(|(t, px, py)| {
|
||
ora.duration_since(t).as_millis() < 350
|
||
&& (px - cx).abs() < 3.0
|
||
&& (py - cy).abs() < 3.0
|
||
})
|
||
.unwrap_or(false);
|
||
ultimo_clic = Some((ora, cx, cy));
|
||
|
||
// il testo su cui si clicca è quello che il motore ha disegnato
|
||
let testo_corrente = form
|
||
.values
|
||
.get(&f.key)
|
||
.cloned()
|
||
.unwrap_or_else(|| f.text.clone());
|
||
let modificabile = matches!(
|
||
f.kind,
|
||
ControlKind::Text | ControlKind::Password | ControlKind::Textarea
|
||
);
|
||
if modificabile {
|
||
if let Some(m) = &metri {
|
||
let rel_x = cx - (f.rect.x + 4.0);
|
||
let indice = if f.kind == ControlKind::Textarea {
|
||
let top = f.rect.y + f.font_size * 0.37;
|
||
engine::layout::caret_index_in_lines(
|
||
m,
|
||
&testo_corrente,
|
||
f.font_size,
|
||
rel_x,
|
||
cy - top,
|
||
)
|
||
} else {
|
||
engine::layout::caret_index_at(
|
||
m,
|
||
&testo_corrente,
|
||
f.font_size,
|
||
rel_x,
|
||
)
|
||
};
|
||
form.caret = Some(indice);
|
||
if doppio {
|
||
form.selection =
|
||
Some(engine::layout::word_range(&testo_corrente, indice));
|
||
} else {
|
||
form.selection = None;
|
||
}
|
||
}
|
||
}
|
||
|
||
if f.kind == ControlKind::Select {
|
||
let aperto = form.open_select.as_deref() == Some(f.key.as_str());
|
||
form.open_select = if aperto { None } else { Some(f.key.clone()) };
|
||
form.select_highlight = if aperto { None } else { Some(f.selected) };
|
||
form.focus = Some(f.key.clone());
|
||
needs_render = true;
|
||
} else if f.kind == ControlKind::Button {
|
||
// invio del form: l'evento va al <form>, che è il
|
||
// bersaglio naturale; senza gestori non si invia
|
||
// nulla e lo si dice, invece di far finta
|
||
let bersaglio =
|
||
antenato_con_tag(&contenuto.doc, f.node, "form").unwrap_or(f.node);
|
||
let rami = catena_antenati(&contenuto.doc, bersaglio);
|
||
let gestori =
|
||
macchina.evento(&mut contenuto.doc, "submit", &rami, 0.0, 0.0);
|
||
if gestori == 0 {
|
||
eprintln!(
|
||
"mosaic: nessun gestore di submit (invio non implementato)"
|
||
);
|
||
}
|
||
needs_render = true;
|
||
} else if matches!(f.kind, ControlKind::Checkbox | ControlKind::Radio) {
|
||
// il clic sulla casella la spunta: prima serviva la
|
||
// barra spaziatrice, che nessuno indovina
|
||
let valore = form.values.get(&f.key).cloned().unwrap_or_default();
|
||
let nuovo = if valore == "on" || valore == "true" {
|
||
String::new()
|
||
} else {
|
||
"on".to_string()
|
||
};
|
||
form.values.insert(f.key.clone(), nuovo);
|
||
form.focus = Some(f.key.clone());
|
||
form.open_select = None;
|
||
needs_render = true;
|
||
} else {
|
||
form.open_select = None;
|
||
if form.focus.as_deref() != Some(f.key.as_str()) {
|
||
// il fuoco si sposta: blur sul vecchio, focus sul nuovo
|
||
let vecchio = rendered.as_ref().and_then(|r| {
|
||
form.focus
|
||
.as_ref()
|
||
.and_then(|k| r.focusables.iter().find(|x| &x.key == k))
|
||
.map(|x| x.node)
|
||
});
|
||
if let Some(v) = vecchio {
|
||
// uscendo dal campo si segnalano blur e change
|
||
eventi_su(&mut macchina, &mut contenuto, v, "blur");
|
||
eventi_su(&mut macchina, &mut contenuto, v, "change");
|
||
}
|
||
eventi_su(&mut macchina, &mut contenuto, f.node, "focus");
|
||
form.focus = Some(f.key.clone());
|
||
if modificabile {
|
||
// il cursore è già stato calcolato dal punto del clic
|
||
} else {
|
||
form.selection = None;
|
||
let valore =
|
||
form.values.get(&f.key).cloned().unwrap_or_default();
|
||
form.caret = Some(valore.chars().count());
|
||
}
|
||
}
|
||
needs_render = true;
|
||
}
|
||
} else if form.open_select.is_some() {
|
||
form.open_select = None;
|
||
form.select_highlight = None;
|
||
needs_render = true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- elenco aperto: frecce spostano l'evidenza, Invio conferma, Esc chiude ---
|
||
if let Some(ap) = form.open_select.clone() {
|
||
let voci = rendered
|
||
.as_ref()
|
||
.and_then(|r| r.focusables.iter().find(|f| f.key == ap))
|
||
.map(|f| f.options.len())
|
||
.unwrap_or(0);
|
||
if voci > 0 {
|
||
let mut hi = form.select_highlight.unwrap_or(0).min(voci - 1);
|
||
if window.is_key_pressed(Key::Down, KeyRepeat::Yes) {
|
||
hi = (hi + 1).min(voci - 1);
|
||
form.select_highlight = Some(hi);
|
||
needs_render = true;
|
||
}
|
||
if window.is_key_pressed(Key::Up, KeyRepeat::Yes) {
|
||
hi = hi.saturating_sub(1);
|
||
form.select_highlight = Some(hi);
|
||
needs_render = true;
|
||
}
|
||
if window.is_key_pressed(Key::Enter, KeyRepeat::No) {
|
||
if let Some(f) = rendered
|
||
.as_ref()
|
||
.and_then(|r| r.focusables.iter().find(|f| f.key == ap))
|
||
.cloned()
|
||
{
|
||
if let Some((_, valore)) = f.options.get(hi) {
|
||
let valore = valore.clone();
|
||
form.values.insert(ap.clone(), valore);
|
||
}
|
||
}
|
||
form.open_select = None;
|
||
form.select_highlight = None;
|
||
needs_render = true;
|
||
}
|
||
if window.is_key_pressed(Key::Escape, KeyRepeat::No) {
|
||
form.open_select = None;
|
||
form.select_highlight = None;
|
||
needs_render = true;
|
||
}
|
||
}
|
||
}
|
||
|
||
// --- moduli: Tab sposta il fuoco, i tasti scrivono nel campo attivo ---
|
||
let focusables = rendered
|
||
.as_ref()
|
||
.map(|r| r.focusables.clone())
|
||
.unwrap_or_default();
|
||
if window.is_key_pressed(Key::Tab, KeyRepeat::No) && !focusables.is_empty() {
|
||
let indice = form
|
||
.focus
|
||
.as_ref()
|
||
.and_then(|k| focusables.iter().position(|f| &f.key == k))
|
||
.map(|i| (i + 1) % focusables.len())
|
||
.unwrap_or(0);
|
||
form.focus = Some(focusables[indice].key.clone());
|
||
needs_render = true;
|
||
}
|
||
if let Some(attivo) = form
|
||
.focus
|
||
.as_ref()
|
||
.and_then(|k| focusables.iter().find(|f| &f.key == k))
|
||
.cloned()
|
||
{
|
||
let tipo = attivo.kind;
|
||
let modificabile = matches!(
|
||
tipo,
|
||
ControlKind::Text | ControlKind::Password | ControlKind::Textarea
|
||
);
|
||
let mut testo = form.values.get(&attivo.key).cloned().unwrap_or_default();
|
||
let mut cambiato = false;
|
||
|
||
if modificabile {
|
||
// posizione del cursore in caratteri; selezione come intervallo
|
||
let len = testo.chars().count();
|
||
let mut caret = form.caret.unwrap_or(len).min(len);
|
||
let mut ancora = form.selection.map(|(a, _)| a.min(len));
|
||
let shift = window.is_key_down(Key::LeftShift);
|
||
|
||
let muovi = |nuovo: usize, caret: &mut usize, ancora: &mut Option<usize>| {
|
||
if shift {
|
||
// shift estende la selezione dall'ancora
|
||
if ancora.is_none() {
|
||
*ancora = Some(*caret);
|
||
}
|
||
} else {
|
||
*ancora = None;
|
||
}
|
||
*caret = nuovo;
|
||
};
|
||
if window.is_key_pressed(Key::Left, KeyRepeat::Yes) {
|
||
muovi(caret.saturating_sub(1), &mut caret, &mut ancora);
|
||
}
|
||
if window.is_key_pressed(Key::Right, KeyRepeat::Yes) {
|
||
muovi((caret + 1).min(len), &mut caret, &mut ancora);
|
||
}
|
||
if window.is_key_pressed(Key::Home, KeyRepeat::Yes) {
|
||
muovi(0, &mut caret, &mut ancora);
|
||
}
|
||
if window.is_key_pressed(Key::End, KeyRepeat::Yes) {
|
||
muovi(len, &mut caret, &mut ancora);
|
||
}
|
||
form.selection = ancora.map(|a| (a, caret));
|
||
|
||
// cancellazione: prima la selezione, poi il carattere vicino
|
||
let mut cancella = |testo: &mut String, caret: &mut usize, avanti: bool| {
|
||
let len = testo.chars().count();
|
||
match form.selection {
|
||
Some((a, b)) if a != b => {
|
||
let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
|
||
let inizio = char_to_byte(testo, lo);
|
||
let fine = char_to_byte(testo, hi);
|
||
testo.replace_range(inizio..fine, "");
|
||
*caret = lo.min(len);
|
||
form.selection = None;
|
||
}
|
||
_ => {
|
||
let bersaglio = if avanti {
|
||
*caret
|
||
} else {
|
||
caret.saturating_sub(1)
|
||
};
|
||
if bersaglio < len {
|
||
let inizio = char_to_byte(testo, bersaglio);
|
||
let fine = char_to_byte(testo, bersaglio + 1);
|
||
testo.replace_range(inizio..fine, "");
|
||
*caret = bersaglio;
|
||
}
|
||
}
|
||
}
|
||
};
|
||
if window.is_key_pressed(Key::Backspace, KeyRepeat::Yes) {
|
||
cancella(&mut testo, &mut caret, false);
|
||
cambiato = true;
|
||
}
|
||
if window.is_key_pressed(Key::Delete, KeyRepeat::Yes) {
|
||
cancella(&mut testo, &mut caret, true);
|
||
cambiato = true;
|
||
}
|
||
form.caret = Some(caret);
|
||
|
||
// inserimento: se c'è una selezione la si sostituisce
|
||
let mut inserisci = |testo: &mut String, c: char, caret: &mut usize| {
|
||
if let Some((a, b)) = form.selection.take() {
|
||
let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
|
||
let inizio = char_to_byte(testo, lo);
|
||
let fine = char_to_byte(testo, hi);
|
||
testo.replace_range(inizio..fine, "");
|
||
*caret = lo;
|
||
}
|
||
let at = char_to_byte(testo, *caret);
|
||
testo.insert(at, c);
|
||
*caret += 1;
|
||
};
|
||
if window.is_key_pressed(Key::Space, KeyRepeat::Yes) {
|
||
inserisci(&mut testo, ' ', &mut caret);
|
||
cambiato = true;
|
||
}
|
||
if tipo == ControlKind::Textarea && window.is_key_pressed(Key::Enter, KeyRepeat::No)
|
||
{
|
||
inserisci(&mut testo, '\n', &mut caret);
|
||
cambiato = true;
|
||
}
|
||
for k in window.get_keys_pressed(KeyRepeat::No) {
|
||
if let Some(c) = key_char(k, shift) {
|
||
// M2.5: keydown vede il tasto prima che finisca nel campo
|
||
let rami = catena_antenati(&contenuto.doc, attivo.node);
|
||
if macchina.evento_tasto(&mut contenuto.doc, &rami, &c.to_string()) > 0 {
|
||
needs_render = true;
|
||
}
|
||
inserisci(&mut testo, c, &mut caret);
|
||
cambiato = true;
|
||
}
|
||
}
|
||
form.caret = Some(caret);
|
||
} else if window.is_key_pressed(Key::Space, KeyRepeat::Yes)
|
||
&& matches!(tipo, ControlKind::Checkbox | ControlKind::Radio)
|
||
{
|
||
let nuovo = if testo == "on" || testo == "true" {
|
||
String::new()
|
||
} else {
|
||
"on".to_string()
|
||
};
|
||
form.values.insert(attivo.key.clone(), nuovo);
|
||
needs_render = true;
|
||
}
|
||
|
||
if cambiato {
|
||
form.values.insert(attivo.key.clone(), testo);
|
||
// M2.5d: chi ascolta `input` deve sapere che il campo è cambiato
|
||
let rami = catena_antenati(&contenuto.doc, attivo.node);
|
||
macchina.evento(&mut contenuto.doc, "input", &rami, 0.0, 0.0);
|
||
needs_render = true;
|
||
}
|
||
}
|
||
|
||
let passo = (if window.is_key_down(Key::LeftShift) {
|
||
400.0
|
||
} else {
|
||
80.0
|
||
}) * zoom;
|
||
if window.is_key_down(Key::Down) {
|
||
scroll += passo * 0.25;
|
||
}
|
||
if window.is_key_down(Key::Up) {
|
||
scroll -= passo * 0.25;
|
||
}
|
||
if window.is_key_pressed(Key::PageDown, KeyRepeat::Yes) {
|
||
scroll += h as f32 * 0.9;
|
||
}
|
||
if window.is_key_pressed(Key::PageUp, KeyRepeat::Yes) {
|
||
scroll -= h as f32 * 0.9;
|
||
}
|
||
if window.is_key_pressed(Key::Home, KeyRepeat::No) {
|
||
scroll = 0.0;
|
||
}
|
||
if window.is_key_pressed(Key::End, KeyRepeat::No) {
|
||
scroll = f32::MAX;
|
||
}
|
||
|
||
if needs_render || rendered.as_ref().map(|r| r.width != w).unwrap_or(true) {
|
||
// si azzera **prima** di ridisegnare: quello che il rendering scopre
|
||
// (valori scritti dagli script) deve poter chiedere un altro giro
|
||
needs_render = false;
|
||
match render_finestra(&page, &contenuto, w, h, zoom, &font, &form) {
|
||
Ok(r) => {
|
||
window.set_title(&format!(
|
||
"Mosaic — {}% · {:.*} ms · {}×{} · Esc/Q per chiudere",
|
||
(zoom * 100.0).round(),
|
||
1,
|
||
r.ms,
|
||
r.width,
|
||
r.height
|
||
));
|
||
rendered = Some(r);
|
||
// valori impostati dagli script al caricamento
|
||
if applica_valori_scritti(&mut macchina, rendered.as_ref().unwrap(), &mut form)
|
||
{
|
||
needs_render = true;
|
||
}
|
||
}
|
||
Err(e) => {
|
||
eprintln!("errore di rendering: {}", e);
|
||
rendered = None;
|
||
}
|
||
}
|
||
}
|
||
|
||
// timer e fetch: la pagina può cambiare senza che l'utente faccia nulla
|
||
if pompa_timer(&mut macchina, &mut contenuto, rendered.as_ref(), &mut form) {
|
||
needs_render = true;
|
||
}
|
||
if servi_fetch(
|
||
&mut macchina,
|
||
&mut contenuto,
|
||
&client,
|
||
page.base_url.as_deref(),
|
||
) {
|
||
needs_render = true;
|
||
}
|
||
if let Some(scadenza) = macchina.prossima_scadenza() {
|
||
let attesa = scadenza.saturating_sub(adesso_ms()).min(16);
|
||
std::thread::sleep(std::time::Duration::from_millis(attesa.max(1)));
|
||
}
|
||
|
||
let buf = match &mut rendered {
|
||
Some(r) => blit(r, w, h, &mut scroll),
|
||
None => vec![0x00ff_ffff; (w * h) as usize],
|
||
};
|
||
if let Err(e) = window.update_with_buffer(&buf, w as usize, h as usize) {
|
||
eprintln!("errore di presentazione: {}", e);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Copia la parte visibile dell'immagine nel buffer della finestra (0RGB).
|
||
/// Lo scroll qui non costa nulla: l'immagine è già tutta rasterizzata.
|
||
/// Carica un indirizzo scritto a mano. Senza schema si prova https, che è la
|
||
/// norma; un indirizzo senza percorso riceve `/`, altrimenti il server riceve
|
||
/// una richiesta vuota.
|
||
fn apri_indirizzo(testo: &str, client: &engine::net::Client) -> Result<Page, String> {
|
||
let scritto = testo.trim();
|
||
if scritto.is_empty() {
|
||
return Err("indirizzo vuoto".to_string());
|
||
}
|
||
let mut indirizzo = if scritto.starts_with("http://") || scritto.starts_with("https://") {
|
||
scritto.to_string()
|
||
} else if scritto.starts_with("file://") {
|
||
let percorso = scritto.trim_start_matches("file://");
|
||
return load(
|
||
&PathBuf::from(percorso),
|
||
None,
|
||
&PathBuf::from("."),
|
||
None,
|
||
client,
|
||
);
|
||
} else {
|
||
format!("https://{}", scritto)
|
||
};
|
||
// "https://esempio.it" senza percorso: la barra finale non è un dettaglio,
|
||
// perché alcuni server rispondono 400 a un percorso vuoto
|
||
let dopo_schema = indirizzo.find("://").map(|i| i + 3).unwrap_or(0);
|
||
if !indirizzo[dopo_schema..].contains('/') {
|
||
indirizzo.push('/');
|
||
}
|
||
load(
|
||
&PathBuf::new(),
|
||
None,
|
||
&PathBuf::from("."),
|
||
Some(&indirizzo),
|
||
client,
|
||
)
|
||
}
|
||
|
||
/// Disegna la barra degli indirizzi sopra la pagina: una banda scura e il testo.
|
||
/// Il testo si disegna su una tela RGBA perché il raster del motore lavora in
|
||
/// RGBA, mentre la finestra vuole 0x00RRGGBB.
|
||
fn disegna_barra(buf: &mut [u32], w: u32, h: u32, testo: &str, font: &Option<engine::FontHolder>) {
|
||
const ALTEZZA: u32 = 38;
|
||
const MARGINE: f32 = 12.0;
|
||
const CORPO: f32 = 16.0;
|
||
let banda = 0x001b_2b_3a; // blu notte
|
||
let altezza = ALTEZZA.min(h);
|
||
for y in 0..altezza {
|
||
for x in 0..w {
|
||
buf[(y * w + x) as usize] = banda;
|
||
}
|
||
}
|
||
// filo chiaro in fondo alla banda, per staccarla dalla pagina
|
||
if altezza < h {
|
||
for x in 0..w {
|
||
buf[((altezza) * w + x) as usize] = 0x0055_6b_7f;
|
||
}
|
||
}
|
||
|
||
let Some(font) = font.as_ref() else {
|
||
return;
|
||
};
|
||
let mut tela = vec![0u8; (w as usize) * (altezza as usize) * 4];
|
||
// la tela parte dal colore della banda: il testo ci si sovrappone
|
||
for pixel in tela.chunks_exact_mut(4) {
|
||
pixel[0] = ((banda >> 16) & 0xff) as u8;
|
||
pixel[1] = ((banda >> 8) & 0xff) as u8;
|
||
pixel[2] = (banda & 0xff) as u8;
|
||
pixel[3] = 255;
|
||
}
|
||
let sagoma = font.shape(testo, CORPO);
|
||
let bianco = engine::Color {
|
||
r: 240,
|
||
g: 244,
|
||
b: 248,
|
||
a: 255,
|
||
};
|
||
font.draw_shaped(
|
||
&mut tela,
|
||
w,
|
||
altezza,
|
||
MARGINE,
|
||
altezza as f32 * 0.68,
|
||
&sagoma,
|
||
CORPO,
|
||
CORPO,
|
||
bianco,
|
||
400,
|
||
false,
|
||
);
|
||
for y in 0..altezza {
|
||
for x in 0..w {
|
||
let i = ((y * w + x) * 4) as usize;
|
||
buf[(y * w + x) as usize] =
|
||
((tela[i] as u32) << 16) | ((tela[i + 1] as u32) << 8) | tela[i + 2] as u32;
|
||
}
|
||
}
|
||
|
||
// il cursore va disegnato DOPO aver riportato la tela, altrimenti la copia
|
||
// lo cancella: è quello che era successo alla prima stesura
|
||
let fine = MARGINE + font.advance(testo, CORPO);
|
||
let x_cursore = (fine as u32).min(w.saturating_sub(1));
|
||
for y in (altezza as f32 * 0.25) as u32..(altezza as f32 * 0.78) as u32 {
|
||
let indice = (y * w + x_cursore) as usize;
|
||
if indice < buf.len() {
|
||
buf[indice] = 0x00f0_f4_f8;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Confronto fra le due vie, con i numeri veri: la pagina intera come un'unica
|
||
/// immagine (quello che facevano i gusci) contro la composizione a tessere.
|
||
fn misura_finestra_e_pagina(
|
||
page: &Page,
|
||
contenuto: &engine::ContenutoPagina,
|
||
w: u32,
|
||
h: u32,
|
||
zoom: f32,
|
||
font: &Path,
|
||
form: &FormState,
|
||
) {
|
||
let t = Instant::now();
|
||
let piena = render_page(page, contenuto, w, h, zoom, font, form);
|
||
let ms_piena = t.elapsed().as_secs_f64() * 1000.0;
|
||
let t = Instant::now();
|
||
let mut finestra = render_finestra(page, contenuto, w, h, zoom, font, form);
|
||
let ms_finestra = t.elapsed().as_secs_f64() * 1000.0;
|
||
match (piena, finestra) {
|
||
(Ok(p), Ok(mut f)) => {
|
||
let mb_piena = (p.rgba.len() as f64) / (1024.0 * 1024.0);
|
||
println!(
|
||
"pagina {}x{}: immagine piena {:.1} MB in {:.0} ms",
|
||
f.width, f.height, mb_piena, ms_piena
|
||
);
|
||
println!(
|
||
"finestra {}x{}: impaginato + tessere in {:.0} ms",
|
||
w, h, ms_finestra
|
||
);
|
||
// scorrere: quanto costa comporre una finestra nuova
|
||
let mut scroll = 0.0f32;
|
||
for passo in 1..=5 {
|
||
let t = Instant::now();
|
||
let _ = blit(&mut f, w, h, &mut scroll);
|
||
println!(
|
||
" finestra {passo}: composta in {:.2} ms",
|
||
t.elapsed().as_secs_f64() * 1000.0
|
||
);
|
||
scroll += h as f32;
|
||
}
|
||
// la memoria si dichiara **dopo** aver composto: prima del primo
|
||
// disegno nessuna tessera è ancora stata rasterizzata
|
||
let tessere = f.compositor.as_ref().map(|c| c.rasterizzate()).unwrap_or(0);
|
||
let mb_tessere = (tessere
|
||
* (engine::compositor::LATO as usize)
|
||
* (engine::compositor::LATO as usize)
|
||
* 4) as f64
|
||
/ (1024.0 * 1024.0);
|
||
println!(
|
||
" in tutto: {tessere} tessere rasterizzate, {mb_tessere:.1} MB contro {:.1} MB dell'immagine piena",
|
||
(p.rgba.len() as f64) / (1024.0 * 1024.0)
|
||
);
|
||
}
|
||
(Err(e), _) => println!("misura: errore impaginando la pagina intera: {e}"),
|
||
(_, Err(e)) => println!("misura: errore preparando la finestra: {e}"),
|
||
}
|
||
}
|
||
|
||
fn blit(img: &mut Rendered, w: u32, h: u32, scroll: &mut f32) -> Vec<u32> {
|
||
let max_scroll = (img.height as f32 - h as f32).max(0.0);
|
||
if *scroll < 0.0 {
|
||
*scroll = 0.0;
|
||
}
|
||
if *scroll > max_scroll {
|
||
*scroll = max_scroll;
|
||
}
|
||
// con il compositor si chiede solo la finestra: le tessere già pronte non si
|
||
// rifanno, e la pagina intera non è mai un'unica texture
|
||
if let Some(c) = img.compositor.as_mut() {
|
||
let finestra = c.componi(*scroll, w, h);
|
||
let mut out = vec![0x00ff_ffffu32; (w * h) as usize];
|
||
for i in 0..(w * h) as usize {
|
||
let k = i * 4;
|
||
out[i] = ((finestra[k] as u32) << 16)
|
||
| ((finestra[k + 1] as u32) << 8)
|
||
| finestra[k + 2] as u32;
|
||
}
|
||
return out;
|
||
}
|
||
let y0 = *scroll as u32;
|
||
let mut out = vec![0x00ff_ffffu32; (w * h) as usize];
|
||
for y in 0..h {
|
||
let sy = y0 + y;
|
||
if sy >= img.height || y >= img.height {
|
||
break;
|
||
}
|
||
let src_start = ((sy * img.width) * 4) as usize;
|
||
let dst_start = (y * w) as usize;
|
||
for x in 0..w.min(img.width) {
|
||
let i = src_start + (x * 4) as usize;
|
||
let r = img.rgba[i] as u32;
|
||
let g = img.rgba[i + 1] as u32;
|
||
let b = img.rgba[i + 2] as u32;
|
||
out[dst_start + x as usize] = (r << 16) | (g << 8) | b;
|
||
}
|
||
}
|
||
out
|
||
}
|
||
|
||
fn render_page(
|
||
page: &Page,
|
||
contenuto: &engine::ContenutoPagina,
|
||
w: u32,
|
||
h: u32,
|
||
zoom: f32,
|
||
font: &Path,
|
||
form: &FormState,
|
||
) -> Result<Rendered, String> {
|
||
let opts = RenderOptions {
|
||
viewport: (w, h),
|
||
dpi_scale: zoom,
|
||
font_path: font.to_path_buf(),
|
||
auto_height: true,
|
||
base_dir: page.base_dir.clone(),
|
||
base_url: page.base_url.clone(),
|
||
};
|
||
let t = Instant::now();
|
||
let res = engine::render_contenuto(contenuto, &page.css, &opts, form)?;
|
||
let ms = t.elapsed().as_secs_f64() * 1000.0;
|
||
Ok(Rendered {
|
||
layout: res.layout.clone(),
|
||
width: res.width,
|
||
height: res.height,
|
||
rgba: res.rgba,
|
||
compositor: None,
|
||
ms,
|
||
focusables: res.focusables,
|
||
})
|
||
}
|
||
|
||
/// Impagina **senza** rasterizzare la pagina intera e prepara la composizione a
|
||
/// tessere: è la via della finestra interattiva, dove tenere in memoria l'intero
|
||
/// documento come un'unica immagine costa decine di MB.
|
||
fn render_finestra(
|
||
page: &Page,
|
||
contenuto: &engine::ContenutoPagina,
|
||
w: u32,
|
||
h: u32,
|
||
zoom: f32,
|
||
font: &Path,
|
||
form: &FormState,
|
||
) -> Result<Rendered, String> {
|
||
let opts = RenderOptions {
|
||
viewport: (w, h),
|
||
dpi_scale: zoom,
|
||
font_path: font.to_path_buf(),
|
||
auto_height: true,
|
||
base_dir: page.base_dir.clone(),
|
||
base_url: page.base_url.clone(),
|
||
};
|
||
let t = Instant::now();
|
||
let res = engine::render_contenuto_comandi(contenuto, &page.css, &opts, form)?;
|
||
let ms = t.elapsed().as_secs_f64() * 1000.0;
|
||
let mut compositor = engine::compositor::Compositor::new(res.width, res.height, zoom);
|
||
compositor.aggiorna_tutto(res.cmds);
|
||
Ok(Rendered {
|
||
layout: res.layout.clone(),
|
||
width: res.width,
|
||
height: res.height,
|
||
rgba: Vec::new(),
|
||
compositor: Some(compositor),
|
||
ms,
|
||
focusables: res.focusables,
|
||
})
|
||
}
|
||
|
||
fn load(
|
||
html: &Path,
|
||
css: Option<&Path>,
|
||
_base: &Path,
|
||
url: Option<&str>,
|
||
client: &engine::net::Client,
|
||
) -> Result<Page, String> {
|
||
// con --url il documento arriva dalla rete; senza, dal file
|
||
let html_text = match url {
|
||
Some(u) => {
|
||
let risposta = client
|
||
.get(u, &engine::net::Limiti::default())
|
||
.map_err(|e| format!("richiesta a {} fallita: {}", u, e))?;
|
||
risposta
|
||
.text()
|
||
.map_err(|e| format!("corpo di {} inutilizzabile: {}", u, e))?
|
||
}
|
||
None => std::fs::read_to_string(html).map_err(|e| format!("{}: {}", html.display(), e))?,
|
||
};
|
||
let css_text = match css {
|
||
Some(p) => std::fs::read_to_string(p).map_err(|e| format!("{}: {}", p.display(), e))?,
|
||
None => String::new(),
|
||
};
|
||
let base_dir = html
|
||
.parent()
|
||
.map(|p| p.to_path_buf())
|
||
.unwrap_or_else(|| PathBuf::from("."));
|
||
Ok(Page {
|
||
html: html_text,
|
||
css: css_text,
|
||
base_dir,
|
||
base_url: url.map(|u| u.to_string()),
|
||
})
|
||
}
|
||
|
||
/// Offset in byte della posizione di carattere `idx` (il cursore si conta in caratteri).
|
||
fn char_to_byte(s: &str, idx: usize) -> usize {
|
||
s.char_indices().nth(idx).map(|(b, _)| b).unwrap_or(s.len())
|
||
}
|
||
|
||
/// Carattere prodotto da un tasto, con il maiuscolo gestito dallo shift.
|
||
fn key_char(k: Key, shift: bool) -> Option<char> {
|
||
let c = match k {
|
||
Key::A => 'a',
|
||
Key::B => 'b',
|
||
Key::C => 'c',
|
||
Key::D => 'd',
|
||
Key::E => 'e',
|
||
Key::F => 'f',
|
||
Key::G => 'g',
|
||
Key::H => 'h',
|
||
Key::I => 'i',
|
||
Key::J => 'j',
|
||
Key::K => 'k',
|
||
Key::L => 'l',
|
||
Key::M => 'm',
|
||
Key::N => 'n',
|
||
Key::O => 'o',
|
||
Key::P => 'p',
|
||
Key::Q => 'q',
|
||
Key::R => 'r',
|
||
Key::S => 's',
|
||
Key::T => 't',
|
||
Key::U => 'u',
|
||
Key::V => 'v',
|
||
Key::W => 'w',
|
||
Key::X => 'x',
|
||
Key::Y => 'y',
|
||
Key::Z => 'z',
|
||
Key::Key0 => '0',
|
||
Key::Key1 => '1',
|
||
Key::Key2 => '2',
|
||
Key::Key3 => '3',
|
||
Key::Key4 => '4',
|
||
Key::Key5 => '5',
|
||
Key::Key6 => '6',
|
||
Key::Key7 => '7',
|
||
Key::Key8 => '8',
|
||
Key::Key9 => '9',
|
||
Key::Period => '.',
|
||
Key::Comma => ',',
|
||
Key::Minus => '-',
|
||
Key::Equal => '=',
|
||
Key::Slash => '/',
|
||
Key::Semicolon => ';',
|
||
Key::Apostrophe => '\'',
|
||
Key::Backslash => '\\',
|
||
Key::LeftBracket => '[',
|
||
Key::RightBracket => ']',
|
||
_ => return None,
|
||
};
|
||
Some(if shift { c.to_ascii_uppercase() } else { c })
|
||
}
|
||
|
||
fn default_font() -> PathBuf {
|
||
if let Ok(p) = std::env::var("MOSAIC_FONT") {
|
||
return PathBuf::from(p);
|
||
}
|
||
for c in [
|
||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||
"/usr/share/fonts/dejavu/DejaVuSans.ttf",
|
||
] {
|
||
if Path::new(c).exists() {
|
||
return PathBuf::from(c);
|
||
}
|
||
}
|
||
PathBuf::from("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf")
|
||
}
|
||
|
||
// evita il warning sull'import non usato di MouseMode in alcune versioni di minifb
|
||
#[allow(dead_code)]
|
||
fn _mouse(_: MouseMode) {}
|