mlux 1.14.0

A rich Markdown viewer for modern terminals
Documentation
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! Sandboxed tile renderer.
//!
//! Provides high-level APIs that combine image preparation (Fork 1) with
//! sandboxed rendering (Fork 2). Callers supply [`BuildParams`] and get back
//! a [`TileRenderer`] or dump result — all fork/sandbox/IPC details are hidden.

use std::path::Path;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

use crate::fork_sandbox::process;
use crate::fork_sandbox::sandbox;
use crate::highlight::{HighlightRect, HighlightSpec};
use crate::image::LoadedImages;
use crate::log::{LogBuffer, LogEntry, WireLogEntry};
use crate::pipeline::{BuildParams, compile_and_dump, compile_and_tile};
use crate::tile::DocumentMeta;
use crate::tile_cache::TilePngs;

pub use crate::fork_sandbox::process::ChildProcess;

// ---------------------------------------------------------------------------
// IPC protocol types (private)
// ---------------------------------------------------------------------------

/// Request from parent to child.
#[derive(Serialize, Deserialize)]
enum Request {
    RenderTile(usize),
    FindHighlightRects { idx: usize, spec: HighlightSpec },
    Shutdown,
}

/// Response from child to parent.
///
/// The first message is always `Meta`. Subsequent messages are `Tile`, `Rects`,
/// or `Error`.
#[derive(Serialize, Deserialize)]
enum Response {
    Meta(DocumentMeta),
    Tile {
        idx: usize,
        pngs: TilePngs,
    },
    Rects {
        idx: usize,
        rects: Vec<HighlightRect>,
    },
    Error(String),
}

/// Wire-level wrapper: every child→parent message carries piggyback log entries.
#[derive(Serialize, Deserialize)]
struct ChildMessage {
    response: Response,
    logs: Vec<WireLogEntry>,
}

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// A response from the child process, tagged with the tile index.
#[derive(Debug)]
pub enum TileResponse {
    Tile {
        idx: usize,
        pngs: TilePngs,
    },
    Rects {
        idx: usize,
        rects: Vec<HighlightRect>,
    },
}

/// Tile renderer communicating with a forked child process via typed IPC.
pub struct TileRenderer {
    tx: process::TypedWriter<Request>,
    rx: process::TypedReader<ChildMessage>,
    log_buffer: LogBuffer,
}

impl TileRenderer {
    /// Receive the initial metadata response from the child.
    ///
    /// Must be called exactly once as the first operation after [`build_renderer`].
    pub fn wait_for_meta(&mut self) -> Result<DocumentMeta> {
        match self
            .recv_and_ingest()
            .context("failed to receive metadata from child")?
        {
            Response::Meta(m) => Ok(m),
            Response::Error(e) => anyhow::bail!("child build error: {e}"),
            _ => anyhow::bail!("unexpected response, expected Meta"),
        }
    }

    /// Send a tile render request without waiting for the response.
    pub fn send_render_tile(&mut self, idx: usize) -> Result<()> {
        self.tx.send(&Request::RenderTile(idx))
    }

    /// Send a highlight rects request without waiting for the response.
    pub fn send_find_rects(&mut self, idx: usize, spec: &HighlightSpec) -> Result<()> {
        self.tx.send(&Request::FindHighlightRects {
            idx,
            spec: spec.clone(),
        })
    }

    /// Non-blocking receive. Returns `Ok(None)` if no data is ready.
    pub fn try_recv(&mut self) -> Result<Option<TileResponse>> {
        if !self.has_pending_data() {
            return Ok(None);
        }
        self.recv().map(Some)
    }

    /// Blocking receive. Waits for the next response from the child.
    pub fn recv(&mut self) -> Result<TileResponse> {
        match self.recv_and_ingest()? {
            Response::Tile { idx, pngs } => Ok(TileResponse::Tile { idx, pngs }),
            Response::Rects { idx, rects } => Ok(TileResponse::Rects { idx, rects }),
            Response::Error(e) => anyhow::bail!("{e}"),
            Response::Meta(_) => anyhow::bail!("unexpected Meta response"),
        }
    }

