iced_webview_v2 0.1.11

An easily embedded webview library for iced
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
use std::cell::RefCell;
use std::collections::HashMap;

use iced::keyboard;
use iced::mouse::{self, Interaction};
use iced::{Point, Size};
use url::Url;

use super::{Engine, PageType, PixelFormat, ViewId, ViewManager};
use crate::ImageInfo;

use litehtml::pixbuf::PixbufContainer;
use litehtml::selection::Selection;
use litehtml::{
    css_escape_ident, BackgroundLayer, BorderRadiuses, Borders, Color, ConicGradient, Document,
    DocumentContainer, DrawContext, FontDescription, FontHandle, FontMetrics, LinearGradient,
    ListMarker, MediaFeatures, Position, RadialGradient, TextTransform,
};

/// Wrapper around `PixbufContainer` that handles CSS import resolution
/// and image baseurl tracking, mirroring litehtml-rs's `BrowseContainer`.
struct WebviewContainer {
    inner: PixbufContainer,
    base_url: String,
    css_cache: RefCell<HashMap<String, String>>,
    /// Maps raw image src → baseurl passed by litehtml, so image fetches
    /// can resolve relative URLs against the correct context (stylesheet
    /// URL, not the page URL).
    image_baseurls: RefCell<HashMap<String, String>>,
}

impl WebviewContainer {
    fn new(width: u32, height: u32, scale: f32) -> Self {
        Self {
            inner: PixbufContainer::new_with_scale(width, height, scale),
            base_url: String::new(),
            css_cache: RefCell::new(HashMap::new()),
            image_baseurls: RefCell::new(HashMap::new()),
        }
    }

    fn inner(&self) -> &PixbufContainer {
        &self.inner
    }

    fn inner_mut(&mut self) -> &mut PixbufContainer {
        &mut self.inner
    }

    fn set_css_cache(&self, cache: HashMap<String, String>) {
        *self.css_cache.borrow_mut() = cache;
    }

    /// Resolve a URL against a given base, falling back to self.base_url.
    fn resolve_against(&self, href: &str, baseurl: &str) -> Option<Url> {
        // Already absolute
        if let Ok(u) = Url::parse(href) {
            return Some(u);
        }
        // Resolve against the provided base context (e.g. stylesheet URL)
        if !baseurl.is_empty() {
            if let Ok(base) = Url::parse(baseurl) {
                if let Ok(u) = base.join(href) {
                    return Some(u);
                }
            }
        }
        // Fall back to page base URL
        if !self.base_url.is_empty() {
            if let Ok(base) = Url::parse(&self.base_url) {
                return base.join(href).ok();
            }
        }
        None
    }
}

