Skip to main content

hpl_cjk_text/
breakspace.rs

1//! Break-space insertion for the stock exe, which only wraps at U+0020. A faithful port of
2//! `insert_break_spaces` in the TC tooling's `scripts/common.py`:
3//!
4//! 1. Original spaces become `wide_space` (the CJK fonts give U+0020 ~0 advance). A `$But…`
5//!    variable is followed by `icon_pad[action]` as gamepad icon room, which absorbs one
6//!    original space right after it. Variables without icon room keep their spaces; at the
7//!    end of a string they get a trailing `wide_space`.
8//! 2. U+0020 is inserted between two adjacent CJK characters (or after padding before a CJK
9//!    character), unless the second is a no-line-start character, the first a no-line-end
10//!    character, or the second is padding. After a wide space that replaced an original space,
11//!    U+0020 is inserted before any character except no-line-start characters, padding and
12//!    tokens.
13//!
14//! Tokens (`$But…`, `[br]`, `[u…]`) are atomic: nothing is inserted next to them.
15//! `breaks = false` applies only rule 1 (short labels that never wrap).
16
17use crate::rules::{is_cjk, NO_LINE_END, NO_LINE_START};
18use std::collections::{HashMap, HashSet};
19
20const ICON_SPACE: char = '\u{3000}';
21const DPAD_EXTRA: char = '\u{2002}';
22
23/// Options for [`insert_break_spaces`]; the defaults equal the TC tooling's defaults.
24#[derive(Clone, Debug)]
25pub struct BreakSpaceOptions {
26    pub wide_space: char,
27    pub breaks: bool,
28    /// Action name (after `$But`) -> padding inserted after the variable.
29    pub icon_pad: HashMap<String, String>,
30}
31
32impl Default for BreakSpaceOptions {
33    fn default() -> Self {
34        BreakSpaceOptions { wide_space: '\u{3000}', breaks: true, icon_pad: default_icon_pad() }
35    }
36}
37
38/// Padding after each `$But<Action>` whose default gamepad binding draws an icon (TC tooling:
39/// `DEFAULT_ICON_PAD`, derived from `config/default_user_keys_sdl2.cfg` plus Exit = Start).
40/// LB/RB icons are 2 em wide.
41pub fn default_icon_pad() -> HashMap<String, String> {
42    let one = ICON_SPACE.to_string();
43    let two: String = [ICON_SPACE, ICON_SPACE].iter().collect();
44    [
45        ("Inventory", &one), ("Journal", &one), ("Attack", &two), ("Interact", &two),
46        ("Rotate", &one), ("Lantern", &one), ("Run", &one), ("Lean", &one),
47        ("Crouch", &one), ("Jump", &one), ("QuestLog", &one), ("Exit", &one),
48    ]
49    .into_iter()
50    .map(|(k, v)| (k.to_string(), v.clone()))
51    .collect()
52}
53
54/// One element of the masked text.
55#[derive(Clone, Copy, PartialEq, Eq)]
56enum Item {
57    Char(char),
58    /// Index into the token list.
59    Token(usize),
60}
61
62/// Splits `text` into characters and tokens. Tokens follow the TC regex
63/// `\[br\]|\[u\d+\]|\$But[A-Za-z]+` (ASCII digits).
64fn tokenize(text: &str) -> (Vec<Item>, Vec<String>) {
65    let mut items = Vec::new();
66    let mut tokens = Vec::new();
67    let mut rest = text;
68    while let Some(c) = rest.chars().next() {
69        if let Some(len) = token_len(rest) {
70            tokens.push(rest[..len].to_string());
71            items.push(Item::Token(tokens.len() - 1));
72            rest = &rest[len..];
73        } else {
74            items.push(Item::Char(c));
75            rest = &rest[c.len_utf8()..];
76        }
77    }
78    (items, tokens)
79}
80
81fn token_len(s: &str) -> Option<usize> {
82    let b = s.as_bytes();
83    if s.starts_with("[br]") {
84        return Some(4);
85    }
86    if s.starts_with("[u") {
87        let digits = b[2..].iter().take_while(|c| c.is_ascii_digit()).count();
88        if digits > 0 && b.get(2 + digits) == Some(&b']') {
89            return Some(3 + digits);
90        }
91    }
92    if s.starts_with("$But") {
93        let letters = b[4..].iter().take_while(|c| c.is_ascii_alphabetic()).count();
94        if letters > 0 {
95            return Some(4 + letters);
96        }
97    }
98    None
99}
100
101/// Port of `insert_break_spaces`; see the module docs for the rules.
102pub fn insert_break_spaces(text: &str, opts: &BreakSpaceOptions) -> String {
103    let (masked, tokens) = tokenize(text);
104    let ws = opts.wide_space;
105
106    // Padding after each $But token (empty when the action draws no icon).
107    let but_pad = |item: Item| -> Option<&str> {
108        match item {
109            Item::Token(t) => tokens[t]
110                .strip_prefix("$But")
111                .map(|action| opts.icon_pad.get(action).map(String::as_str).unwrap_or("")),
112            Item::Char(_) => None,
113        }
114    };
115    let mut pads: HashSet<char> = [ws, ICON_SPACE, DPAD_EXTRA].into();
116    for v in opts.icon_pad.values() {
117        let mut it = v.chars();
118        if let (Some(c), None) = (it.next(), it.next()) {
119            pads.insert(c);
120        }
121    }
122
123    // Rule 1: spaces and icon padding.
124    let mut chars: Vec<Item> = Vec::with_capacity(masked.len() * 2);
125    let mut orig_space: HashSet<usize> = HashSet::new();
126    for (i, &item) in masked.iter().enumerate() {
127        if item == Item::Char(' ') {
128            if i > 0 && but_pad(masked[i - 1]).is_some_and(|p| !p.is_empty()) {
129                continue; // absorbed by the icon room
130            }
131            orig_space.insert(chars.len());
132            chars.push(Item::Char(ws));
133            continue;
134        }
135        chars.push(item);
136        if let Some(pad) = but_pad(item) {
137            if !pad.is_empty() {
138                chars.extend(pad.chars().map(Item::Char));
139            } else if i == masked.len() - 1 {
140                chars.push(Item::Char(ws));
141            }
142        }
143    }
144
145    let render = |items: &[Item]| -> String {
146        let mut s = String::with_capacity(text.len() * 2);
147        for item in items {
148            match *item {
149                Item::Char(c) => s.push(c),
150                Item::Token(t) => s.push_str(&tokens[t]),
151            }
152        }
153        s
154    };
155    if !opts.breaks {
156        return render(&chars);
157    }
158
159    // Rule 2: break spaces.
160    let cjk = |item: Item| matches!(item, Item::Char(c) if is_cjk(c));
161    let is_pad = |item: Item| matches!(item, Item::Char(c) if pads.contains(&c));
162    let in_set = |item: Item, set: &[char]| matches!(item, Item::Char(c) if set.contains(&c));
163    let mut out: Vec<Item> = Vec::with_capacity(chars.len() * 2);
164    for (i, &c) in chars.iter().enumerate() {
165        if i > 0 {
166            let a = chars[i - 1];
167            let blocked = in_set(c, NO_LINE_START) || is_pad(c);
168            let after_space = orig_space.contains(&(i - 1)) && matches!(c, Item::Char(_));
169            let between_cjk = (cjk(a) || is_pad(a)) && cjk(c) && !in_set(a, NO_LINE_END);
170            if !blocked && (after_space || between_cjk) {
171                out.push(Item::Char(' '));
172            }
173        }
174        out.push(c);
175    }
176    render(&out)
177}