edamame 0.1.1

A fast TUI Markdown editor and viewer
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! Resolve image URLs to decoded bytes.
//!
//! Local paths are read from disk relative to the document path (or
//! absolute if the URL starts with `/` or uses the `file://` scheme).
//! `http://` and `https://` URLs are fetched via `ureq` when allowed by
//! the configured `RemoteImagePolicy` plus the per-session "allow remote"
//! flag.
//!
//! This function is **blocking**; the intended call site is a background
//! thread that reports completion via `AppEvent::ImageReady`.  Keeping it
//! blocking (rather than async) avoids an async runtime dependency and
//! keeps the rest of the code-base free of `async fn`s.

use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::time::Duration;

use image::DynamicImage;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;

use crate::config::RemoteImagePolicy;
use crate::image::svg::{rasterize_svg, SvgError, SvgScaleMode, SvgSizing};

/// Decoded image paired with its origin info — sufficient for
/// `ImageCache::decoded` to key the entry and for debugging.
///
/// `scratch` is an optional pre-rendered halfblocks `Buffer` for a known
/// target rect, built on the decode worker thread so the UI thread's
/// first paint doesn't pay a cold-path sync encode.  `None` when image
/// support is absent or when the dispatcher didn't supply the picker +
/// target width at decode time.
#[derive(Debug)]
pub struct LoadedImage {
    pub url: String,
    pub image: DynamicImage,
    pub scratch: Option<(Rect, Buffer)>,
}

/// Errors reported by [`resolve`].  The UI falls back to the
/// `[Image: alt]` placeholder on any variant.
#[derive(Debug, thiserror::Error)]
pub enum ImageLoadError {
    #[error("remote image blocked by policy: {0}")]
    RemoteBlocked(String),
    #[error("file read failed for {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error("http fetch failed for {url}: {source}")]
    Http {
        url: String,
        #[source]
        source: Box<ureq::Error>,
    },
    #[error("image decode failed for {url}: {source}")]
    Decode {
        url: String,
        #[source]
        source: image::ImageError,
    },
    #[error("svg render failed for {url}: {source}")]
    Svg {
        url: String,
        #[source]
        source: SvgError,
    },
    #[error("unsupported url scheme: {0}")]
    UnsupportedScheme(String),
}

/// HTTP timeout for remote image fetches.  Long enough for a busy
/// connection, short enough that the UI doesn't appear hung for minutes
/// if a server ghosts us.
const REMOTE_TIMEOUT: Duration = Duration::from_secs(10);

/// Cap on the size of a *local* image file read off disk.  Remote fetches
/// are already bounded by ureq's 10 MB body limit, but local files
/// otherwise had no cap at all — a multi-gigabyte file would be slurped
/// into memory in one `std::fs::read` before the decode limits below even
/// apply.  64 MB is comfortably above any real raster a terminal would
/// display.
const MAX_LOCAL_IMAGE_BYTES: u64 = 64 * 1024 * 1024;

/// Hard ceilings applied to every raster decode (see [`decode`]).  A
/// highly-compressed raster (PNG zlib ratios routinely exceed 1000:1)
/// expands enormously on decode, and `image`'s decoder allocates the full
/// pixel buffer *before* the loader's `pre_resize` can shrink it — so the
/// only place to bound peak memory is at decode time, via `image::Limits`.
/// 50 000 px per side is far larger than any terminal can show, and the
/// allocation cap bounds the worst-case RGBA buffer to a couple hundred
/// MB so a decode bomb errors out instead of aborting the process.
const MAX_DECODE_DIMENSION: u32 = 50_000;
const MAX_DECODE_ALLOC: u64 = 256 * 1024 * 1024;