// Delegate everything to inner, override import_css, set_base_url, load_image
impl DocumentContainer for WebviewContainer {
    fn create_font(&mut self, descr: &FontDescription) -> (FontHandle, FontMetrics) {
        self.inner.create_font(descr)
    }
    fn delete_font(&mut self, font: FontHandle) {
        self.inner.delete_font(font);
    }
    fn text_width(&self, text: &str, font: FontHandle) -> f32 {
        self.inner.text_width(text, font)
    }
    fn draw_text(
        &mut self,
        hdc: DrawContext,
        text: &str,
        font: FontHandle,
        color: Color,
        pos: Position,
    ) {
        self.inner.draw_text(hdc, text, font, color, pos);
    }
    fn draw_list_marker(&mut self, hdc: DrawContext, marker: &ListMarker) {
        self.inner.draw_list_marker(hdc, marker);
    }
    fn load_image(&mut self, src: &str, baseurl: &str, redraw_on_ready: bool) {
        // Store the baseurl context so image fetches can resolve correctly
        if !baseurl.is_empty() {
            self.image_baseurls
                .borrow_mut()
                .insert(src.to_string(), baseurl.to_string());
        }
        self.inner.load_image(src, baseurl, redraw_on_ready);
    }
    fn get_image_size(&self, src: &str, baseurl: &str) -> litehtml::Size {
        self.inner.get_image_size(src, baseurl)
    }
    fn draw_image(&mut self, hdc: DrawContext, layer: &BackgroundLayer, url: &str, base_url: &str) {
        self.inner.draw_image(hdc, layer, url, base_url);
    }
    fn draw_solid_fill(&mut self, hdc: DrawContext, layer: &BackgroundLayer, color: Color) {
        self.inner.draw_solid_fill(hdc, layer, color);
    }
    fn draw_linear_gradient(
        &mut self,
        hdc: DrawContext,
        layer: &BackgroundLayer,
        gradient: &LinearGradient,
    ) {
        self.inner.draw_linear_gradient(hdc, layer, gradient);
    }
    fn draw_radial_gradient(
        &mut self,
        hdc: DrawContext,
        layer: &BackgroundLayer,
        gradient: &RadialGradient,
    ) {
        self.inner.draw_radial_gradient(hdc, layer, gradient);
    }
    fn draw_conic_gradient(
        &mut self,
        hdc: DrawContext,
        layer: &BackgroundLayer,
        gradient: &ConicGradient,
    ) {
        self.inner.draw_conic_gradient(hdc, layer, gradient);
    }
    fn draw_borders(
        &mut self,
        hdc: DrawContext,
        borders: &Borders,
        draw_pos: Position,
        root: bool,
    ) {
        self.inner.draw_borders(hdc, borders, draw_pos, root);
    }
    fn set_caption(&mut self, caption: &str) {
        self.inner.set_caption(caption);
    }
    fn set_base_url(&mut self, base_url: &str) {
        // Update our stored base URL for resolve_against fallback
        self.base_url = base_url.to_string();
        self.inner.set_base_url(base_url);
    }
    fn on_anchor_click(&mut self, url: &str) {
        self.inner.on_anchor_click(url);
    }
    fn set_cursor(&mut self, cursor: &str) {
        self.inner.set_cursor(cursor);
    }
    fn transform_text(&self, text: &str, tt: TextTransform) -> String {
        self.inner.transform_text(text, tt)
    }
    fn import_css(&self, url: &str, baseurl: &str) -> (String, Option<String>) {
        // Resolve against the baseurl parameter (stylesheet context)
        let resolved = match self.resolve_against(url, baseurl) {
            Some(u) => u,
            None => return (String::new(), None),
        };
        let key = resolved.to_string();
        if let Some(cached) = self.css_cache.borrow().get(&key) {
            return (cached.clone(), Some(key));
        }
        // Not in cache — return empty (the CSS wasn't pre-fetched)
        (String::new(), None)
    }
    fn set_clip(&mut self, pos: Position, radius: BorderRadiuses) {
        self.inner.set_clip(pos, radius);
    }
    fn del_clip(&mut self) {
        self.inner.del_clip();
    }
    fn get_viewport(&self) -> Position {
        self.inner.get_viewport()
    }
    fn get_media_features(&self) -> MediaFeatures {
        self.inner.get_media_features()
    }
}

/// Persistent document and selection state for a view.
///
/// # Safety
///
/// The `doc` field borrows from the `Box<WebviewContainer>` in the parent
/// `LitehtmlView`. The container is heap-allocated for address stability.
/// `doc_state` is declared before `container` in `LitehtmlView` for correct
/// drop order — it must be dropped first.
///
/// To avoid aliasing UB, `doc_state` is temporarily taken out (`Option::take`)
/// whenever the container is accessed directly. This ensures only one `&mut`
/// to the container data exists at a time.
type MeasureFn = Box<dyn Fn(&str, FontHandle) -> f32>;

struct DocumentState {
    doc: Document<'static>,
    measure: MeasureFn,
    selection: Selection<'static>,
}

