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.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-15
Size
105.5 KB
Downloads
24
Checksum
f438a48f6f2fc61d892f930eb4fb56fb5a8e302e733a8c3a6283d0ff7350cd08
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
//! ブラウザから試すための小さなサーバ
//!
//! 原稿を貼って押すと PDF になり、そのまま画面に出て、保存もできる。
//!
//! 使い方:
//!   cargo run --release --example serve
//!   cargo run --release --example serve -- --port 8080 --font-japanese font/ipaexm.ttf
//!
//! 開くのは http://127.0.0.1:7830 である。外からはつながらない。

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;


/// 受け取る原稿の大きさの上限
const LIMIT: usize = 4 * 1024 * 1024;


/// 画像や `\input` を探す起点
const BASE: &str = "test";


/// 最初から入れておく見本
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));
    }
}


/// 選び方を 1 つ取り出す
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)
}


/// font/ にある、数式ではない書体を 1 つ探す
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()
}


/// つながってきた 1 つに答える
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(),
        ),
    }
}


/// 原稿を組んで返す
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(),
        ),
    }
}


/// ヘッダに入れられるように、ASCII でない文字を %XX にする
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
}


/// 答えを書き出す
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();
}