/// Resolve `url` to a decoded `DynamicImage`.
///
/// * `doc_path` — path of the currently-open document (used as the base
///   for relative image paths).  Pass `None` for an unsaved buffer;
///   relative URLs then resolve against the current working directory.
/// * `remote_policy` — `Ask` / `Always` / `Never` from config.  `Ask` is
///   interpreted as "blocked unless the per-session flag is set" — the
///   App shows the prompt on document load and flips the flag based on
///   the user's choice.
/// * `session_allow_remote` — set by the remote-load prompt's
///   `Yes` / `Always` buttons.  Takes precedence over a `Never`
///   persisted policy only if the caller has already verified its
///   provenance (the prompt itself defers to policy).
/// * `max_cells` / `font_size` — the target ceiling for pre-resizing
///   the decoded image so the main thread never has to resize on a
///   render path.  Passing `None` disables pre-resize (the main thread
///   will do it in the protocol, incurring a one-time cost on first
///   paint — acceptable for tests that don't exercise rendering).
///
/// Pre-resize runs on the worker thread **before** the image reaches
/// the main thread.  This means by the time `paint_images` builds the
/// `StatefulProtocol` the image already has `cells <= max_cells`, and
/// `Resize::Fit` is a no-op on every subsequent frame — no re-encoding
/// on scroll.
pub fn resolve(
    url: &str,
    doc_path: Option<&Path>,
    remote_policy: RemoteImagePolicy,
    session_allow_remote: bool,
    max_cells: Option<(u16, u16)>,
    font_size: Option<(u16, u16)>,
) -> Result<LoadedImage, ImageLoadError> {
    let image = if is_remote(url) {
        let allow = matches!(remote_policy, RemoteImagePolicy::Always) || session_allow_remote;
        if !allow {
            return Err(ImageLoadError::RemoteBlocked(url.to_owned()));
        }
        let bytes = fetch_remote(url)?;
        decode_any(url, &bytes, max_cells, font_size)?
    } else {
        let path = resolve_local_path(url, doc_path)?;
        let meta = std::fs::metadata(&path).map_err(|source| ImageLoadError::Io {
            path: path.clone(),
            source,
        })?;
        if meta.len() > MAX_LOCAL_IMAGE_BYTES {
            return Err(ImageLoadError::Io {
                path: path.clone(),
                source: std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "image file too large: {} bytes (max {MAX_LOCAL_IMAGE_BYTES})",
                        meta.len()
                    ),
                ),
            });
        }
        let bytes = std::fs::read(&path).map_err(|source| ImageLoadError::Io {
            path: path.clone(),
            source,
        })?;
        decode_any(url, &bytes, max_cells, font_size)?
    };

    let image = match (max_cells, font_size) {
        (Some(cells), Some(font)) => pre_resize(image, cells, font),
        _ => image,
    };

    Ok(LoadedImage {
        url: url.to_owned(),
        image,
        scratch: None,
    })
}

/// Downscale `image` to fit within `max_cells × font_size` pixels while
/// preserving aspect ratio.  Returns the original image unmodified when
/// it already fits, so small images don't pay the resize cost.
fn pre_resize(image: DynamicImage, max_cells: (u16, u16), font_size: (u16, u16)) -> DynamicImage {
    let max_w_px = u32::from(max_cells.0) * u32::from(font_size.0);
    let max_h_px = u32::from(max_cells.1) * u32::from(font_size.1);
    if max_w_px == 0 || max_h_px == 0 {
        return image;
    }
    if image.width() <= max_w_px && image.height() <= max_h_px {
        return image;
    }
    // `Triangle` (bilinear) is ~3–5× faster than `Lanczos3` and
    // visually indistinguishable at thumbnail sizes.  The image is
    // subsequently re-encoded by `ratatui-image`'s protocol layer
    // (halfblocks averages 2 pixels per cell, native graphics just
    // transmits the pre-scaled pixels), so the extra Lanczos quality
    // would never reach the terminal anyway.
    image.resize(max_w_px, max_h_px, image::imageops::FilterType::Triangle)
}

/// True when `url` is an `http://` or `https://` URL.  Other schemes
/// (`data:`, `file:`, `ftp:`, …) are not considered remote: `file:` is
/// handled as a local path, everything else is rejected in
/// [`resolve_local_path`].
pub fn is_remote(url: &str) -> bool {
    let lower = url.to_ascii_lowercase();
    lower.starts_with("http://") || lower.starts_with("https://")
}