    /// Receive a `ChildMessage`, ingest piggybacked logs, return the `Response`.
    fn recv_and_ingest(&mut self) -> Result<Response> {
        let msg = self.rx.recv()?;
        for entry in msg.logs {
            self.log_buffer.push(LogEntry::from(entry));
        }
        Ok(msg.response)
    }

    /// Request a tile pair (content + sidebar) from the child.
    pub fn render_tile_pair(&mut self, idx: usize) -> Result<TilePngs> {
        self.send_render_tile(idx)?;
        match self.recv()? {
            TileResponse::Tile { pngs, .. } => Ok(pngs),
            _ => anyhow::bail!("unexpected response, expected Tile"),
        }
    }

    /// Request highlight rectangles for a tile's content (no rendering).
    pub fn find_highlight_rects(
        &mut self,
        idx: usize,
        spec: &HighlightSpec,
    ) -> Result<Vec<HighlightRect>> {
        self.send_find_rects(idx, spec)?;
        match self.recv()? {
            TileResponse::Rects { rects, .. } => Ok(rects),
            _ => anyhow::bail!("unexpected response, expected Rects"),
        }
    }

    /// Check if the child has sent data (non-blocking).
    pub fn has_pending_data(&self) -> bool {
        use std::os::fd::AsRawFd;
        let fd = self.rx.as_raw_fd();
        let mut pfd = nix::libc::pollfd {
            fd,
            events: nix::libc::POLLIN,
            revents: 0,
        };
        let ret = unsafe { nix::libc::poll(&mut pfd, 1, 0) };
        ret > 0 && (pfd.revents & nix::libc::POLLIN) != 0
    }

    /// Send shutdown request to the child.
    pub fn shutdown(mut self) {
        let _ = self.tx.send(&Request::Shutdown);
    }
}

// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------

/// Drain child-local log buffer and send a response wrapped in `ChildMessage`.
fn send_with_logs(
    tx: &mut process::TypedWriter<ChildMessage>,
    response: Response,
    log_buf: &LogBuffer,
) -> Result<()> {
    let logs = log_buf
        .drain()
        .into_iter()
        .map(WireLogEntry::from)
        .collect();
    tx.send(&ChildMessage { response, logs })
}

/// Extract image paths (Fork 1, sandboxed) and fetch remote images (parent).
///
/// Fork 1 runs pulldown-cmark under a sandbox with no FS access and TCP denied.
/// The parent then fetches any remote images on the trusted side.
fn prepare_remote_images(
    params: &BuildParams,
    no_sandbox: bool,
    log_buffer: &LogBuffer,
) -> Result<(crate::pipeline::Prescan, LoadedImages)> {
    use crate::fork_sandbox::fork_compute;

    // Fork 1: prescan under sandbox (no FS, no network)
    let prescan_result = fork_compute(None, &[], no_sandbox, log_buffer, {
        let md = params.markdown.clone();
        move || crate::pipeline::prescan(&md)
    })?;
    let paths = &prescan_result.image_paths;

    // Parent: fetch remote images (trusted side)
    let remote_images = if params.allow_remote_images {
        let remote_urls: Vec<String> = paths
            .iter()
            .filter(|p| p.starts_with("http://") || p.starts_with("https://"))
            .cloned()
            .collect();
        if remote_urls.is_empty() {
            LoadedImages::default()
        } else {
            let (images, errors) = crate::image::load_images(&remote_urls, None, true);
            for err in &errors {
                log::warn!("{err}");
            }
            images
        }
    } else {
        LoadedImages::default()
    };

    Ok((prescan_result, remote_images))
}