struct LitehtmlView {
    // IMPORTANT: doc_state must be declared before container so it drops first.
    doc_state: Option<DocumentState>,
    container: Box<WebviewContainer>,
    html: String,
    url: String,
    title: String,
    cursor: Interaction,
    last_frame: ImageInfo,
    needs_render: bool,
    /// Fetched image bytes waiting to be flushed into the container.
    /// Accumulated between render cycles so multiple images cause only
    /// one document rebuild instead of one per image.
    staged_images: Vec<(String, Vec<u8>, bool)>,
    /// Selection highlight rects in logical coords, scroll-adjusted.
    /// Drawn as iced quads by the widget so the base image Handle stays stable.
    selection_rects: Vec<[f32; 4]>,
    scroll_y: f32,
    content_height: f32,
    size: Size<u32>,
    drag_origin: Option<(f32, f32)>,
    drag_active: bool,
}

/// CPU-based HTML rendering engine backed by litehtml.
///
/// No URL navigation, no keyboard input, no JavaScript.
/// Uses `litehtml::pixbuf::PixbufContainer` for software rasterization.
pub struct Litehtml {
    views: ViewManager<LitehtmlView>,
    scale_factor: f32,
}

impl Default for Litehtml {
    fn default() -> Self {
        Self {
            views: ViewManager::default(),
            scale_factor: 1.0,
        }
    }
}

/// Build a persistent Document for the view, storing it alongside its
/// text-measurement closure and a fresh Selection.
///
/// Drops any existing document state first (releasing the container borrow),
/// then resizes the container, creates a new Document, and renders the layout.
fn rebuild_document(view: &mut LitehtmlView) {
    view.doc_state = None;

    // Flush any staged images while doc_state is None (safe — no Document
    // holds a borrow of the container).
    if !view.staged_images.is_empty() {
        for (url, bytes, _) in view.staged_images.drain(..) {
            view.container.inner_mut().load_image_data(&url, &bytes);
        }
    }

    let w = view.size.width;
    let h = view.size.height;

    if w == 0 || h == 0 || view.html.is_empty() {
        return;
    }

    // Pass 1: use a tall viewport so CSS `100vh` doesn't cap content height.
    let layout_h = h.max(10_000);
    view.container.inner_mut().resize(w, layout_h);

    // Capture the text measurement closure before borrowing the container
    let measure = view.container.inner().text_measure_fn();

    // SAFETY: Manual lifetime extension is required here due to litehtml API constraints.
    //
    // The litehtml Document<'a> type is invariant over its lifetime parameter and
    // requires a mutable borrow of the container. This makes it incompatible with
    // self-referential struct crates like ouroboros or self_cell, which cannot handle:
    //   1. Lifetime invariance (they require covariance)
    //   2. Multiple mutable borrows from the same field (Document and Selection)
    //
    // The unsafe lifetime extension to 'static is safe because:
    //   1. container is Box<WebviewContainer> — heap-allocated with a stable address
    //   2. doc_state is declared before container in LitehtmlView → drops first
    //   3. doc_state is set to None before any container modification or drop
    //   4. The Document never outlives the container it borrows from
    //
    // This pattern has been carefully reviewed and is the standard approach for
    // self-referential structures when safe abstractions are incompatible.
    let container_ptr = &mut *view.container as *mut WebviewContainer;
    let container_ref: &'static mut WebviewContainer = unsafe { &mut *container_ptr };

    match Document::from_html(&view.html, container_ref, None, None) {
        Err(e) => {
            eprintln!("litehtml: from_html failed: {e:?}");
        }
        Ok(mut doc) => {
            let _ = doc.render(w as f32);
            let measured = doc.height();

            // Pass 2: if content overflows the layout viewport, re-layout so
            // `100vh` covers the full content and overflow clips don't cut it off.
            if measured > layout_h as f32 {
                let final_h = measured.ceil() as u32;

                // Drop the document BEFORE resizing. Calling resize while doc
                // holds a &mut borrow of the container would create two live
                // &mut references — undefined behavior.
                drop(doc);

                view.container.inner_mut().resize(w, final_h);
                let measure2 = view.container.inner().text_measure_fn();

                let container_ptr2 = &mut *view.container as *mut WebviewContainer;
                let container_ref2: &'static mut WebviewContainer = unsafe { &mut *container_ptr2 };

                match Document::from_html(&view.html, container_ref2, None, None) {
                    Err(e) => {
                        eprintln!("litehtml: from_html pass 2 failed: {e:?}");
                    }
                    Ok(mut doc2) => {
                        let _ = doc2.render(w as f32);
                        view.content_height = doc2.height();

                        let selection: Selection<'static> = Selection::new();
                        view.doc_state = Some(DocumentState {
                            doc: doc2,
                            measure: Box::new(measure2),
                            selection,
                        });
                    }
                }
            } else {
                view.content_height = measured;

                let selection: Selection<'static> = Selection::new();
                view.doc_state = Some(DocumentState {
                    doc,
                    measure: Box::new(measure),
                    selection,
                });
            }
        }
    }
}

