Skip to main content

deq_shapes/
leet.rs

1//! Deq Leet: text written with Deq glyphs, and decoding of `basic` output (ADR 0015).
2//!
3//! The tables come from `data/leet.json`, generated from `spec/leet/`.
4
5use std::collections::HashMap;
6use std::sync::LazyLock;
7
8use regex::Regex;
9use serde_json::{Map, Value};
10use unicode_normalization::UnicodeNormalization;
11
12use crate::error::{DeqError, ErrorCode, Result};
13use crate::format::{is_integer, js_round, js_str, num};
14use crate::options::{number, picklist};
15use crate::pattern::compile;
16use crate::random::{MAX_SEED, Random};
17use crate::scene::{Cell, Scene, glyph_markup, resolve_scene_options, scene_svg};
18
19/// The longest input accepted, in UTF-16 code units.
20pub const MAX_INPUT: usize = 1024;
21/// The most glyphs one text may draw.
22pub const MAX_GLYPHS: usize = MAX_GLYPHS_U32 as usize;
23/// The most lines one text may have.
24pub const MAX_LINES: usize = MAX_LINES_U32 as usize;
25// The caps as `u32`, for exact conversion to `f64`.
26const MAX_GLYPHS_U32: u32 = 256;
27const MAX_LINES_U32: u32 = 32;
28
29/// Largest SVG [`decode_leet`] reads, in UTF-16 code units.
30pub const MAX_DECODE_INPUT: usize = 4 * 1024 * 1024;
31
32static TABLES: LazyLock<Value> = LazyLock::new(|| {
33    serde_json::from_str(include_str!("../data/leet.json")).unwrap_or(Value::Null)
34});
35
36static INDEX: LazyLock<[HashMap<String, &'static Value>; 2]> =
37    LazyLock::new(|| [build_index(Script::Latin), build_index(Script::Sorani)]);
38
39const NUM: &str = r"[0-9]+(?:\.[0-9]+)?";
40static META: LazyLock<Regex> = LazyLock::new(|| {
41    compile(&format!(
42        r#"^<svg [^>]*?data-deq-leet="(latin|sorani) (basic|advanced|full) ({NUM}) ({NUM})""#
43    ))
44});
45static GROUP: LazyLock<Regex> = LazyLock::new(|| {
46    compile(&format!(
47        r#"(?s)<g data-layer="c[0-9]+" transform="translate\((-?{NUM}) (-?{NUM})\)"(?: color="[^"<>]*" stroke="currentColor")?>(.*?)</g>"#
48    ))
49});
50
51/// A script with a Leet table.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum Script {
54    /// Latin and Kurmanji letters, digits and punctuation, left to right.
55    Latin,
56    /// Sorani in Arabic script, right to left.
57    Sorani,
58}
59
60impl Script {
61    /// The script's name in the tables and options.
62    #[must_use]
63    pub fn as_str(self) -> &'static str {
64        match self {
65            Self::Latin => "latin",
66            Self::Sorani => "sorani",
67        }
68    }
69
70    fn from_name(name: &str) -> Self {
71        if name == "sorani" {
72            Self::Sorani
73        } else {
74            Self::Latin
75        }
76    }
77
78    fn slot(self) -> usize {
79        match self {
80            Self::Latin => 0,
81            Self::Sorani => 1,
82        }
83    }
84}
85
86/// The table of `script`: `{version, script, direction, aliases, glyphs}` as in `spec/leet/`.
87#[must_use]
88pub fn leet_table(script: Script) -> &'static Value {
89    &TABLES[script.as_str()]
90}
91
92fn build_index(script: Script) -> HashMap<String, &'static Value> {
93    leet_table(script)["glyphs"]
94        .as_array()
95        .map(|glyphs| {
96            glyphs
97                .iter()
98                .filter_map(|e| e["char"].as_str().map(|c| (c.to_owned(), e)))
99                .collect()
100        })
101        .unwrap_or_default()
102}
103
104/// The entry for an already normalised character, if the table has one.
105#[must_use]
106pub fn entry_of(script: Script, ch: &str) -> Option<&'static Value> {
107    INDEX[script.slot()].get(ch).copied()
108}
109
110/// Sorani when `text` has Arabic-script letters, else Latin.
111#[must_use]
112pub fn detect_script(text: &str) -> Script {
113    if text.chars().any(|c| ('\u{600}'..='\u{6FF}').contains(&c)) {
114        Script::Sorani
115    } else {
116        Script::Latin
117    }
118}
119
120// Joiners, tatweel and bidi controls carry no letter of their own.
121fn ignored(c: char) -> bool {
122    matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{640}' | '\u{FEFF}')
123}
124
125fn space(c: char) -> bool {
126    matches!(
127        c,
128        '\t' | ' ' | '\u{A0}' | '\u{2000}'..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
129    )
130}
131
132/// What JavaScript's `trimStart` removes.
133fn js_space(c: char) -> bool {
134    matches!(
135        c,
136        '\t' | '\n' | '\u{B}' | '\u{C}' | '\r' | ' ' | '\u{A0}' | '\u{1680}' | '\u{2000}'
137            ..='\u{200A}'
138                | '\u{2028}'
139                | '\u{2029}'
140                | '\u{202F}'
141                | '\u{205F}'
142                | '\u{3000}'
143                | '\u{FEFF}'
144    )
145}
146
147fn utf16_len(s: &str) -> usize {
148    s.encode_utf16().count()
149}
150
151fn limit(message: String) -> DeqError {
152    DeqError::new(ErrorCode::LimitExceeded, message)
153}
154
155/// The result of [`normalize`].
156#[derive(Debug, Clone, PartialEq)]
157pub struct Normalized {
158    /// Lines of tokens (a table entry, or `None` for a space), trimmed.
159    pub lines: Vec<Vec<Option<&'static Value>>>,
160    /// The normalised text (what decoding `basic` output gives back).
161    pub text: String,
162    /// Characters with no glyph in the table, in first-seen order.
163    pub unknown: Vec<String>,
164}
165
166/// Normalise `text` for `script`: NFC, LF, no joiners or tatweel, upper case, aliases.
167///
168/// # Errors
169/// `LimitExceeded` for input over [`MAX_INPUT`], more than [`MAX_GLYPHS`] glyphs or more
170/// than [`MAX_LINES`] lines.
171pub fn normalize(text: &str, script: Script) -> Result<Normalized> {
172    if utf16_len(text) > MAX_INPUT {
173        return Err(limit(format!("text is longer than {MAX_INPUT} characters")));
174    }
175    let aliases = &leet_table(script)["aliases"];
176    let mut unknown: Vec<String> = Vec::new();
177    let mut raw: Vec<Vec<Option<&'static Value>>> = vec![Vec::new()];
178    let mut glyphs = 0usize;
179    let clean: String = text
180        .nfc()
181        .collect::<String>()
182        .replace("\r\n", "\n")
183        .replace('\r', "\n");
184    for ch in clean.chars().filter(|c| !ignored(*c)) {
185        if ch == '\n' {
186            raw.push(Vec::new());
187            continue;
188        }
189        let Some(line) = raw.last_mut() else { continue };
190        if space(ch) {
191            line.push(None);
192            continue;
193        }
194        for up in ch.to_uppercase() {
195            let up = up.to_string();
196            let key = aliases.get(&up).and_then(Value::as_str).unwrap_or(&up);
197            if let Some(entry) = entry_of(script, key) {
198                line.push(Some(entry));
199                glyphs += 1;
200            } else {
201                let original = ch.to_string();
202                if !unknown.contains(&original) {
203                    unknown.push(original);
204                }
205            }
206        }
207    }
208    if glyphs > MAX_GLYPHS {
209        return Err(limit(format!("text has more than {MAX_GLYPHS} glyphs")));
210    }
211    let mut lines: Vec<Vec<Option<&'static Value>>> = raw
212        .into_iter()
213        .map(|row| {
214            let a = row.iter().position(Option::is_some).unwrap_or(row.len());
215            let b = row.iter().rposition(Option::is_some).map_or(a, |b| b + 1);
216            row.get(a..b).map(<[_]>::to_vec).unwrap_or_default()
217        })
218        .collect();
219    let first = lines
220        .iter()
221        .position(|l| !l.is_empty())
222        .unwrap_or(lines.len());
223    let last = lines
224        .iter()
225        .rposition(|l| !l.is_empty())
226        .map_or(first, |b| b + 1);
227    lines = lines
228        .get(first..last)
229        .map(<[_]>::to_vec)
230        .unwrap_or_default();
231    if lines.len() > MAX_LINES {
232        return Err(limit(format!("text has more than {MAX_LINES} lines")));
233    }
234    let text = lines
235        .iter()
236        .map(|row| {
237            row.iter()
238                .map(|t| t.and_then(|e| e["char"].as_str()).unwrap_or(" "))
239                .collect::<String>()
240        })
241        .collect::<Vec<_>>()
242        .join("\n");
243    Ok(Normalized {
244        lines,
245        text,
246        unknown,
247    })
248}
249
250/// A check of one option: `None` when the value is fine, else the problem.
251pub(crate) type Check = fn(&Value) -> Option<String>;
252
253pub(crate) fn integer(v: &Value, lo: f64, hi: f64) -> Option<String> {
254    if !is_integer(v) {
255        return Some("must be an integer".to_owned());
256    }
257    let x = v.as_f64().unwrap_or(f64::NAN);
258    if (lo..=hi).contains(&x) {
259        None
260    } else {
261        Some(format!(
262            "must be from {} to {} (got {})",
263            num(lo),
264            num(hi),
265            js_str(v)
266        ))
267    }
268}
269
270pub(crate) fn seed_check(v: &Value) -> Option<String> {
271    integer(v, 0.0, f64::from(MAX_SEED))
272}
273
274/// A whole number already checked to be in range, as an index type.
275#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
276pub(crate) fn to_usize(v: f64) -> usize {
277    v as usize
278}
279
280/// A seed already checked to be in range.
281#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
282pub(crate) fn to_seed(v: Option<&Value>) -> u32 {
283    v.and_then(Value::as_f64).map_or(1, |s| s as u32)
284}
285
286const LEET_CHECKS: [(&str, Check); 6] = [
287    ("level", |v| picklist(v, &["basic", "advanced", "full"])),
288    ("script", |v| picklist(v, &["latin", "sorani"])),
289    ("seed", seed_check),
290    ("letterSpacing", |v| number(v, 0.0, 24.0, false)),
291    ("lineSpacing", |v| number(v, 0.0, 48.0, false)),
292    ("align", |v| picklist(v, &["start", "center", "end"])),
293];
294
295/// Split `options` into checked own options and the scene options left over.
296pub(crate) fn split_options(
297    options: &Value,
298    checks: &[(&str, Check)],
299    what: &str,
300) -> Result<(Map<String, Value>, Value)> {
301    let Value::Object(map) = options else {
302        return Ok((Map::new(), options.clone()));
303    };
304    let mut scene = map.clone();
305    let mut own = Map::new();
306    let mut issues = Vec::new();
307    for (key, check) in checks {
308        if let Some(v) = scene.shift_remove(*key) {
309            match check(&v) {
310                None => {
311                    own.insert((*key).to_owned(), v);
312                }
313                Some(problem) => issues.push(format!("{key}: {problem}")),
314            }
315        }
316    }
317    if issues.is_empty() {
318        Ok((own, Value::Object(scene)))
319    } else {
320        Err(DeqError::options(&format!("invalid {what}"), issues))
321    }
322}
323
324/// The result of [`leet`].
325#[derive(Debug, Clone, PartialEq)]
326pub struct LeetResult {
327    /// The SVG document, one `<g data-layer="cN">` per glyph in reading order.
328    pub svg: String,
329    /// The normalised text that was drawn.
330    pub text: String,
331    /// The script used.
332    pub script: Script,
333    /// `basic`, `advanced` or `full`.
334    pub level: String,
335    /// Input characters with no glyph, in first-seen order (they are left out).
336    pub unknown: Vec<String>,
337    /// The placed glyphs.
338    pub scene: Scene,
339}
340
341fn glyph_for(entry: &Value, level: &str, random: &mut Random) -> Value {
342    match level {
343        "basic" => entry["basic"].clone(),
344        "full" => entry["full"].clone(),
345        _ => {
346            let mut choices = vec![&entry["basic"]];
347            if let Some(alts) = entry["advanced"].as_array() {
348                choices.extend(alts.iter());
349            }
350            random
351                .pick(&choices)
352                .map_or_else(|| entry["basic"].clone(), |g| (*g).clone())
353        }
354    }
355}
356
357/// Write `text` with Deq glyphs.
358///
359/// The input is plain text: length-capped, normalised and never parsed as markup.
360/// Characters without a glyph are left out and listed in `unknown`; Sorani runs right to
361/// left. Options are `level`, `script`, `seed`, `letterSpacing`, `lineSpacing`, `align`,
362/// `colors` and the render options except the per-shape ones.
363///
364/// # Errors
365/// `InvalidOptions` (also when nothing is left to draw) or `LimitExceeded`.
366#[allow(clippy::cast_precision_loss)]
367pub fn leet(text: &str, options: &Value) -> Result<LeetResult> {
368    let (own, scene) = split_options(options, &LEET_CHECKS, "leet options")?;
369    resolve_scene_options(&scene)?;
370    let level = own.get("level").and_then(Value::as_str).unwrap_or("basic");
371    let sc = own
372        .get("script")
373        .and_then(Value::as_str)
374        .map_or_else(|| detect_script(text), Script::from_name);
375    let rtl = leet_table(sc)["direction"] == "rtl";
376    let norm = normalize(text, sc)?;
377    if norm.lines.iter().all(Vec::is_empty) {
378        let issue = format!("text: no characters of the {} table", sc.as_str());
379        return Err(DeqError::options("invalid text", vec![issue]));
380    }
381    let f = |key: &str, default: f64| own.get(key).and_then(Value::as_f64).unwrap_or(default);
382    let ls = f("letterSpacing", 2.0);
383    let lh = f("lineSpacing", 6.0);
384    let ax = 24.0 + ls;
385    let ay = 24.0 + lh;
386    let cols = norm.lines.iter().map(Vec::len).max().unwrap_or(0);
387    let width = cols as f64 * ax - ls;
388    let height = norm.lines.len() as f64 * ay - lh;
389    let mut random = Random::new(to_seed(own.get("seed")));
390    let at = own.get("align").and_then(Value::as_str).unwrap_or("start");
391    let mut cells = Vec::new();
392    for (row, tokens) in norm.lines.iter().enumerate() {
393        let len = tokens.len();
394        let free = width - (len as f64 * ax - ls);
395        // The offset of the line's leftmost cell.
396        let left = if at == "center" {
397            free / 2.0
398        } else if (at == "end") != rtl {
399            free
400        } else {
401            0.0
402        };
403        for (col, token) in tokens.iter().enumerate() {
404            let Some(entry) = token else { continue };
405            let slot = if rtl { len - 1 - col } else { col };
406            cells.push(Cell {
407                x: left + slot as f64 * ax,
408                y: row as f64 * ay,
409                glyph: glyph_for(entry, level, &mut random),
410            });
411        }
412    }
413    let placed = Scene {
414        width,
415        height,
416        cells,
417    };
418    let meta = format!(
419        " data-deq-leet=\"{} {level} {} {}\"",
420        sc.as_str(),
421        num(ax),
422        num(ay)
423    );
424    let svg = scene_svg(&placed, &scene, &norm.text.replace('\n', " "), &meta)?;
425    Ok(LeetResult {
426        svg,
427        text: norm.text,
428        script: sc,
429        level: level.to_owned(),
430        unknown: norm.unknown,
431        scene: placed,
432    })
433}
434
435/// The result of [`decode_leet`].
436#[derive(Debug, Clone, PartialEq, Eq)]
437pub struct DecodedLeet {
438    /// The text; glyphs that are not basic glyphs read as U+FFFD.
439    pub text: String,
440    /// The script named in the SVG.
441    pub script: Script,
442    /// How many glyph groups were not basic glyphs of the table.
443    pub unmatched: usize,
444}
445
446fn not_leet(issue: &str) -> DeqError {
447    DeqError::options("invalid input", vec![issue.to_owned()])
448}
449
450/// Read the text back from Leet SVG written by [`leet`] at the `basic` level.
451///
452/// `options` must be the render options used to write it. The SVG is treated as text and
453/// only matched against what [`leet`] writes.
454///
455/// # Errors
456/// `InvalidOptions` when the input is not Deq Leet SVG, or `LimitExceeded` (input over
457/// [`MAX_DECODE_INPUT`], more than [`MAX_GLYPHS`] glyphs).
458pub fn decode_leet(svg: &str, options: &Value) -> Result<DecodedLeet> {
459    if utf16_len(svg) > MAX_DECODE_INPUT {
460        return Err(limit(format!(
461            "SVG is larger than {MAX_DECODE_INPUT} characters"
462        )));
463    }
464    let Some(meta) = META.captures(svg.trim_start_matches(js_space)) else {
465        return Err(not_leet(
466            "svg: not Deq Leet SVG (no data-deq-leet attribute)",
467        ));
468    };
469    let script = Script::from_name(&meta[1]);
470    let ax: f64 = meta[3].parse().unwrap_or(0.0);
471    let ay: f64 = meta[4].parse().unwrap_or(0.0);
472    // The advances leet() can write: 24 plus the letter (0..24) or line (0..48) spacing.
473    if !(24.0..=48.0).contains(&ax) || !(24.0..=72.0).contains(&ay) {
474        return Err(not_leet("svg: data-deq-leet advances out of range"));
475    }
476    let o = resolve_scene_options(options)?.render;
477    let mut by_markup: HashMap<String, String> = HashMap::new();
478    if let Some(glyphs) = leet_table(script)["glyphs"].as_array() {
479        for entry in glyphs {
480            let ch = entry["char"].as_str().unwrap_or_default().to_owned();
481            by_markup.insert(glyph_markup(&entry["basic"], &o)?, ch);
482        }
483    }
484    let mut text = String::new();
485    let mut unmatched = 0usize;
486    let mut prev: Option<(f64, f64)> = None;
487    for (n, m) in GROUP.captures_iter(svg).enumerate() {
488        if n >= MAX_GLYPHS {
489            return Err(limit(format!("SVG has more than {MAX_GLYPHS} glyphs")));
490        }
491        let x: f64 = m[1].parse().unwrap_or(0.0);
492        let y: f64 = m[2].parse().unwrap_or(0.0);
493        if let Some((px, py)) = prev {
494            // Gaps are capped at what leet() can write, so crafted offsets cannot blow up.
495            let rows = js_round((y - py) / ay).min(f64::from(MAX_LINES_U32));
496            let gap = js_round((x - px).abs() / ax) - 1.0;
497            if rows > 0.0 {
498                text.push_str(&"\n".repeat(to_usize(rows)));
499            } else {
500                text.push_str(&" ".repeat(to_usize(gap.clamp(0.0, f64::from(MAX_GLYPHS_U32)))));
501            }
502        }
503        prev = Some((x, y));
504        if let Some(ch) = by_markup.get(&m[3]) {
505            text.push_str(ch);
506        } else {
507            unmatched += 1;
508            text.push('\u{FFFD}');
509        }
510    }
511    Ok(DecodedLeet {
512        text,
513        script,
514        unmatched,
515    })
516}