/// Derive the sandbox read base path from BuildParams.
fn sandbox_read_base(params: &BuildParams) -> Option<&Path> {
    params.base_dir.as_deref()
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Build a sandboxed renderer: prepare images (Fork 1) + fork renderer (Fork 2).
///
/// Returns `(renderer, child_handle)` without waiting for metadata.
/// The caller must call [`TileRenderer::wait_for_meta`] to receive the first message.
pub fn build_renderer(
    params: &BuildParams,
    no_sandbox: bool,
    log_buffer: &LogBuffer,
) -> Result<(TileRenderer, ChildProcess)> {
    let (prescan, remote_images) = prepare_remote_images(params, no_sandbox, log_buffer)?;
    let read_base = sandbox_read_base(params);
    let font_dirs = params.fonts.font_dirs();

    let params = params.clone();
    let read_base = read_base.map(|p| p.to_path_buf());

    let log_buf = log_buffer.clone();
    let (tx, rx, child) = process::fork_with_channels::<Request, ChildMessage, _>(
        move |mut req_rx: process::TypedReader<Request>,
              mut resp_tx: process::TypedWriter<ChildMessage>| {
            // SECURITY: Fork 2 applies sandbox immediately.
            if !no_sandbox
                && let Err(e) = sandbox::enforce_sandbox(read_base.as_deref(), &font_dirs)
            {
                log::warn!("child: sandbox failed: {e:#}");
            }

            // Load local images (Landlock read scope allows git root)
            let (mut images, errors) =
                crate::image::load_images(&prescan.image_paths, params.base_dir.as_deref(), false);
            for err in &errors {
                log::warn!("{err}");
            }

            // Merge pre-fetched remote images from parent
            images.extend(remote_images);

            // Font cache inherited from parent via fork COW (static lifetime)
            let doc = match compile_and_tile(&params, &prescan, images) {
                Ok(doc) => doc,
                Err(e) => {
                    log::error!("child: build failed: {e:#}");
                    let _ =
                        send_with_logs(&mut resp_tx, Response::Error(format!("{e:#}")), &log_buf);
                    return;
                }
            };

            // Send metadata as first response
            let meta = doc.metadata();
            if send_with_logs(&mut resp_tx, Response::Meta(meta), &log_buf).is_err() {
                return;
            }

            // Request loop
            loop {
                let req = match req_rx.recv() {
                    Ok(r) => r,
                    Err(_) => break, // Parent closed channel
                };
                match req {
                    Request::RenderTile(idx) => {
                        let resp =
                            match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                doc.render_tile_pair(idx)
                            })) {
                                Ok(Ok(pngs)) => Response::Tile { idx, pngs },
                                Ok(Err(e)) => Response::Error(format!("render tile {idx}: {e:#}")),
                                Err(_) => Response::Error(format!("render tile {idx}: panic")),
                            };
                        if send_with_logs(&mut resp_tx, resp, &log_buf).is_err() {
                            break;
                        }
                    }
                    Request::FindHighlightRects { idx, spec } => {
                        let resp =
                            match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                doc.find_tile_highlight_rects(idx, &spec)
                            })) {
                                Ok(rects) => Response::Rects { idx, rects },
                                Err(_) => Response::Error(format!(
                                    "find highlight rects tile {idx}: panic"
                                )),
                            };
                        if send_with_logs(&mut resp_tx, resp, &log_buf).is_err() {
                            break;
                        }
                    }
                    Request::Shutdown => break,
                }
            }
        },
    )?;

    Ok((
        TileRenderer {
            tx,
            rx,
            log_buffer: log_buffer.clone(),
        },
        child,
    ))
}

/// Build a sandboxed renderer and wait for metadata.
///
/// Convenience wrapper around [`build_renderer`] that also receives the initial
/// `Response::Meta` message. Used by `render` mode where no loading UI is needed.
///
/// Returns `(metadata, renderer, child_handle)`.
pub fn build_renderer_blocking(
    params: &BuildParams,
    no_sandbox: bool,
    log_buffer: &LogBuffer,
) -> Result<(DocumentMeta, TileRenderer, ChildProcess)> {
    let (mut renderer, child) = build_renderer(params, no_sandbox, log_buffer)?;
    let meta = renderer.wait_for_meta()?;
    Ok((meta, renderer, child))
}