/// Draw the document into the pixel buffer and capture `last_frame`.
///
/// Resizes the container to fit the full content height, disables CSS
/// overflow clips, draws, then captures the pixels.
///
/// To avoid aliasing UB, the document is temporarily taken out of
/// `doc_state` while the container is mutated (resize, clip flags),
/// then restored for the `draw` call, and taken out again for cleanup.
fn capture_frame(view: &mut LitehtmlView) {
    let w = view.size.width;
    let full_h = (view.content_height.ceil() as u32).max(1);

    // Take doc_state out so we can safely mutate the container.
    let doc_state = view.doc_state.take();

    view.container.inner_mut().resize(w, full_h);
    view.container.inner_mut().set_ignore_overflow_clips(true);

    // Restore doc_state and draw.
    view.doc_state = doc_state;
    if let Some(ref mut ds) = view.doc_state {
        let clip = Position {
            x: 0.0,
            y: 0.0,
            width: w as f32,
            height: full_h as f32,
        };
        ds.doc.draw(DrawContext(0), 0.0, 0.0, Some(clip));
    }

    // Take doc_state out again to safely access the container.
    let doc_state = view.doc_state.take();
    view.container.inner_mut().set_ignore_overflow_clips(false);

    let phys_w = view.container.inner().width();
    let phys_h = view.container.inner().height();
    let pixels = unpremultiply_rgba(view.container.inner().pixels());
    view.last_frame = ImageInfo::new(pixels, PixelFormat::Rgba, phys_w, phys_h);
    view.needs_render = false;

    view.doc_state = doc_state;
}

/// Render the full document into the pixel buffer and update `last_frame`.
///
/// The buffer covers the entire content height so the widget can scroll
/// by offsetting the draw position — no re-render needed per scroll.
fn draw_view(view: &mut LitehtmlView) {
    capture_frame(view);
}

/// Flush staged image bytes into the container and redraw.
///
/// Drops the document first to release its borrow on the container, loads
/// the image data safely, then rebuilds the document from the stored HTML.
/// This avoids all mutable aliasing — the previous approach used raw
/// pointers to mutate the container while the Document held a `&mut` borrow,
/// which was undefined behavior under Rust's aliasing rules.
///
/// The rebuild cost is acceptable: `Document::from_html` + `render` is fast
/// for typical HTML, and this path only runs when async image fetches complete.
fn flush_images_and_redraw(view: &mut LitehtmlView) {
    if view.staged_images.is_empty() {
        return;
    }

    let w = view.size.width;
    if w == 0 || view.size.height == 0 {
        return;
    }

    // Drop the document to release its borrow on the container.
    view.doc_state = None;

    // Now safe to mutate the container — no Document holds a borrow.
    for (url, bytes, _) in view.staged_images.drain(..) {
        view.container.inner_mut().load_image_data(&url, &bytes);
    }

    // Rebuild the document from stored HTML (includes render + draw).
    rebuild_document(view);
    capture_frame(view);
}