fn resolve_local_path(url: &str, doc_path: Option<&Path>) -> Result<PathBuf, ImageLoadError> {
    // Accept `file:///abs/path` and bare paths.  Reject any other scheme.
    if let Some(stripped) = url.strip_prefix("file://") {
        return Ok(PathBuf::from(stripped));
    }
    if let Some((scheme, _)) = url.split_once(':') {
        // A bare Windows path ("C:/…") has a single-char scheme — treat
        // any single-char prefix as not-a-scheme so we don't reject those.
        let looks_like_scheme = scheme.len() > 1
            && scheme
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
        if looks_like_scheme {
            return Err(ImageLoadError::UnsupportedScheme(url.to_owned()));
        }
    }
    let candidate = PathBuf::from(url);
    if candidate.is_absolute() {
        return Ok(candidate);
    }
    match doc_path.and_then(|p| p.parent()) {
        Some(parent) => Ok(parent.join(candidate)),
        None => Ok(candidate),
    }
}

fn fetch_remote(url: &str) -> Result<Vec<u8>, ImageLoadError> {
    // ureq 3 replaced `AgentBuilder` with a typed config builder
    // (`Config` → `Agent` via `Into`) and split the single read timeout
    // into receive-response / receive-body phases.  We bound the connect
    // and both receive phases at `REMOTE_TIMEOUT` so a slow server can't
    // hang the decode worker.
    let config = ureq::Agent::config_builder()
        .timeout_connect(Some(REMOTE_TIMEOUT))
        .timeout_recv_response(Some(REMOTE_TIMEOUT))
        .timeout_recv_body(Some(REMOTE_TIMEOUT))
        .build();
    // Build the agent with a resolver that refuses internal IP ranges so a
    // remote image can't be used to probe loopback / LAN / cloud-metadata
    // endpoints (SSRF).  See `PublicOnlyResolver`.
    let agent = ureq::Agent::with_parts(
        config,
        ureq::unversioned::transport::DefaultConnector::default(),
        PublicOnlyResolver::default(),
    );
    let mut response = agent
        .get(url)
        .call()
        .map_err(|source| ImageLoadError::Http {
            url: url.to_owned(),
            source: Box::new(source),
        })?;
    // ureq 3 reads the body off the response itself; `read_to_vec`
    // surfaces transport errors as `ureq::Error`, so they route through
    // the same `Http` variant as the request failure above.
    response
        .body_mut()
        .read_to_vec()
        .map_err(|source| ImageLoadError::Http {
            url: url.to_owned(),
            source: Box::new(source),
        })
}

// ── SSRF guard ──────────────────────────────────────────────────────────────

/// A name resolver that drops any address in an internal range, wrapping
/// ureq's `DefaultResolver`.  Once the user allows remote images for a
/// document, *every* `http(s)` URL in it is fetched — so without this a
/// benign-looking URL (or a `3xx` redirect from one) could reach
/// `127.0.0.1`, a LAN host, or the `169.254.169.254` cloud-metadata
/// endpoint.  Filtering on the *resolved* IP rather than the hostname
/// defeats literal-IP URLs, DNS names pointed at private space (DNS
/// rebinding), and every redirect hop uniformly, because ureq re-resolves
/// each hop through this resolver.
#[derive(Debug, Default)]
struct PublicOnlyResolver {
    inner: ureq::unversioned::resolver::DefaultResolver,
}

impl ureq::unversioned::resolver::Resolver for PublicOnlyResolver {
    fn resolve(
        &self,
        uri: &ureq::http::Uri,
        config: &ureq::config::Config,
        timeout: ureq::unversioned::transport::NextTimeout,
    ) -> Result<ureq::unversioned::resolver::ResolvedSocketAddrs, ureq::Error> {
        let resolved = self.inner.resolve(uri, config, timeout)?;
        let mut allowed = self.empty();
        for addr in &resolved {
            if !is_blocked_ip(addr.ip()) {
                allowed.push(*addr);
            }
        }
        if allowed.is_empty() {
            // Every candidate address was internal — treat the host as
            // unresolvable rather than connecting to it.
            return Err(ureq::Error::HostNotFound);
        }
        Ok(allowed)
    }
}

