Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.4.01085.8 KB2026-10-160.3.21087.6 KB2026-10-160.3.11087.5 KB2026-10-160.3.0117.8 KB2026-10-160.2.1106.1 KB2026-10-150.2.0105.5 KB2026-10-15
Version
0.4.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-16
Size
1085.8 KB
Downloads
19
Checksum
df10d3447b809454aba0a9fd252d07428b819520aff22324461ba2dcbf1e43fb
Dependencies
rust/[email protected]
rust/[email protected]

web.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
//! Writes what the page in web/ needs: hongo.js holds the wasm, and font.js holds the typefaces
//!
//! A page opened by double clicking cannot read the files next to it, so both are written as
//! base64 into scripts that the page loads.
//!
//! Usage:
//!   cargo build --lib --release --target wasm32-unknown-unknown
//!   cargo run --example web
//!   cargo run --example web -- --font-japanese /path/to/mincho.otf --output ~/Desktop/hongo

use std::path::{Path, PathBuf};


/// The wasm that cargo builds
const WASM: &str = "target/wasm32-unknown-unknown/release/hongo.wasm";


/// The math typeface
const MATH: &str = "font/latinmodern-math.otf";


/// The directory that holds the page
const PAGE: &str = "web";


fn main() {
    let mut argument: Vec<String> = std::env::args().skip(1).collect();
    let japanese = take(&mut argument, "--font-japanese")
        .map(PathBuf::from)
        .or_else(|| any_font(Path::new(MATH)));
    let output = take(&mut argument, "--output")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(PAGE));
    let wasm = read(
        Path::new(WASM),
        "build it first with cargo build --lib --release --target wasm32-unknown-unknown",
    );
    let math = read(Path::new(MATH), "the math typeface is needed");
    let japanese_data = match &japanese {
        Some(path) => read(path, "cannot read the typeface for Japanese text"),
        None => {
            eprintln!("no typeface for Japanese text, so Japanese will not appear. Put a Mincho typeface in font/ to set it");

            Vec::new()
        }
    };

    if let Err(reason) = std::fs::create_dir_all(&output) {
        fail(&format!("cannot make {}: {reason}", output.display()));
    }

    copy_page(&output);
    write(&output.join("hongo.js"), &format!("const hongoWasm = '{}'\n", base64(&wasm)));
    write(
        &output.join("font.js"),
        &format!(
            "// mathFont is Latin Modern Math from GUST, under the GUST Font License \
(GUST-FONT-LICENSE.txt)\nconst mathFont = '{}'\n\nconst japaneseFont = '{}'\n",
            base64(&math),
            base64(&japanese_data)
        ),
    );

    println!("wrote {}. Open index.html", output.display());
}


/// Takes out one option
fn take(argument: &mut Vec<String>, name: &str) -> Option<String> {
    let at = argument.iter().position(|one| one == name)?;

    if at + 1 >= argument.len() {
        fail(&format!("{name} must be followed by a value"));
    }

    let value = argument.remove(at + 1);
    argument.remove(at);

    Some(value)
}


/// Looks for one typeface in font/ that is not the math typeface
fn any_font(except: &Path) -> Option<PathBuf> {
    let mut found: Vec<PathBuf> = std::fs::read_dir("font")
        .ok()?
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.path())
        .filter(|path| {
            let suffix = path
                .extension()
                .and_then(|one| one.to_str())
                .unwrap_or_default()
                .to_lowercase();

            matches!(suffix.as_str(), "otf" | "ttf" | "ttc") && path != except
        })
        .collect();
    found.sort();

    found.into_iter().next()
}


/// Copies the page and the license of the math typeface when the output is somewhere other than
/// web/
fn copy_page(output: &Path) {
    let same = match (output.canonicalize(), Path::new(PAGE).canonicalize()) {
        (Ok(left), Ok(right)) => left == right,
        _ => false,
    };

    if same {
        return;
    }

    for name in ["index.html", "GUST-FONT-LICENSE.txt"] {
        if let Err(reason) = std::fs::copy(Path::new(PAGE).join(name), output.join(name)) {
            fail(&format!("cannot copy {name}: {reason}"));
        }
    }
}


/// Reads a file. If it cannot be read, says so and stops
fn read(path: &Path, hint: &str) -> Vec<u8> {
    match std::fs::read(path) {
        Ok(data) => data,
        Err(reason) => fail(&format!("cannot read {}: {reason}\n{hint}", path.display())),
    }
}


/// Writes a file. If it cannot be written, says so and stops
fn write(path: &Path, body: &str) {
    if let Err(reason) = std::fs::write(path, body) {
        fail(&format!("cannot write {}: {reason}", path.display()));
    }
}


/// Says what went wrong and stops
fn fail(message: &str) -> ! {
    eprintln!("{message}");
    std::process::exit(1)
}


/// Writes bytes in base64
fn base64(data: &[u8]) -> String {
    const TABLE: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);

    for chunk in data.chunks(3) {
        let value = ((chunk[0] as usize) << 16)
            | ((chunk.get(1).copied().unwrap_or(0) as usize) << 8)
            | (chunk.get(2).copied().unwrap_or(0) as usize);

        out.push(TABLE[(value >> 18) & 63] as char);
        out.push(TABLE[(value >> 12) & 63] as char);
        out.push(if chunk.len() > 1 {TABLE[(value >> 6) & 63] as char} else {'='});
        out.push(if chunk.len() > 2 {TABLE[value & 63] as char} else {'='});
    }

    out
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bytes_become_base64() {
        assert_eq!(base64(b""), "");
        assert_eq!(base64(b"f"), "Zg==");
        assert_eq!(base64(b"fo"), "Zm8=");
        assert_eq!(base64(b"foo"), "Zm9v");
        assert_eq!(base64(b"foobar"), "Zm9vYmFy");
    }
}