/// Main render entry point: rebuilds the document if needed, then draws.
fn render_view(view: &mut LitehtmlView) {
    let w = view.size.width;
    let h = view.size.height;

    if w == 0 || h == 0 {
        return;
    }

    if view.html.is_empty() {
        let phys_w = view.container.inner().width();
        let phys_h = view.container.inner().height();
        view.last_frame = ImageInfo::blank(phys_w, phys_h);
        view.needs_render = false;
        return;
    }

    if view.doc_state.is_none() {
        rebuild_document(view);
        draw_view(view);
    } else if !view.staged_images.is_empty() {
        // Document exists — inject images, re-layout, and draw in one
        // pass so the container size stays consistent throughout.
        flush_images_and_redraw(view);
    } else {
        draw_view(view);
    }
}

/// Convert premultiplied-alpha RGBA pixels to straight alpha.
///
/// litehtml's pixbuf backend (tiny-skia) stores premultiplied RGBA, but
/// iced's `image::Handle::from_rgba` expects straight (unpremultiplied) alpha.
fn unpremultiply_rgba(pixels: &[u8]) -> Vec<u8> {
    let mut result = Vec::with_capacity(pixels.len());
    for chunk in pixels.chunks_exact(4) {
        let a = chunk[3] as u32;
        if a == 0 {
            result.extend_from_slice(&[0, 0, 0, 0]);
        } else {
            let r = ((chunk[0] as u32 * 255 + a / 2) / a).min(255) as u8;
            let g = ((chunk[1] as u32 * 255 + a / 2) / a).min(255) as u8;
            let b = ((chunk[2] as u32 * 255 + a / 2) / a).min(255) as u8;
            result.extend_from_slice(&[r, g, b, chunk[3]]);
        }
    }
    result
}

/// Map a CSS cursor value from litehtml to an iced mouse interaction.
fn css_cursor_to_interaction(cursor: &str) -> Interaction {
    match cursor {
        "pointer" => Interaction::Pointer,
        "text" => Interaction::Text,
        "crosshair" => Interaction::Crosshair,
        "grab" => Interaction::Grab,
        "grabbing" => Interaction::Grabbing,
        "not-allowed" | "no-drop" => Interaction::NotAllowed,
        "col-resize" | "ew-resize" => Interaction::ResizingHorizontally,
        "row-resize" | "ns-resize" => Interaction::ResizingVertically,
        _ => Interaction::Idle,
    }
}

/// Store selection rectangles in document coordinates.
/// The widget layer applies the scroll offset when drawing.
fn update_selection_rects(view: &mut LitehtmlView) {
    view.selection_rects.clear();
    if let Some(ref state) = view.doc_state {
        for r in state.selection.rectangles() {
            view.selection_rects.push([r.x, r.y, r.width, r.height]);
        }
    }
}

impl Engine for Litehtml {
    fn handles_urls(&self) -> bool {
        false
    }

    fn update(&mut self) {
        // No-op: litehtml has no async work or background tasks.
    }

    fn render(&mut self, _size: Size<u32>) {
        for view in self.views.values_mut() {
            if view.needs_render {
                render_view(view);
            }
        }
    }

    fn request_render(&mut self, id: ViewId, _size: Size<u32>) {
        let Some(view) = self.views.get_mut(id) else {
            return;
        };
        if view.needs_render {
            render_view(view);
        }
    }

    fn flush_staged_images(&mut self, id: ViewId, _size: Size<u32>) {
        let Some(view) = self.views.get_mut(id) else {
            return;
        };
        if !view.staged_images.is_empty() {
            render_view(view);
        }
    }