/// Build and dump: prepare images (Fork 1) + fork dump (Fork 2).
///
/// The child compiles the document and writes the generated Typst source
/// and frame tree to stderr, then exits.
pub fn build_dump(
    params: &BuildParams,
    no_sandbox: bool,
    log_buffer: &LogBuffer,
) -> Result<ChildProcess> {
    let (prescan, remote_images) = prepare_remote_images(params, no_sandbox, log_buffer)?;
    let read_base = sandbox_read_base(params);
    let font_dirs = params.fonts.font_dirs();

    let params = params.clone();
    let read_base = read_base.map(|p| p.to_path_buf());

    // Fork 2 for dump: no IPC responses to piggyback logs on. Child writes to
    // stderr and exits immediately, so Fork 2 logs are not forwarded. Fork 1
    // logs (via prepare_remote_images) are still forwarded.
    let (_, _, child) = process::fork_with_channels::<(), (), _>(move |_, _| {
        if !no_sandbox && let Err(e) = sandbox::enforce_sandbox(read_base.as_deref(), &font_dirs) {
            log::warn!("child: sandbox failed: {e:#}");
        }

        // Load local images (Landlock read scope allows git root)
        let (mut images, errors) =
            crate::image::load_images(&prescan.image_paths, params.base_dir.as_deref(), false);
        for err in &errors {
            log::warn!("{err}");
        }

        // Merge pre-fetched remote images from parent
        images.extend(remote_images);

        // Font cache inherited from parent via fork COW (static lifetime)
        if let Err(e) = compile_and_dump(&params, &prescan, images) {
            eprintln!("{e:#}");
            unsafe { nix::libc::_exit(1) }
        }
    })?;

    Ok(child)
}

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

    #[test]
    fn request_response_serde_roundtrip() {
        let req = Request::RenderTile(42);
        let encoded = bincode::serde::encode_to_vec(&req, bincode::config::standard()).unwrap();
        let (decoded, _): (Request, _) =
            bincode::serde::decode_from_slice(&encoded, bincode::config::standard()).unwrap();
        match decoded {
            Request::RenderTile(idx) => assert_eq!(idx, 42),
            _ => panic!("wrong variant"),
        }

        let req2 = Request::Shutdown;
        let encoded2 = bincode::serde::encode_to_vec(&req2, bincode::config::standard()).unwrap();
        let (decoded2, _): (Request, _) =
            bincode::serde::decode_from_slice(&encoded2, bincode::config::standard()).unwrap();
        assert!(matches!(decoded2, Request::Shutdown));

        let req3 = Request::FindHighlightRects {
            idx: 7,
            spec: HighlightSpec {
                target_ranges: vec![10..20, 30..40],
                active_ranges: vec![10..20],
            },
        };
        let encoded3 = bincode::serde::encode_to_vec(&req3, bincode::config::standard()).unwrap();
        let (decoded3, _): (Request, _) =
            bincode::serde::decode_from_slice(&encoded3, bincode::config::standard()).unwrap();
        match decoded3 {
            Request::FindHighlightRects { idx, spec } => {
                assert_eq!(idx, 7);
                assert_eq!(spec.target_ranges.len(), 2);
                assert_eq!(spec.target_ranges[0], 10..20);
                assert_eq!(spec.target_ranges[1], 30..40);
            }
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn response_error_serde_roundtrip() {
        let resp = Response::Error("test error".into());
        let encoded = bincode::serde::encode_to_vec(&resp, bincode::config::standard()).unwrap();
        let (decoded, _): (Response, _) =
            bincode::serde::decode_from_slice(&encoded, bincode::config::standard()).unwrap();
        match decoded {
            Response::Error(msg) => assert_eq!(msg, "test error"),
            _ => panic!("wrong variant"),
        }
    }

    #[test]
    fn child_message_serde_roundtrip() {
        let msg = ChildMessage {
            response: Response::Error("oops".into()),
            logs: vec![WireLogEntry {
                timestamp_ms: 1234567890,
                level: 2,
                target: "mlux::test".into(),
                message: "warning".into(),
            }],
        };
        let encoded = bincode::serde::encode_to_vec(&msg, bincode::config::standard()).unwrap();
        let (decoded, _): (ChildMessage, _) =
            bincode::serde::decode_from_slice(&encoded, bincode::config::standard()).unwrap();
        assert_eq!(decoded.logs.len(), 1);
        assert_eq!(decoded.logs[0].level, 2);
        assert_eq!(decoded.logs[0].message, "warning");
        match decoded.response {
            Response::Error(e) => assert_eq!(e, "oops"),
            _ => panic!("wrong variant"),
        }
    }
}