/// True for any IP edamame must not connect to when fetching a remote
/// image: loopback, RFC1918 private, link-local (incl. the
/// `169.254.169.254` cloud-metadata address), carrier-grade NAT,
/// unique-local / link-local IPv6, and the unspecified / broadcast /
/// documentation ranges.  IPv4-mapped IPv6 addresses are unwrapped and
/// re-checked so `::ffff:127.0.0.1` can't slip past.
fn is_blocked_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(v4) => {
            v4.is_loopback()
                || v4.is_private()
                || v4.is_link_local()
                || v4.is_unspecified()
                || v4.is_broadcast()
                || v4.is_documentation()
                || v4.octets()[0] == 0
                // 100.64.0.0/10 — carrier-grade NAT
                || (v4.octets()[0] == 100 && (v4.octets()[1] & 0xc0) == 64)
        }
        IpAddr::V6(v6) => {
            if let Some(mapped) = v6.to_ipv4_mapped() {
                return is_blocked_ip(IpAddr::V4(mapped));
            }
            let seg0 = v6.segments()[0];
            v6.is_loopback()
                || v6.is_unspecified()
                || v6.is_multicast()
                || (seg0 & 0xfe00) == 0xfc00 // fc00::/7  unique-local
                || (seg0 & 0xffc0) == 0xfe80 // fe80::/10 link-local
        }
    }
}

/// True when `url`'s path ends in `.svg` (case-insensitive), ignoring any
/// `?query` / `#fragment` suffix on a remote URL.  Detection is by
/// extension only: a remote URL that serves SVG without a `.svg` path
/// (e.g. `?format=svg`) falls through to the raster decoder and fails
/// like any non-image — that is the documented trade-off.
fn is_svg_url(url: &str) -> bool {
    let path = url.split(['?', '#']).next().unwrap_or(url);
    path.to_ascii_lowercase().ends_with(".svg")
}

/// Decode `bytes` into a `DynamicImage`, picking the SVG rasterizer for
/// `.svg` URLs and the raster (`image` crate) decoder otherwise.
fn decode_any(
    url: &str,
    bytes: &[u8],
    max_cells: Option<(u16, u16)>,
    font_size: Option<(u16, u16)>,
) -> Result<DynamicImage, ImageLoadError> {
    if is_svg_url(url) {
        decode_svg(url, bytes, max_cells, font_size)
    } else {
        decode(url, bytes)
    }
}

/// Decode raster `bytes` into a `DynamicImage` through `image::ImageReader`
/// with [`image::Limits`] in force, so a compression bomb is rejected with
/// a `Decode` error rather than driving an OOM that `catch_unwind` cannot
/// contain.  Replaces the unbounded `image::load_from_memory`.
fn decode(url: &str, bytes: &[u8]) -> Result<DynamicImage, ImageLoadError> {
    let mut limits = image::Limits::no_limits();
    limits.max_image_width = Some(MAX_DECODE_DIMENSION);
    limits.max_image_height = Some(MAX_DECODE_DIMENSION);
    limits.max_alloc = Some(MAX_DECODE_ALLOC);

    let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
        .with_guessed_format()
        .map_err(|e| ImageLoadError::Decode {
            url: url.to_owned(),
            source: image::ImageError::IoError(e),
        })?;
    reader.limits(limits);
    reader.decode().map_err(|source| ImageLoadError::Decode {
        url: url.to_owned(),
        source,
    })
}

/// Rasterize SVG `bytes` to a `DynamicImage`.  Unlike a diagram, a user's
/// SVG file has a meaningful natural size, so it is only downscaled to
/// fit the envelope (`SvgSizing::Natural`) — `Resize::Fit` then displays
/// it 1:1, crisp at natural size — and its transparency is preserved
/// (no background fill) to composite over the document like a
/// transparent PNG.  The subsequent `pre_resize` is a no-op here because
/// the rasterizer has already capped the pixel size at the envelope.
///
/// Only UTF-8 SVG bytes are accepted; a UTF-16-encoded or BOM-prefixed
/// file is reported as an `Svg` parse error rather than silently failing
/// elsewhere.  Both are rare for hand- and tool-authored SVGs.
fn decode_svg(
    url: &str,
    bytes: &[u8],
    max_cells: Option<(u16, u16)>,
    font_size: Option<(u16, u16)>,
) -> Result<DynamicImage, ImageLoadError> {
    let svg = std::str::from_utf8(bytes).map_err(|e| ImageLoadError::Svg {
        url: url.to_owned(),
        source: SvgError::Parse(format!("invalid UTF-8: {e}")),
    })?;
    rasterize_svg(
        svg,
        SvgSizing {
            envelope: max_cells,
            font_size,
            mode: SvgScaleMode::Natural,
        },
        None,
    )
    .map_err(|source| ImageLoadError::Svg {
        url: url.to_owned(),
        source,
    })
}

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

    /// Generate a tiny valid PNG in-memory using the `image` crate so the
    /// test doesn't depend on a hand-crafted byte string (which is easy
    /// to get wrong — CRCs, IDAT compression, etc.).
    fn tiny_png() -> Vec<u8> {
        use image::{ImageBuffer, Rgba};
        let img: ImageBuffer<Rgba<u8>, Vec<u8>> =
            ImageBuffer::from_pixel(2, 2, Rgba([10, 20, 30, 255]));
        let mut out = std::io::Cursor::new(Vec::new());
        image::DynamicImage::ImageRgba8(img)
            .write_to(&mut out, image::ImageFormat::Png)
            .expect("encode png");
        out.into_inner()
    }

    /// A minimal valid SVG with explicit dimensions.
    fn tiny_svg() -> &'static [u8] {
        br##"<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
  <rect width="24" height="24" fill="#3498db"/>