    fn new_view(&mut self, size: Size<u32>, content: Option<PageType>) -> ViewId {
        let w = size.width.max(1);
        let h = size.height.max(1);

        let html = match &content {
            Some(PageType::Html(html)) => html.clone(),
            _ => String::new(),
        };
        let url = match &content {
            Some(PageType::Url(url)) => url.clone(),
            _ => String::new(),
        };

        let mut view = LitehtmlView {
            doc_state: None,
            container: Box::new(WebviewContainer::new(w, h, self.scale_factor)),
            html,
            url,
            title: String::new(),
            cursor: Interaction::Idle,
            last_frame: ImageInfo::blank(w, h),
            needs_render: true,
            staged_images: Vec::new(),
            selection_rects: Vec::new(),
            scroll_y: 0.0,
            content_height: 0.0,
            size,
            drag_origin: None,
            drag_active: false,
        };

        render_view(&mut view);
        self.views.insert(view)
    }

    fn remove_view(&mut self, id: ViewId) {
        self.views.remove(id);
    }

    fn has_view(&self, id: ViewId) -> bool {
        self.views.contains(id)
    }

    fn view_ids(&self) -> Vec<ViewId> {
        self.views.keys()
    }

    fn focus(&mut self) {
        // No-op: litehtml has no focus model.
    }

    fn unfocus(&self) {
        // No-op: litehtml has no focus model.
    }

    fn resize(&mut self, size: Size<u32>) {
        for view in self.views.values_mut() {
            view.doc_state = None;

            view.size = size;
            view.needs_render = true;
        }
    }

    fn set_scale_factor(&mut self, scale: f32) {
        if (self.scale_factor - scale).abs() < f32::EPSILON {
            return;
        }
        self.scale_factor = scale;
        for view in self.views.values_mut() {
            view.doc_state = None;

            view.container
                .inner_mut()
                .resize_with_scale(view.size.width, view.size.height, scale);
            view.needs_render = true;
        }
    }

    fn handle_keyboard_event(&mut self, _id: ViewId, _event: keyboard::Event) {
        // No-op: litehtml has no keyboard interaction.
    }

    fn handle_mouse_event(&mut self, id: ViewId, point: Point, event: mouse::Event) {
        match event {
            mouse::Event::WheelScrolled { delta } => {
                self.scroll(id, delta);
            }
            mouse::Event::ButtonPressed(mouse::Button::Left) => {
                let Some(view) = self.views.get_mut(id) else {
                    return;
                };
                view.drag_origin = Some((point.x, point.y));
                view.drag_active = false;
                if let Some(ref mut state) = view.doc_state {
                    let doc_y = point.y + view.scroll_y;
                    state.doc.on_lbutton_down(point.x, doc_y, point.x, point.y);
                    state.selection.clear();
                }
                view.selection_rects.clear();
            }
            mouse::Event::CursorMoved { .. } => {
                let Some(view) = self.views.get_mut(id) else {
                    return;
                };

                // Notify litehtml of mouse movement for :hover and cursor updates
                if let Some(ref mut state) = view.doc_state {
                    let doc_y = point.y + view.scroll_y;
                    state.doc.on_mouse_over(point.x, doc_y, point.x, point.y);
                }
                // Take doc_state out to avoid aliasing while reading cursor.
                let doc_state = view.doc_state.take();
                view.cursor = css_cursor_to_interaction(view.container.inner().cursor());
                view.doc_state = doc_state;

                if let Some((ox, oy)) = view.drag_origin {
                    let dx = point.x - ox;
                    let dy = point.y - oy;

                    if !view.drag_active && (dx * dx + dy * dy).sqrt() >= 4.0 {
                        view.drag_active = true;
                        if let Some(ref mut state) = view.doc_state {
                            let doc_y = oy + view.scroll_y;
                            state.selection.start_at(
                                &state.doc,
                                &*state.measure,
                                ox,
                                doc_y,
                                ox,
                                oy,
                            );
                        }
                    }

                    if view.drag_active {
                        if let Some(ref mut state) = view.doc_state {
                            let doc_y = point.y + view.scroll_y;
                            state.selection.extend_to(
                                &state.doc,
                                &*state.measure,
                                point.x,
                                doc_y,
                                point.x,
                                point.y,
                            );
                        }
                        update_selection_rects(view);
                    }
                }
            }
            mouse::Event::ButtonReleased(mouse::Button::Left) => {
                let Some(view) = self.views.get_mut(id) else {
                    return;
                };
                let was_dragging = view.drag_active;
                view.drag_active = false;
                view.drag_origin = None;

                // Always notify litehtml to clear :active pseudo-class state
                if let Some(ref mut state) = view.doc_state {
                    let doc_y = point.y + view.scroll_y;
                    state.doc.on_lbutton_up(point.x, doc_y, point.x, point.y);
                }
                // Discard anchor clicks produced during text selection.
                // Take doc_state out to avoid aliasing with container.
                if was_dragging {
                    let doc_state = view.doc_state.take();
                    view.container.inner_mut().take_anchor_click();
                    view.doc_state = doc_state;
                }
            }
            mouse::Event::CursorLeft => {
                if let Some(view) = self.views.get_mut(id) {
                    if let Some(ref mut state) = view.doc_state {
                        state.doc.on_mouse_leave();
                    }
                    view.cursor = Interaction::Idle;
                }
            }
            _ => {}
        }
    }

