Timer con orologio iniettato e documento con stato nel confine C
M2.5 - timer: setTimeout/setInterval/clearTimeout con la coda in JS e il tempo fornito dall'esterno. Il motore non legge mai l'orologio: i test usano un tempo finto (pompa_timer con istanti scelti) e restano riproducibili; il desktop usa l'orologio di sistema e dorme fino alla scadenza successiva invece di girare a vuoto. M2.6 - confine C a documento: engine_doc_new/render/click/pump/next_timer/errors. Il guscio tiene DOM, macchina JavaScript e timer nel motore, come il desktop. L'indirizzo del documento arriva al motore: sotto-risorse e script esterni funzionano anche sul telefono, che ora consegna i tocchi al JavaScript. Corretto un difetto introdotto con gli script esterni: la sequenza degli script veniva letta dal DOM, dove il testo degli script inline non c'è, quindi nessuno script inline veniva più eseguito nei gusci. Ora si consuma il vettore del parser nell'ordine del documento.
This commit is contained in:
1 parent
94faf56304
commit
b40d9d8a1c
16 files changed
+839
-59
No files matched your search
+254
-43
@@ -220,52 +220,55 @@ fn render_inner(
|
||||
match result {
|
||||
Err(_) => error_image("panic nel motore".to_string()),
|
||||
Ok(Err(message)) => error_image(message),
|
||||
Ok(Ok(res)) => {
|
||||
let mut pixels = res.rgba;
|
||||
pixels.shrink_to_fit();
|
||||
let len = pixels.len();
|
||||
let ptr = pixels.as_mut_ptr();
|
||||
std::mem::forget(pixels);
|
||||
// controlli per il guscio: posizione e tipo, in pixel CSS
|
||||
let controlli: Vec<serde_json::Value> = res
|
||||
.focusables
|
||||
.iter()
|
||||
.map(|f| {
|
||||
serde_json::json!({
|
||||
"key": f.key,
|
||||
"kind": format!("{:?}", f.kind).to_lowercase(),
|
||||
"x": f.rect.x,
|
||||
"y": f.rect.y,
|
||||
"w": f.rect.w,
|
||||
"h": f.rect.h,
|
||||
"labels": f.options.iter().map(|(e, _)| e.clone()).collect::<Vec<_>>(),
|
||||
"values": f.options.iter().map(|(_, v)| v.clone()).collect::<Vec<_>>(),
|
||||
"selected": f.selected,
|
||||
"popup": f.popup.map(|r| serde_json::json!({
|
||||
"x": r.x, "y": r.y, "w": r.w, "h": r.h
|
||||
})),
|
||||
"rowHeight": f.row_height,
|
||||
"fontSize": f.font_size,
|
||||
"text": f.text,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let json = serde_json::Value::Array(controlli).to_string();
|
||||
let controls = CString::new(json)
|
||||
.map(|c| c.into_raw())
|
||||
.unwrap_or(std::ptr::null_mut());
|
||||
Box::into_raw(Box::new(EngineImage {
|
||||
controls,
|
||||
width: res.width,
|
||||
height: res.height,
|
||||
pixels: ptr,
|
||||
len,
|
||||
error: std::ptr::null_mut(),
|
||||
}))
|
||||
}
|
||||
Ok(Ok(res)) => image_from(res),
|
||||
}
|
||||
}
|
||||
|
||||
/// Costruisce l'immagine per il guscio da un risultato di rendering.
|
||||
fn image_from(res: crate::RenderResult) -> *mut EngineImage {
|
||||
let mut pixels = res.rgba;
|
||||
pixels.shrink_to_fit();
|
||||
let len = pixels.len();
|
||||
let ptr = pixels.as_mut_ptr();
|
||||
std::mem::forget(pixels);
|
||||
// controlli per il guscio: posizione e tipo, in pixel CSS
|
||||
let controlli: Vec<serde_json::Value> = res
|
||||
.focusables
|
||||
.iter()
|
||||
.map(|f| {
|
||||
serde_json::json!({
|
||||
"key": f.key,
|
||||
"kind": format!("{:?}", f.kind).to_lowercase(),
|
||||
"x": f.rect.x,
|
||||
"y": f.rect.y,
|
||||
"w": f.rect.w,
|
||||
"h": f.rect.h,
|
||||
"labels": f.options.iter().map(|(e, _)| e.clone()).collect::<Vec<_>>(),
|
||||
"values": f.options.iter().map(|(_, v)| v.clone()).collect::<Vec<_>>(),
|
||||
"selected": f.selected,
|
||||
"popup": f.popup.map(|r| serde_json::json!({
|
||||
"x": r.x, "y": r.y, "w": r.w, "h": r.h
|
||||
})),
|
||||
"rowHeight": f.row_height,
|
||||
"fontSize": f.font_size,
|
||||
"text": f.text,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let json = serde_json::Value::Array(controlli).to_string();
|
||||
let controls = CString::new(json)
|
||||
.map(|c| c.into_raw())
|
||||
.unwrap_or(std::ptr::null_mut());
|
||||
Box::into_raw(Box::new(EngineImage {
|
||||
controls,
|
||||
width: res.width,
|
||||
height: res.height,
|
||||
pixels: ptr,
|
||||
len,
|
||||
error: std::ptr::null_mut(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Libera l'immagine e i pixel. Idempotente su puntatore nullo.
|
||||
/// Scarica un documento (`http://` o `https://`) e ne restituisce il testo.
|
||||
///
|
||||
@@ -355,3 +358,211 @@ pub extern "C" fn engine_image_free(img: *mut EngineImage) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Documento con stato: DOM, macchina JavaScript, ultimo impaginato.
|
||||
///
|
||||
/// È quello che serve a un guscio grafico: si crea una volta, si rasterizza
|
||||
/// quante volte si vuole, si consegnano clic, si fanno avanzare i timer.
|
||||
pub struct EngineDoc {
|
||||
contenuto: crate::ContenutoPagina,
|
||||
macchina: crate::script::Macchina,
|
||||
css: String,
|
||||
base_dir: PathBuf,
|
||||
/// ultimo impaginato: serve a sapere che nodo sta sotto il puntatore
|
||||
layout: Option<crate::layout::LayoutBox>,
|
||||
}
|
||||
|
||||
/// Crea un documento, eseguendo subito gli script (anche esterni).
|
||||
/// `base_url` può essere NULL per i documenti locali.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn engine_doc_new(
|
||||
html: *const c_char,
|
||||
css: *const c_char,
|
||||
base_dir: *const c_char,
|
||||
base_url: *const c_char,
|
||||
) -> *mut EngineDoc {
|
||||
let html = cstr_or_empty(html);
|
||||
let css = cstr_or_empty(css);
|
||||
let cartella = {
|
||||
let b = cstr_or_empty(base_dir);
|
||||
if b.is_empty() {
|
||||
std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
|
||||
} else {
|
||||
PathBuf::from(b)
|
||||
}
|
||||
};
|
||||
let indirizzo = {
|
||||
let u = cstr_or_empty(base_url);
|
||||
if u.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(u.to_string())
|
||||
}
|
||||
};
|
||||
let esito = catch_unwind(AssertUnwindSafe(|| {
|
||||
let mut contenuto = crate::ContenutoPagina::da_html(&html);
|
||||
let mut macchina = match crate::script::Macchina::nuova() {
|
||||
Ok(m) => m,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let cartella_carica = cartella.clone();
|
||||
let indirizzo_carica = indirizzo.clone();
|
||||
contenuto.esegui_script_con(&mut macchina, &|src: &str| {
|
||||
if let Some(url) = crate::resource::risolvi_url(indirizzo_carica.as_deref(), src) {
|
||||
return crate::net::get(&url, &crate::net::Limiti::default())
|
||||
.ok()
|
||||
.and_then(|r| r.text().ok());
|
||||
}
|
||||
std::fs::read_to_string(cartella_carica.join(src)).ok()
|
||||
});
|
||||
Ok(EngineDoc {
|
||||
contenuto,
|
||||
macchina,
|
||||
css,
|
||||
base_dir: cartella,
|
||||
layout: None,
|
||||
})
|
||||
}));
|
||||
match esito {
|
||||
Ok(Ok(doc)) => Box::into_raw(Box::new(doc)),
|
||||
_ => std::ptr::null_mut(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Libera un documento.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn engine_doc_free(doc: *mut EngineDoc) {
|
||||
if !doc.is_null() {
|
||||
unsafe {
|
||||
drop(Box::from_raw(doc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rasterizza lo stato corrente del documento.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn engine_doc_render(
|
||||
doc: *mut EngineDoc,
|
||||
width: u32,
|
||||
height: u32,
|
||||
scale: f32,
|
||||
auto_height: i32,
|
||||
font_path: *const c_char,
|
||||
state_json: *const c_char,
|
||||
) -> *mut EngineImage {
|
||||
if doc.is_null() {
|
||||
return error_image("documento nullo".to_string());
|
||||
}
|
||||
let d = unsafe { &mut *doc };
|
||||
let form = parse_form_state(&cstr_or_empty(state_json));
|
||||
let font = cstr_or_empty(font_path);
|
||||
let opts = RenderOptions {
|
||||
viewport: (width, height),
|
||||
dpi_scale: if scale > 0.0 { scale } else { 1.0 },
|
||||
font_path: PathBuf::from(if font.is_empty() {
|
||||
PathBuf::from("font.ttf")
|
||||
} else {
|
||||
PathBuf::from(font)
|
||||
}),
|
||||
auto_height: auto_height != 0,
|
||||
base_dir: d.base_dir.clone(),
|
||||
base_url: None,
|
||||
};
|
||||
if width == 0 || height == 0 {
|
||||
return error_image("viewport nullo".to_string());
|
||||
}
|
||||
let esito = catch_unwind(AssertUnwindSafe(|| {
|
||||
crate::render_contenuto(&d.contenuto, &d.css, &opts, &form)
|
||||
}));
|
||||
match esito {
|
||||
Ok(Ok(res)) => {
|
||||
d.layout = Some(res.layout.clone());
|
||||
image_from(res)
|
||||
}
|
||||
Ok(Err(e)) => error_image(e),
|
||||
Err(_) => error_image("errore interno nel rendering".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Consegna un clic alle coordinate CSS: `submit` se il bersaglio è un pulsante,
|
||||
/// poi `click` con propagazione agli antenati. Restituisce quanti gestori hanno
|
||||
/// reagito (0 = nessuno, la pagina non va ridisegnata per questo motivo).
|
||||
#[no_mangle]
|
||||
pub extern "C" fn engine_doc_click(doc: *mut EngineDoc, css_x: f32, css_y: f32) -> i32 {
|
||||
if doc.is_null() {
|
||||
return 0;
|
||||
}
|
||||
let d = unsafe { &mut *doc };
|
||||
let Some(layout) = d.layout.clone() else {
|
||||
return 0;
|
||||
};
|
||||
let Some(nodo) = crate::layout::nodo_al_punto(&layout, css_x, css_y) else {
|
||||
return 0;
|
||||
};
|
||||
let mut gestori = 0usize;
|
||||
// submit, se il nodo è un pulsante dentro un form
|
||||
let pulsante = crate::layout::controllo_su_nodo(&layout, nodo)
|
||||
.map(|k| k == crate::layout::ControlKind::Button)
|
||||
.unwrap_or(false);
|
||||
if pulsante {
|
||||
if let Some(form_node) = antenato_tag(&d.contenuto.doc, nodo, "form") {
|
||||
let catena = crate::layout::catena_antenati(&d.contenuto.doc, form_node);
|
||||
gestori += d
|
||||
.macchina
|
||||
.evento(&mut d.contenuto.doc, "submit", &catena, css_x, css_y);
|
||||
}
|
||||
}
|
||||
let catena = crate::layout::catena_antenati(&d.contenuto.doc, nodo);
|
||||
gestori += d
|
||||
.macchina
|
||||
.evento(&mut d.contenuto.doc, "click", &catena, css_x, css_y);
|
||||
gestori as i32
|
||||
}
|
||||
|
||||
/// Fa avanzare i timer fino a `now_ms` (orologio del sistema). Restituisce
|
||||
/// quanti ne ha eseguiti: se è > 0 la pagina va ridisegnata.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn engine_doc_pump(doc: *mut EngineDoc, now_ms: u64) -> i32 {
|
||||
if doc.is_null() {
|
||||
return 0;
|
||||
}
|
||||
let d = unsafe { &mut *doc };
|
||||
d.macchina.pompa_timer(&mut d.contenuto.doc, now_ms, 100) as i32
|
||||
}
|
||||
|
||||
/// Prima scadenza dei timer in millisecondi, oppure -1 se non c'è nulla in coda.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn engine_doc_next_timer(doc: *mut EngineDoc) -> i64 {
|
||||
if doc.is_null() {
|
||||
return -1;
|
||||
}
|
||||
let d = unsafe { &mut *doc };
|
||||
d.macchina
|
||||
.prossima_scadenza()
|
||||
.map(|v| v as i64)
|
||||
.unwrap_or(-1)
|
||||
}
|
||||
|
||||
/// Errori degli script raccolti nel documento, una voce per riga.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn engine_doc_errors(doc: *mut EngineDoc) -> *mut c_char {
|
||||
if doc.is_null() {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let d = unsafe { &mut *doc };
|
||||
let mut voci = d.contenuto.script_errors.clone();
|
||||
voci.extend(d.macchina.messaggi_log());
|
||||
cstring_errore(voci.join("\n"))
|
||||
}
|
||||
|
||||
/// Primo antenato (o il nodo stesso) con quel nome di elemento.
|
||||
fn antenato_tag(doc: &crate::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
|
||||
}
|
||||
@@ -1761,6 +1761,65 @@ pub fn select_row_height(font_size: f32) -> f32 {
|
||||
font_size * 1.4 + 6.0
|
||||
}
|
||||
|
||||
/// Nodo più profondo sotto il punto (px CSS): l'evento JavaScript va a lui.
|
||||
/// I controlli non hanno un box proprio, vivono nelle righe di testo.
|
||||
pub fn nodo_al_punto(b: &LayoutBox, x: f32, y: f32) -> Option<crate::dom::NodeId> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
for linea in &b.lines {
|
||||
for run in &linea.runs {
|
||||
if let Some(c) = &run.control {
|
||||
let r = 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)
|
||||
}
|
||||
|
||||
/// Tipo del controllo che corrisponde a un nodo, se ce n'è uno.
|
||||
pub fn controllo_su_nodo(b: &LayoutBox, nodo: crate::dom::NodeId) -> Option<ControlKind> {
|
||||
for linea in &b.lines {
|
||||
for run in &linea.runs {
|
||||
if let Some(c) = &run.control {
|
||||
if c.node == nodo {
|
||||
return Some(c.kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for figlio in &b.children {
|
||||
if let Some(k) = controllo_su_nodo(figlio, nodo) {
|
||||
return Some(k);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Nodo e antenati, dal più profondo alla radice: è l'ordine di propagazione.
|
||||
pub fn catena_antenati(
|
||||
doc: &crate::dom::Document,
|
||||
nodo: crate::dom::NodeId,
|
||||
) -> Vec<crate::dom::NodeId> {
|
||||
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
|
||||
}
|
||||
|
||||
/// Chiave stabile del controllo corrispondente a un nodo (la stessa che il
|
||||
/// motore usa per fuoco e valori): serve all'invio dei formulari.
|
||||
pub fn chiave_del_controllo(doc: &Document, node: NodeId) -> Option<String> {
|
||||
|
||||
+10
-3
@@ -102,7 +102,7 @@ impl ContenutoPagina {
|
||||
pub fn da_html(html: &str) -> ContenutoPagina {
|
||||
let avvio = std::time::Instant::now();
|
||||
let built = treebuilder::parse(html);
|
||||
let sequenza = sequenza_script(&built.doc);
|
||||
let sequenza = sequenza_script(&built.doc, &built.scripts);
|
||||
ContenutoPagina {
|
||||
doc: built.doc,
|
||||
fogli_inline: built.style_text,
|
||||
@@ -266,7 +266,10 @@ fn render_pezzi(
|
||||
|
||||
/// Script del documento in ordine: `<script>codice</script>` e `<script src="…">`.
|
||||
/// Si legge dall'albero invece che dal parser, così vale per entrambi i casi.
|
||||
fn sequenza_script(doc: &dom::Document) -> Vec<script::Sorgente> {
|
||||
fn sequenza_script(doc: &dom::Document, inline: &[String]) -> Vec<script::Sorgente> {
|
||||
// Il testo degli script inline vive nel vettore del parser, non nei nodi del
|
||||
// DOM: si consuma in ordine, uno per ogni `<script>` senza `src`.
|
||||
let mut prossimo = 0usize;
|
||||
let mut out = Vec::new();
|
||||
let mut pila = vec![doc.root()];
|
||||
while let Some(id) = pila.pop() {
|
||||
@@ -275,7 +278,11 @@ fn sequenza_script(doc: &dom::Document) -> Vec<script::Sorgente> {
|
||||
Some(src) if !src.trim().is_empty() => {
|
||||
out.push(script::Sorgente::Esterno(src.trim().to_string()))
|
||||
}
|
||||
_ => out.push(script::Sorgente::Inline(doc.text_content(id))),
|
||||
_ => {
|
||||
let codice = inline.get(prossimo).cloned().unwrap_or_default();
|
||||
prossimo += 1;
|
||||
out.push(script::Sorgente::Inline(codice));
|
||||
}
|
||||
}
|
||||
continue; // niente da visitare dentro
|
||||
}
|
||||
|
||||
@@ -94,4 +94,12 @@ impl Macchina {
|
||||
pub fn messaggi_log(&self) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
pub fn pompa_timer(&mut self, _doc: &mut Document, _adesso_ms: u64, _limite: usize) -> usize {
|
||||
0
|
||||
}
|
||||
|
||||
pub fn prossima_scadenza(&mut self) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,8 @@ thread_local! {
|
||||
/// consegnare un evento, così lo script può leggere cosa è stato digitato
|
||||
static VALORI: RefCell<std::collections::HashMap<usize, String>> =
|
||||
RefCell::new(std::collections::HashMap::new());
|
||||
/// orologio del guscio, in millisecondi: il motore non legge mai l'ora vera
|
||||
static OROLOGIO: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// valori che gli script hanno scritto nei campi (`campo.value = ...`)
|
||||
static SCRITTI: RefCell<Vec<(usize, String)>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
@@ -99,6 +101,74 @@ var __preventuto = false;
|
||||
/* vero se un gestore ha fermato la propagazione */
|
||||
var __ferma = false;
|
||||
|
||||
/* Timer: la coda vive qui, ma il tempo lo fornisce il motore (che a sua volta lo
|
||||
riceve dal guscio). Così il motore non legge mai l'orologio e i test possono
|
||||
usare un tempo finto, restando riproducibili. */
|
||||
var __timers = [];
|
||||
var __prossimo_timer = 1;
|
||||
|
||||
function __timer_aggiungi(fn, ms, ripeti) {
|
||||
if (typeof fn !== 'function') { return 0; }
|
||||
var attesa = Number(ms);
|
||||
if (!isFinite(attesa) || attesa < 0) { attesa = 0; }
|
||||
var id = __prossimo_timer++;
|
||||
__timers.push({
|
||||
id: id,
|
||||
fn: fn,
|
||||
quando: __adesso() + attesa,
|
||||
ogni: ripeti ? Math.max(1, attesa) : 0,
|
||||
ripeti: !!ripeti
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
function __timer_togli(id) {
|
||||
for (var i = 0; i < __timers.length; i++) {
|
||||
if (__timers[i].id === Number(id)) { __timers.splice(i, 1); return; }
|
||||
}
|
||||
}
|
||||
|
||||
function setTimeout(fn, ms) { return __timer_aggiungi(fn, ms, false); }
|
||||
function setInterval(fn, ms) { return __timer_aggiungi(fn, ms, true); }
|
||||
function clearTimeout(id) { __timer_togli(id); }
|
||||
function clearInterval(id) { __timer_togli(id); }
|
||||
|
||||
/* Esegue i timer scaduti entro `adesso`, al massimo `limite` per non restare
|
||||
prigionieri di un ciclo infinito scritto male. */
|
||||
function __timer_pompa(adesso, limite) {
|
||||
var eseguiti = 0;
|
||||
for (var giro = 0; giro < limite; giro++) {
|
||||
var scelto = -1;
|
||||
var minore = null;
|
||||
for (var i = 0; i < __timers.length; i++) {
|
||||
var t = __timers[i];
|
||||
if (t.quando <= adesso && (minore === null || t.quando < minore)) {
|
||||
minore = t.quando;
|
||||
scelto = i;
|
||||
}
|
||||
}
|
||||
if (scelto < 0) { break; }
|
||||
var timer = __timers[scelto];
|
||||
if (timer.ripeti) {
|
||||
timer.quando = Math.max(timer.quando + timer.ogni, adesso + 1);
|
||||
} else {
|
||||
__timers.splice(scelto, 1);
|
||||
}
|
||||
try { timer.fn(); } catch (e) { __log('errore in un timer: ' + e); }
|
||||
eseguiti++;
|
||||
}
|
||||
return eseguiti;
|
||||
}
|
||||
|
||||
/* Prima scadenza futura, in millisecondi; -1 se non c'è nulla in coda. */
|
||||
function __timer_prossimo() {
|
||||
var minimo = -1;
|
||||
for (var i = 0; i < __timers.length; i++) {
|
||||
if (minimo < 0 || __timers[i].quando < minimo) { minimo = __timers[i].quando; }
|
||||
}
|
||||
return minimo;
|
||||
}
|
||||
|
||||
var console = {
|
||||
log: function () {
|
||||
var pezzi = [];
|
||||
@@ -556,6 +626,12 @@ fn inline(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsVa
|
||||
})
|
||||
}
|
||||
|
||||
/// `__adesso()`: tempo corrente in millisecondi, fornito dal guscio.
|
||||
fn adesso(_this: &JsValue, _args: &[JsValue], _ctx: &mut Context) -> JsResult<JsValue> {
|
||||
let ora = OROLOGIO.with(|o| o.get());
|
||||
Ok(JsValue::from(ora as f64))
|
||||
}
|
||||
|
||||
/// `__log(testo)`: `console.log`. I messaggi finiscono in `MOSAIC_JS_LOG`
|
||||
/// (stderr) e nella lista degli errori, così non si perdono.
|
||||
fn log(_this: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {
|
||||
@@ -1086,6 +1162,7 @@ impl Macchina {
|
||||
("__log", 1, log),
|
||||
("__selettore_uno", 2, selettore_uno),
|
||||
("__selettori", 2, selettori),
|
||||
("__adesso", 0, adesso),
|
||||
];
|
||||
for (nome, arita, f) in registrazioni {
|
||||
ctx.register_global_builtin_callable(
|
||||
@@ -1119,6 +1196,7 @@ impl Macchina {
|
||||
return Vec::new();
|
||||
}
|
||||
prepara(doc);
|
||||
OROLOGIO.with(|o| o.set(OROLOGIO.with(|x| x.get())));
|
||||
let mut errori = Vec::new();
|
||||
for (i, voce) in sequenza.iter().enumerate() {
|
||||
let codice = match voce {
|
||||
@@ -1212,6 +1290,37 @@ impl Macchina {
|
||||
STATO.with(|s| s.borrow().log.clone())
|
||||
}
|
||||
|
||||
/// Esegue i timer scaduti entro `adesso_ms` (orologio del guscio) e applica
|
||||
/// le modifiche al DOM. Restituisce quanti timer sono stati eseguiti.
|
||||
pub fn pompa_timer(&mut self, doc: &mut Document, adesso_ms: u64, limite: usize) -> usize {
|
||||
OROLOGIO.with(|o| o.set(adesso_ms));
|
||||
let codice = format!("__timer_pompa({}, {})", adesso_ms, limite);
|
||||
let eseguiti = match self.ctx.eval(Source::from_bytes(codice.as_str())) {
|
||||
Ok(v) => v.to_number(&mut self.ctx).unwrap_or(0.0) as usize,
|
||||
Err(e) => {
|
||||
eprintln!("mosaic: errore nei timer: {}", e);
|
||||
0
|
||||
}
|
||||
};
|
||||
if eseguiti > 0 {
|
||||
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
|
||||
applica(doc, ops);
|
||||
}
|
||||
eseguiti
|
||||
}
|
||||
|
||||
/// Prima scadenza futura secondo l'orologio del guscio, se c'è un timer in coda.
|
||||
pub fn prossima_scadenza(&mut self) -> Option<u64> {
|
||||
match self.ctx.eval(Source::from_bytes("__timer_prossimo()")) {
|
||||
Ok(v) => v
|
||||
.to_number(&mut self.ctx)
|
||||
.ok()
|
||||
.filter(|n| *n >= 0.0)
|
||||
.map(|n| n as u64),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Vero se l'ultimo evento consegnato è stato annullato con `preventDefault`.
|
||||
pub fn preventuto_default(&mut self) -> bool {
|
||||
self.ctx
|
||||
@@ -1589,6 +1698,99 @@ mod tests {
|
||||
assert_eq!(scritti, vec![(nodo, "impostato".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timer_scatta_quando_il_tempo_avanza() {
|
||||
let mut built = treebuilder::parse(
|
||||
"<div id=\"t\">fermo</div><script>\
|
||||
setTimeout(function () {\
|
||||
document.getElementById('t').textContent = 'scattato';\
|
||||
}, 100);</script>",
|
||||
);
|
||||
let mut macchina = Macchina::nuova().expect("interprete");
|
||||
macchina.esegui(&mut built.doc, &built.scripts);
|
||||
assert_eq!(testo_del_div(&built.doc, "t"), "fermo");
|
||||
|
||||
// il tempo lo decide il test: prima della scadenza non succede nulla
|
||||
assert_eq!(macchina.pompa_timer(&mut built.doc, 50, 10), 0);
|
||||
assert_eq!(testo_del_div(&built.doc, "t"), "fermo");
|
||||
assert_eq!(macchina.pompa_timer(&mut built.doc, 150, 10), 1);
|
||||
assert_eq!(testo_del_div(&built.doc, "t"), "scattato");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interval_ripete_e_clear_ferma() {
|
||||
let mut built = treebuilder::parse(
|
||||
"<div id=\"t\">0</div><script>\
|
||||
var n = 0;\
|
||||
var id = setInterval(function () {\
|
||||
n = n + 1;\
|
||||
document.getElementById('t').textContent = String(n);\
|
||||
if (n >= 3) { clearInterval(id); }\
|
||||
}, 10);</script>",
|
||||
);
|
||||
let mut macchina = Macchina::nuova().expect("interprete");
|
||||
macchina.esegui(&mut built.doc, &built.scripts);
|
||||
|
||||
// un tick per volta, come farebbe un vero ciclo di eventi
|
||||
assert_eq!(macchina.pompa_timer(&mut built.doc, 10, 10), 1);
|
||||
assert_eq!(testo_del_div(&built.doc, "t"), "1");
|
||||
assert_eq!(macchina.pompa_timer(&mut built.doc, 20, 10), 1);
|
||||
assert_eq!(testo_del_div(&built.doc, "t"), "2");
|
||||
assert_eq!(macchina.pompa_timer(&mut built.doc, 30, 10), 1);
|
||||
assert_eq!(testo_del_div(&built.doc, "t"), "3");
|
||||
|
||||
// dopo clearInterval non resta nulla in coda
|
||||
assert_eq!(macchina.pompa_timer(&mut built.doc, 999, 10), 0);
|
||||
assert_eq!(macchina.prossima_scadenza(), None);
|
||||
assert_eq!(testo_del_div(&built.doc, "t"), "3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn salto_grande_non_ripete_i_tick_persi() {
|
||||
// un solo salto in avanti esegue l'intervallo una volta sola, come i browser
|
||||
let mut built = treebuilder::parse(
|
||||
"<div id=\"t\">0</div><script>\
|
||||
var n = 0;\
|
||||
setInterval(function () { n = n + 1; document.getElementById('t').textContent = String(n); }, 10);\
|
||||
</script>",
|
||||
);
|
||||
let mut macchina = Macchina::nuova().expect("interprete");
|
||||
macchina.esegui(&mut built.doc, &built.scripts);
|
||||
assert_eq!(macchina.pompa_timer(&mut built.doc, 1000, 50), 1);
|
||||
assert_eq!(testo_del_div(&built.doc, "t"), "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prossima_scadenza_riportata_al_guscio() {
|
||||
let mut built =
|
||||
treebuilder::parse("<div>x</div><script>setTimeout(function () {}, 400);</script>");
|
||||
let mut macchina = Macchina::nuova().expect("interprete");
|
||||
macchina.esegui(&mut built.doc, &built.scripts);
|
||||
macchina.pompa_timer(&mut built.doc, 0, 10);
|
||||
assert_eq!(macchina.prossima_scadenza(), Some(400));
|
||||
macchina.pompa_timer(&mut built.doc, 399, 10);
|
||||
assert_eq!(macchina.prossima_scadenza(), Some(400));
|
||||
macchina.pompa_timer(&mut built.doc, 400, 10);
|
||||
assert_eq!(macchina.prossima_scadenza(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timer_che_crea_contenuto() {
|
||||
let mut built = treebuilder::parse(
|
||||
"<div id=\"zona\"></div><script>\
|
||||
setTimeout(function () {\
|
||||
var p = document.createElement('p');\
|
||||
p.textContent = 'dopo 1 secondo';\
|
||||
document.getElementById('zona').appendChild(p);\
|
||||
}, 1000);</script>",
|
||||
);
|
||||
let mut macchina = Macchina::nuova().expect("interprete");
|
||||
macchina.esegui(&mut built.doc, &built.scripts);
|
||||
assert_eq!(testo_del_div(&built.doc, "zona"), "");
|
||||
macchina.pompa_timer(&mut built.doc, 1000, 10);
|
||||
assert_eq!(testo_del_div(&built.doc, "zona"), "dopo 1 secondo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prevent_default_sopravvive_alla_propagazione() {
|
||||
// il gestore sta sul form; l'evento prosegue su body e html: il flag non
|
||||
|
||||
Reference in new issue
Block a user