</svg>"##
    }

    #[test]
    fn is_svg_url_matches_extension_ignoring_query() {
        assert!(is_svg_url("icon.svg"));
        assert!(is_svg_url("./art/Logo.SVG"));
        assert!(is_svg_url("/abs/diagram.svg"));
        assert!(is_svg_url("https://img.shields.io/badge/x.svg?style=flat"));
        assert!(is_svg_url("https://example.com/a.svg#frag"));
        assert!(!is_svg_url("photo.png"));
        assert!(!is_svg_url("https://example.com/render?format=svg"));
    }

    #[test]
    fn local_svg_file_rasterizes_at_natural_size() {
        let mut file = tempfile::Builder::new()
            .suffix(".svg")
            .tempfile()
            .expect("tempfile");
        std::io::Write::write_all(&mut file, tiny_svg()).expect("write svg");
        let path = file.path().to_str().unwrap().to_owned();

        // Natural 24×24 fits the 80×24-cell envelope, so it stays 24×24.
        let loaded = resolve(
            &path,
            None,
            RemoteImagePolicy::Never,
            false,
            Some((80, 24)),
            Some((8, 16)),
        )
        .expect("load svg");
        assert_eq!(loaded.image.width(), 24);
        assert_eq!(loaded.image.height(), 24);
    }

    #[test]
    fn invalid_svg_file_reports_svg_error() {
        let mut file = tempfile::Builder::new()
            .suffix(".svg")
            .tempfile()
            .expect("tempfile");
        std::io::Write::write_all(&mut file, b"this is not svg").expect("write");
        let path = file.path().to_str().unwrap().to_owned();

        let err = resolve(&path, None, RemoteImagePolicy::Never, false, None, None).unwrap_err();
        assert!(matches!(err, ImageLoadError::Svg { .. }));
    }

    #[test]
    fn ssrf_filter_blocks_internal_ranges() {
        use std::net::{Ipv4Addr, Ipv6Addr};
        let blocked: [IpAddr; 10] = [
            IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
            IpAddr::V4(Ipv4Addr::new(10, 0, 0, 5)),
            IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)),
            IpAddr::V4(Ipv4Addr::new(172, 16, 0, 1)),
            IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254)), // cloud metadata
            IpAddr::V4(Ipv4Addr::new(100, 64, 0, 1)),      // CGNAT
            IpAddr::V4(Ipv4Addr::UNSPECIFIED),
            IpAddr::V6(Ipv6Addr::LOCALHOST),
            IpAddr::V6("fc00::1".parse().unwrap()),
            IpAddr::V6("fe80::1".parse().unwrap()),
        ];
        for ip in blocked {
            assert!(is_blocked_ip(ip), "{ip} must be blocked");
        }

        let allowed: [IpAddr; 4] = [
            IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
            IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)),
            IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)), // example.com
            IpAddr::V6("2606:4700:4700::1111".parse().unwrap()),
        ];
        for ip in allowed {
            assert!(!is_blocked_ip(ip), "{ip} must be allowed");
        }

        // IPv4-mapped loopback must not slip past the v6 arm.
        assert!(is_blocked_ip(IpAddr::V6(
            "::ffff:127.0.0.1".parse().unwrap()
        )));
    }

    #[test]
    fn is_remote_matches_http_schemes() {
        assert!(is_remote("http://example.com/a.png"));
        assert!(is_remote("HTTPS://Example.COM/a.png"));
        assert!(!is_remote("./img/a.png"));
        assert!(!is_remote("/abs/a.png"));
        assert!(!is_remote("file:///tmp/a.png"));
    }

    #[test]
    fn remote_never_policy_blocks_even_with_session_flag_cleared() {
        let err = resolve(
            "https://example.com/a.png",
            None,
            RemoteImagePolicy::Never,
            false,
            None,
            None,
        )
        .unwrap_err();
        assert!(matches!(err, ImageLoadError::RemoteBlocked(_)));
    }

    #[test]
    fn remote_ask_policy_blocks_without_session_flag() {
        let err = resolve(
            "https://example.com/a.png",
            None,
            RemoteImagePolicy::Ask,
            false,
            None,
            None,
        )
        .unwrap_err();
        assert!(matches!(err, ImageLoadError::RemoteBlocked(_)));
    }

    #[test]
    fn local_absolute_path_is_used_verbatim() {
        let mut file = tempfile::NamedTempFile::new().expect("tempfile");
        let bytes = tiny_png();
        std::io::Write::write_all(&mut file, &bytes).expect("write png");
        let path = file.path().to_str().unwrap().to_owned();

        let loaded =
            resolve(&path, None, RemoteImagePolicy::Never, false, None, None).expect("load");
        assert_eq!(loaded.url, path);
        assert_eq!(loaded.image.width(), 2);
        assert_eq!(loaded.image.height(), 2);
    }

    #[test]
    fn local_relative_path_resolves_from_doc_parent() {
        let dir = tempfile::tempdir().expect("tempdir");
        let img = dir.path().join("pic.png");
        std::fs::write(&img, tiny_png()).expect("write png");
        let doc = dir.path().join("doc.md");

        let loaded = resolve(
            "pic.png",
            Some(&doc),
            RemoteImagePolicy::Never,
            false,
            None,
            None,
        )
        .expect("load relative");
        assert_eq!(loaded.image.width(), 2);
    }

    #[test]
    fn file_scheme_is_treated_as_local_path() {
        let mut file = tempfile::NamedTempFile::new().expect("tempfile");
        let bytes = tiny_png();
        std::io::Write::write_all(&mut file, &bytes).expect("write png");
        let url = format!("file://{}", file.path().display());
        let loaded =
            resolve(&url, None, RemoteImagePolicy::Never, false, None, None).expect("load");
        assert_eq!(loaded.image.width(), 2);
    }

    #[test]
    fn unsupported_scheme_is_rejected() {
        let err = resolve(
            "ftp://example.com/a.png",
            None,
            RemoteImagePolicy::Always,
            false,
            None,
            None,
        )
        .unwrap_err();
        assert!(matches!(err, ImageLoadError::UnsupportedScheme(_)));
    }

    #[test]
    fn missing_local_file_reports_io_error() {
        let err = resolve(
            "/definitely/not/a/real/path/image.png",
            None,
            RemoteImagePolicy::Never,
            false,
            None,
            None,
        )
        .unwrap_err();
        assert!(matches!(err, ImageLoadError::Io { .. }));
    }

    #[test]
    fn pre_resize_downscales_oversized_images() {
        // 40×40 pixels > 20×10 cells × 2×2 font = 40×20 pixels? hmm
        // Use big-enough numbers to ensure the image is downscaled.
        let big = DynamicImage::new_rgba8(500, 500);
        let resized = pre_resize(big, (20, 10), (10, 20));
        // max_w_px = 200, max_h_px = 200 → fit preserves aspect, so
        // 500×500 → 200×200.
        assert!(resized.width() <= 200);
        assert!(resized.height() <= 200);
    }

    #[test]
    fn pre_resize_leaves_small_images_unchanged() {
        let small = DynamicImage::new_rgba8(50, 50);
        let (before_w, before_h) = (small.width(), small.height());
        let resized = pre_resize(small, (20, 10), (10, 20));
        assert_eq!(resized.width(), before_w);
        assert_eq!(resized.height(), before_h);
    }
}