    fn scroll(&mut self, id: ViewId, delta: mouse::ScrollDelta) {
        let Some(view) = self.views.get_mut(id) else {
            return;
        };
        match delta {
            mouse::ScrollDelta::Lines { y, .. } => {
                view.scroll_y -= y * 40.0;
            }
            mouse::ScrollDelta::Pixels { y, .. } => {
                view.scroll_y -= y;
            }
        }
        let max_scroll = (view.content_height - view.size.height as f32).max(0.0);
        view.scroll_y = view.scroll_y.clamp(0.0, max_scroll);
    }

    fn goto(&mut self, id: ViewId, page_type: PageType) {
        let Some(view) = self.views.get_mut(id) else {
            return;
        };
        match page_type {
            PageType::Html(html) => {
                view.doc_state = None;
                // Clear image state from the previous page so stale fetches
                // don't interfere and new images are discovered fresh.
                view.staged_images.clear();
                view.container.inner_mut().clear_pending_images();
                // Clear image baseurls from the previous page
                view.container.image_baseurls.borrow_mut().clear();
                view.selection_rects.clear();

                view.html = html;
                view.scroll_y = 0.0;
                view.needs_render = true;
            }
            PageType::Url(url) => {
                // Take doc_state out to avoid aliasing with container.
                let doc_state = view.doc_state.take();
                view.container.base_url = url.clone();
                view.doc_state = doc_state;
                view.url = url;
            }
        }
    }

    fn refresh(&mut self, id: ViewId) {
        let Some(view) = self.views.get_mut(id) else {
            return;
        };
        view.doc_state = None;

        view.needs_render = true;
    }

    fn go_forward(&mut self, _id: ViewId) {
        // No-op: no navigation history.
    }

    fn go_back(&mut self, _id: ViewId) {
        // No-op: no navigation history.
    }

    fn get_url(&self, id: ViewId) -> String {
        let Some(view) = self.views.get(id) else {
            return "about:blank".to_string();
        };
        if view.url.is_empty() {
            "about:blank".to_string()
        } else {
            view.url.clone()
        }
    }

    fn get_title(&self, id: ViewId) -> String {
        self.views
            .get(id)
            .map(|v| v.title.clone())
            .unwrap_or_default()
    }

    fn get_cursor(&self, id: ViewId) -> Interaction {
        self.views
            .get(id)
            .map(|v| v.cursor)
            .unwrap_or(Interaction::Idle)
    }

    fn get_view(&self, id: ViewId) -> &ImageInfo {
        static BLANK: std::sync::LazyLock<ImageInfo> = std::sync::LazyLock::new(ImageInfo::default);
        self.views.get(id).map(|v| &v.last_frame).unwrap_or(&BLANK)
    }

