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.2.1
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-15
Size
106.1 KB
Downloads
24
Checksum
2dc69758bdc87c93f18bd70b188794e42b99dd6ed36955a65b7bdf8109030321
Dependencies
rust/[email protected]
rust/[email protected]

serve.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//! A small server for trying hongo from a browser
//!
//! Paste the source text and press the button, and it becomes a PDF that is shown on the screen
//! and can also be saved.
//!
//! Usage:
//!   cargo run --release --example serve
//!   cargo run --release --example serve -- --port 8080 --font-japanese font/ipaexm.ttf
//!
//! Open http://127.0.0.1:7830. It does not accept connections from other machines.

use hongo::style::Style;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::Arc;


/// The maximum size of the source text it accepts
const LIMIT: usize = 4 * 1024 * 1024;


/// The directory from which images and `\input` files are looked for
const BASE: &str = "test";


/// The sample that is filled in from the start
const SAMPLE: &str = include_str!("../test/report.tex");


const PAGE: &str = include_str!("serve.html");


fn main() {
    let mut argument: Vec<String> = std::env::args().skip(1).collect();
    let port = take(&mut argument, "--port").unwrap_or_else(|| "7830".to_string());
    let japanese = take(&mut argument, "--font-japanese").map(PathBuf::from);
    let math = PathBuf::from("font/latinmodern-math.otf");

    if !math.is_file() {
        eprintln!("font/latinmodern-math.otf がありません");
        std::process::exit(1);
    }

    let japanese = japanese.or_else(|| any_font(&math));

    if japanese.is_none() {
        eprintln!("和文の書体がありません。font/ に明朝体を置くと日本語が出ます");
    }

    let library = match hongo::font::open(
        &math,
        None,
        None,
        None,
        None,
        None,
        japanese.as_deref(),
    ) {
        Ok(library) => Arc::new(library),
        Err(reason) => {
            eprintln!("書体を読めません: {reason}");
            std::process::exit(1);
        }
    };
    let address = format!("127.0.0.1:{port}");
    let listener = match TcpListener::bind(&address) {
        Ok(listener) => listener,
        Err(reason) => {
            eprintln!("{address} を開けません: {reason}");
            std::process::exit(1);
        }
    };
    println!("http://{address} を開いてください");

    for coming in listener.incoming() {
        let stream = match coming {
            Ok(stream) => stream,
            Err(_) => continue,
        };
        let library = Arc::clone(&library);
        std::thread::spawn(move || answer(stream, &library));
    }
}


/// 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() {
        eprintln!("{name} のあとに値を書いてください");
        std::process::exit(1);
    }

    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()
}


/// Responds to one incoming connection
fn answer(mut stream: TcpStream, library: &hongo::Library) {
    let mut reader = match stream.try_clone() {
        Ok(copy) => BufReader::new(copy),
        Err(_) => return,
    };
    let mut head = String::new();

    if reader.read_line(&mut head).is_err() {
        return;
    }

    let mut length = 0;

    loop {
        let mut line = String::new();

        match reader.read_line(&mut line) {
            Ok(0) => break,
            Ok(_) => {}
            Err(_) => return,
        }

        if line.trim().is_empty() {
            break;
        }

        if let Some(value) = line.to_lowercase().strip_prefix("content-length:") {
            length = value.trim().parse::<usize>().unwrap_or(0).min(LIMIT);
        }
    }

    let mut word = head.split_whitespace();
    let method = word.next().unwrap_or_default();
    let path = word.next().unwrap_or_default();

    match (method, path) {
        ("GET", "/") => send(&mut stream, "200 OK", "text/html; charset=utf-8", "", PAGE.as_bytes()),
        ("GET", "/sample") => send(
            &mut stream,
            "200 OK",
            "text/plain; charset=utf-8",
            "",
            SAMPLE.as_bytes(),
        ),
        ("POST", "/pdf") => {
            let mut body = vec![0; length];

            if reader.read_exact(&mut body).is_err() {
                send(&mut stream, "400 Bad Request", "text/plain; charset=utf-8", "", b"");

                return;
            }

            let source = String::from_utf8_lossy(&body).to_string();
            make(&mut stream, &source, library);
        }
        _ => send(
            &mut stream,
            "404 Not Found",
            "text/plain; charset=utf-8",
            "",
            "ありません".as_bytes(),
        ),
    }
}


/// Typesets the source text and sends the result back
fn make(stream: &mut TcpStream, source: &str, library: &hongo::Library) {
    let style = Style::default();

    match hongo::render(source, library, &style, Path::new(BASE)) {
        Ok(made) => {
            let missing: String = made.missing.iter().collect();
            let extra = format!(
                "X-Page: {}\r\nX-Missing: {}\r\nContent-Disposition: inline; filename=\"hongo.pdf\"\r\n",
                made.page,
                escape(&missing)
            );
            send(stream, "200 OK", "application/pdf", &extra, &made.data);
        }
        Err(reason) => send(
            stream,
            "400 Bad Request",
            "text/plain; charset=utf-8",
            "",
            reason.message.as_bytes(),
        ),
    }
}


/// Turns characters that are not ASCII into %XX so that they can go in a header
fn escape(text: &str) -> String {
    let mut out = String::new();

    for byte in text.as_bytes() {
        if byte.is_ascii_alphanumeric() {
            out.push(*byte as char);

        } else {
            out.push_str(&format!("%{byte:02X}"));
        }
    }

    out
}


/// Writes the response
fn send(stream: &mut TcpStream, status: &str, kind: &str, extra: &str, body: &[u8]) {
    let head = format!(
        "HTTP/1.1 {status}\r\nContent-Type: {kind}\r\nContent-Length: {}\r\n\
Cache-Control: no-store\r\n{extra}Connection: close\r\n\r\n",
        body.len()
    );
    let _ = stream.write_all(head.as_bytes());
    let _ = stream.write_all(body);
    let _ = stream.flush();
}