    fn get_scroll_y(&self, id: ViewId) -> f32 {
        self.views.get(id).map(|v| v.scroll_y).unwrap_or(0.0)
    }

    fn get_content_height(&self, id: ViewId) -> f32 {
        self.views.get(id).map(|v| v.content_height).unwrap_or(0.0)
    }

    fn get_selected_text(&self, id: ViewId) -> Option<String> {
        self.views
            .get(id)?
            .doc_state
            .as_ref()?
            .selection
            .selected_text()
    }

    fn get_selection_rects(&self, id: ViewId) -> &[[f32; 4]] {
        static EMPTY: &[[f32; 4]] = &[];
        self.views
            .get(id)
            .map(|v| v.selection_rects.as_slice())
            .unwrap_or(EMPTY)
    }

    fn take_anchor_click(&mut self, id: ViewId) -> Option<String> {
        let view = self.views.get_mut(id)?;
        // Take doc_state out to avoid aliasing with container.
        let doc_state = view.doc_state.take();
        let result = view.container.inner_mut().take_anchor_click();
        view.doc_state = doc_state;
        result
    }

    fn take_pending_images(&mut self) -> Vec<(ViewId, String, String, bool)> {
        let mut result = Vec::new();
        for (id, view) in self.views.iter_mut() {
            // Take doc_state out to avoid aliasing with container.
            let doc_state = view.doc_state.take();
            for (src, redraw_on_ready) in view.container.inner_mut().take_pending_images() {
                let baseurl = view
                    .container
                    .image_baseurls
                    .borrow()
                    .get(&src)
                    .cloned()
                    .unwrap_or_default();
                result.push((id, src, baseurl, redraw_on_ready));
            }
            view.doc_state = doc_state;
        }
        result
    }

    fn load_image_from_bytes(
        &mut self,
        id: ViewId,
        url: &str,
        bytes: &[u8],
        redraw_on_ready: bool,
    ) {
        let Some(view) = self.views.get_mut(id) else {
            return;
        };
        if let Some(existing) = view.staged_images.iter_mut().find(|(u, _, _)| u == url) {
            existing.1 = bytes.to_vec();
            existing.2 = redraw_on_ready;
        } else {
            view.staged_images
                .push((url.to_string(), bytes.to_vec(), redraw_on_ready));
        }
    }

    fn set_css_cache(&mut self, id: ViewId, cache: HashMap<String, String>) {
        let Some(view) = self.views.get_mut(id) else {
            return;
        };
        // Take doc_state out to avoid aliasing with container.
        let doc_state = view.doc_state.take();
        view.container.set_css_cache(cache);
        view.doc_state = doc_state;
    }

    fn scroll_to_fragment(&mut self, id: ViewId, fragment: &str) -> bool {
        let Some(view) = self.views.get_mut(id) else {
            return false;
        };
        let state = match view.doc_state.as_ref() {
            Some(s) => s,
            None => return false,
        };
        let root = match state.doc.root() {
            Some(r) => r,
            None => return false,
        };

        // Try #id first, then [name="fragment"] (matches browser behavior).
        // Escape CSS meta-characters so fragments like "foo.bar" don't get
        // misinterpreted as compound selectors.
        let escaped = css_escape_ident(fragment);
        let id_selector = format!("#{escaped}");
        let el = root.select_one(&id_selector).or_else(|| {
            let quoted = fragment.replace('\\', "\\\\").replace('"', "\\\"");
            let name_selector = format!("[name=\"{quoted}\"]");
            root.select_one(&name_selector)
        });

        if let Some(el) = el {
            let pos = el.placement();
            let max_scroll = (view.content_height - view.size.height as f32).max(0.0);
            view.scroll_y = pos.y.clamp(0.0, max_scroll);
            true
        } else {
            false
        }
    }
}