teksilo-webview 0.24.2

Embeddable WebView widget for Teksilo — pluggable native engine backend (wry / Servo) behind a Teksilo-native widget.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! `ServoBackend`: the pure-Rust engine backend, through the [`servo`] crate,
//! behind the `servo-backend` feature.
//!
//! Servo renders each page offscreen, into a GL context of this backend's own
//! ([`gl_context`]), and its frames reach the window through the picture the
//! `WebView` widget draws: a [`WebViewRendering::Surface`] backend. Nothing of
//! it touches the window wgpu presents to, so it works under Wayland, where wry
//! cannot embed, and the page clips, sits under overlays and scrolls with its
//! container like any other content.
//!
//! # The loop
//!
//! Servo works on threads of its own and asks to be run on the UI thread
//! through an [`EventLoopWaker`]. The waker posts one [`WebViewPumpPayload`]
//! at a time; `teksilo-app` answers it with `WebViewRegistry::pump`, which runs
//! [`Servo::spin_event_loop`] and then, for each web view Servo reported a new
//! frame for, paints it and starts reading it back. A read is handed on the
//! next time the engine runs (the frame clock wakes it a few milliseconds
//! later), through a `LiveImageDiffWriter`, so a frame identical to the last
//! one commits nothing and wakes no window. A web view that is dormant or
//! scrolled out of view is hidden and throttled in Servo, and paints nothing.
//!
//! # Events
//!
//! Load start and finish, navigations, URL changes, the title, console
//! messages and the page taking or giving up the keyboard reach the widget as
//! [`WebViewEvent`]s.
//!
//! # Input
//!
//! The widget forwards what lands on the page ([`WebViewInputEvent`]), and
//! [`input`] passes it to Servo; see there for the two things that do not
//! carry over exactly.
//!
//! # Messages
//!
//! `window.ipc.postMessage(m)` in a page reaches the widget's `on_message`
//! ([`ipc`]); `post_message` dispatches a `teksilo-message` event in the page.
//!
//! [`WebViewPumpPayload`]: crate::WebViewPumpPayload

mod frame_clock;
mod gl_context;
mod input;
mod ipc;

use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use teksilo_canvas::live_image::{LiveImageDiffWriter, LiveImageWriter};
use teksilo_canvas::{ImageOrientation, Rect};
use teksilo_core::AppEventPoster;
use teksilo_core::raw_handle::ParentHandle;
use teksilo_core::window::TeksiloWindowId;

use dpi::PhysicalSize;
use euclid::Scale;
use servo::protocol_handler::ProtocolRegistry;
use servo::{
    ConsoleLogLevel, Cursor, EmbedderControl, EmbedderControlId, EventLoopWaker, LoadStatus,
    NavigationRequest, RenderingContext, SelectElement, SelectElementOptionOrOptgroup, Servo,
    ServoBuilder, SimpleDialog, UserContentManager, UserScript, WebView as ServoWebView,
    WebViewBuilder, WebViewDelegate,
};
use teksilo_core::widget::CursorIcon;
use url::Url;

use crate::controls::{WebViewControl, WebViewControlAnswer, WebViewSelectOption};

use crate::backend::{
    ConsoleLevel, NoopWebViewHandle, WebSource, WebViewAttributes, WebViewBackend, WebViewEvent,
    WebViewHandle, WebViewId, WebViewInputEvent, WebViewRendering, js_string, post_event,
    post_pump,
};

use frame_clock::FrameClock;
use gl_context::{AdapterKind, HeadlessGlContext};

/// How long a read may wait on the GPU when the engine runs: past it, the
/// clock looks again a little later instead of holding the UI thread.
const READ_WAIT: Duration = Duration::from_millis(2);

/// When to look again for a read still on the GPU.
const READ_RETRY: Duration = Duration::from_millis(3);

/// The pure-Rust engine backend. Construct and hand to
/// `install_web_view(ServoBackend::new())`.
///
/// Every web view this backend opens shares one Servo engine, built when the
/// first one opens. Servo allows one engine per process, ever: its options are
/// a process-wide once-cell that a dropped engine does not reset. So a second
/// `ServoBackend` in the same process (a second application builder, say)
/// cannot get an engine of its own, and its web views show the error chrome
/// with a console message saying why.
#[derive(Default)]
pub struct ServoBackend {
    engine: Option<Rc<Engine>>,
}

impl std::fmt::Debug for ServoBackend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ServoBackend")
            .field("engine_built", &self.engine.is_some())
            .finish()
    }
}

impl ServoBackend {
    /// Construct the Servo backend.
    pub fn new() -> Self {
        Self::default()
    }
}

/// Set once this process has built a Servo engine. Servo panics on a second
/// build (`opts::initialize_options` sets a once-cell), so this is what turns
/// that panic into an error a web view can report.
static ENGINE_BUILT: AtomicBool = AtomicBool::new(false);

/// The process already built its one engine, for another backend.
#[derive(Debug, PartialEq, Eq)]
struct EngineTaken;

/// The engine `slot` holds, built with `build` if this process has none yet.
///
/// Generic so the rule can be tested without starting Servo.
fn shared_engine<T: Clone>(
    slot: &mut Option<T>,
    built: &AtomicBool,
    build: impl FnOnce() -> T,
) -> Result<T, EngineTaken> {
    if let Some(engine) = slot {
        return Ok(engine.clone());
    }
    if built.swap(true, Ordering::AcqRel) {
        return Err(EngineTaken);
    }
    Ok(slot.insert(build()).clone())
}

/// Report engine-init failure: drive the widget to its Error chrome via
/// `NavigationFinished { success: false }`, plus a console message. Returns a
/// no-op handle. Mirrors `wry_backend::fail`.
fn fail(
    poster: &Option<Arc<dyn AppEventPoster>>,
    window_id: TeksiloWindowId,
    web_view_id: WebViewId,
    text: String,
) -> Box<dyn WebViewHandle> {
    post_event(
        poster,
        window_id,
        web_view_id,
        WebViewEvent::ConsoleMessage {
            level: ConsoleLevel::Error,
            text,
        },
    );
    post_event(
        poster,
        window_id,
        web_view_id,
        WebViewEvent::NavigationFinished {
            url: String::new(),
            success: false,
        },
    );
    Box::new(NoopWebViewHandle)
}

/// Asks the UI thread to run the engine: posts one pump request at a time.
/// Called by Servo from its own threads, and by the frame clock.
#[derive(Clone)]
struct ServoWaker {
    inner: Arc<WakerState>,
}

struct WakerState {
    /// A pump request is posted and not yet answered.
    posted: AtomicBool,
    poster: Option<Arc<dyn AppEventPoster>>,
}

impl ServoWaker {
    fn new(poster: Option<Arc<dyn AppEventPoster>>) -> Self {
        Self {
            inner: Arc::new(WakerState {
                posted: AtomicBool::new(false),
                poster,
            }),
        }
    }

    /// The request is being answered: a wake from now on posts another.
    fn answered(&self) {
        self.inner.posted.store(false, Ordering::Release);
    }
}

impl EventLoopWaker for ServoWaker {
    fn clone_box(&self) -> Box<dyn EventLoopWaker> {
        Box::new(self.clone())
    }

    fn wake(&self) {
        if !self.inner.posted.swap(true, Ordering::AcqRel) {
            post_pump(&self.inner.poster);
        }
    }
}

/// The one Servo of the process, and what runs it.
struct Engine {
    servo: Servo,
    waker: ServoWaker,
    clock: FrameClock,
    /// Every open web view; dead entries are dropped as the engine runs.
    views: RefCell<Vec<Weak<View>>>,
    /// Where each web view's `window.ipc` messages go.
    routes: ipc::Routes,
    /// The script every page runs first: `window.ipc`.
    user_content: Rc<UserContentManager>,
}

impl Engine {
    fn start(poster: Option<Arc<dyn AppEventPoster>>) -> Rc<Self> {
        let waker = ServoWaker::new(poster);
        let clock_waker = waker.clone();
        let clock = FrameClock::start(move || clock_waker.wake());
        let routes = ipc::Routes::default();
        // Servo takes its protocol handlers once, as it starts.
        let mut protocols = ProtocolRegistry::default();
        let _ = protocols.register(
            ipc::IPC_SCHEME,
            ipc::IpcHandler {
                routes: routes.clone(),
            },
        );
        // A page's accessibility tree reaches the widget only with this on;
        // it is a process-wide preference, read as the engine starts.
        let preferences = servo::Preferences {
            accessibility_enabled: true,
            ..Default::default()
        };
        let servo = ServoBuilder::default()
            .preferences(preferences)
            .event_loop_waker(Box::new(waker.clone()))
            .protocol_registry(protocols)
            .build();
        let user_content = Rc::new(UserContentManager::new(&servo));
        user_content.add_script(Rc::new(UserScript::new(ipc::IPC_SCRIPT.to_string(), None)));
        Rc::new(Self {
            servo,
            waker,
            clock,
            views: RefCell::new(Vec::new()),
            routes,
            user_content,
        })
    }

    /// Run Servo once, then paint and read back what changed.
    fn pump(&self) {
        self.waker.answered();
        self.servo.spin_event_loop();
        let views: Vec<Rc<View>> = {
            let mut views = self.views.borrow_mut();
            views.retain(|view| view.strong_count() > 0);
            views.iter().filter_map(Weak::upgrade).collect()
        };
        let now = Instant::now();
        for view in views {
            view.present(&self.clock, now);
        }
    }
}

/// One open web view: its rendering context, its Servo `WebView`, and the
/// picture its frames go to.
struct View {
    gl: Rc<HeadlessGlContext>,
    webview: RefCell<Option<ServoWebView>>,
    picture: RefCell<LiveImageDiffWriter>,
    /// Servo reported a frame not painted yet.
    frame_ready: Cell<bool>,
    /// The widget shows the page: not dormant, and some of it in view.
    shown: Cell<bool>,
    /// The context's size, in device pixels.
    size: Cell<PhysicalSize<u32>>,
    scale: Cell<f32>,
    /// The `data:` URL the backend made for inline HTML, reported to the
    /// widget as `about:blank`: as wry reports such a page, and short enough
    /// for a URL bar.
    inline_url: RefCell<Option<String>>,
    /// The dialogs and lists the page opened and the application has not
    /// answered yet. Dropping one answers it with its default.
    controls: RefCell<std::collections::HashMap<u64, PendingControl>>,
    next_control: Cell<u64>,
}

/// A control the page is waiting on.
enum PendingControl {
    Dialog(SimpleDialog),
    Select(SelectElement),
}

impl View {
    /// Hand on a finished read, then paint a reported frame if there is one
    /// and the page is shown.
    fn present(&self, clock: &FrameClock, now: Instant) {
        if self.gl.reads_pending() {
            let mut picture = self.picture.borrow_mut();
            self.gl.finish_reads(READ_WAIT, &mut |rows, width, height| {
                // A refused frame (a size past LiveImage's limits) leaves the
                // previous one shown; the next resize brings it back in range.
                let _ = picture.write_frame(width, height, rows, width as usize * 4);
            });
            if self.gl.reads_pending() {
                clock.wake_at(now + READ_RETRY);
            }
        }

        // The first frame at a new size still shows the page's previous
        // layout, its newly exposed part the page background; the relaid page
        // follows one frame later. Committed as it comes, as a browser shows
        // it.
        if !self.frame_ready.get() || !self.shown.get() {
            return;
        }
        self.frame_ready.set(false);
        let Some(webview) = self.webview.borrow().clone() else {
            return;
        };
        webview.paint();
        self.gl.begin_read();
        clock.wake_at(now + READ_RETRY);
    }
}

/// Translates Servo's delegate callbacks into [`WebViewEvent`]s, and marks
/// its view when a frame is ready.
struct ServoEventDelegate {
    view: Weak<View>,
    poster: Option<Arc<dyn AppEventPoster>>,
    window_id: TeksiloWindowId,
    web_view_id: WebViewId,
}

impl ServoEventDelegate {
    fn post(&self, event: WebViewEvent) {
        post_event(&self.poster, self.window_id, self.web_view_id, event);
    }

    /// `url` as the widget is told it: the backend's own inline-HTML `data:`
    /// URL as `about:blank`.
    fn reported(&self, url: String) -> String {
        let inline = self
            .view
            .upgrade()
            .is_some_and(|view| view.inline_url.borrow().as_deref() == Some(url.as_str()));
        if inline {
            "about:blank".to_string()
        } else {
            url
        }
    }
}

impl WebViewDelegate for ServoEventDelegate {
    fn notify_new_frame_ready(&self, _webview: ServoWebView) {
        // Painted by `Engine::pump` once `spin_event_loop` returns, so every
        // view's frame of this spin is painted in one place.
        if let Some(view) = self.view.upgrade() {
            view.frame_ready.set(true);
        }
    }

    fn notify_load_status_changed(&self, webview: ServoWebView, status: LoadStatus) {
        match status {
            LoadStatus::Started => self.post(WebViewEvent::PageLoadStarted),
            LoadStatus::HeadParsed => {}
            LoadStatus::Complete => {
                self.post(WebViewEvent::PageLoadFinished);
                self.post(WebViewEvent::NavigationFinished {
                    url: self.reported(webview.url().map(|u| u.to_string()).unwrap_or_default()),
                    success: true,
                });
            }
        }
    }

    fn notify_page_title_changed(&self, _webview: ServoWebView, title: Option<String>) {
        self.post(WebViewEvent::TitleChanged(title.unwrap_or_default()));
    }

    fn request_navigation(&self, _webview: ServoWebView, request: NavigationRequest) {
        self.post(WebViewEvent::NavigationStarted {
            url: self.reported(request.url.to_string()),
            can_cancel: false,
        });
        // Dropping the request allows the navigation: the widget observes
        // navigations, it does not veto them.
        drop(request);
    }

    /// A URL change with no load behind it (`history.pushState`, a fragment)
    /// finishes a navigation as far as the widget's URL binding is concerned.
    fn notify_url_changed(&self, _webview: ServoWebView, url: Url) {
        self.post(WebViewEvent::NavigationFinished {
            url: self.reported(url.to_string()),
            success: true,
        });
    }

    fn notify_focus_changed(&self, _webview: ServoWebView, focused: bool) {
        self.post(WebViewEvent::EngineFocusChanged(focused));
    }

    fn notify_accessibility_tree_update(
        &self,
        _webview: ServoWebView,
        update: servo::accesskit::TreeUpdate,
    ) {
        if let Some(update) = page_accessibility(&update) {
            self.post(WebViewEvent::PageAccessibility(update));
        }
    }

    fn notify_cursor_changed(&self, _webview: ServoWebView, cursor: Cursor) {
        self.post(WebViewEvent::CursorChanged(cursor_icon(cursor)));
    }

    /// An editable element took focus: say where its caret is. A dialog or a
    /// `<select>` is kept and handed to the application to present. Every
    /// other control (a file or colour picker, a context menu) is dropped,
    /// which answers it with its default, so no page waits on one.
    fn show_embedder_control(&self, _webview: ServoWebView, control: EmbedderControl) {
        let device_rect = |r: servo::DeviceIntRect| {
            Rect::new(
                r.min.x as f32,
                r.min.y as f32,
                r.width() as f32,
                r.height() as f32,
            )
        };
        let (pending, described) = match control {
            EmbedderControl::InputMethod(input) => {
                self.post(WebViewEvent::InputMethodArea(Some(device_rect(
                    input.position(),
                ))));
                return;
            }
            EmbedderControl::SimpleDialog(dialog) => {
                let described = match &dialog {
                    SimpleDialog::Alert(alert) => WebViewControl::Alert {
                        message: alert.message().to_string(),
                    },
                    SimpleDialog::Confirm(confirm) => WebViewControl::Confirm {
                        message: confirm.message().to_string(),
                    },
                    SimpleDialog::Prompt(prompt) => WebViewControl::Prompt {
                        message: prompt.message().to_string(),
                        default: prompt.current_value().to_string(),
                    },
                };
                (PendingControl::Dialog(dialog), described)
            }
            EmbedderControl::SelectElement(select) => {
                let described = WebViewControl::Select {
                    options: select_options(select.options()),
                    selected: select.selected_options().first().copied(),
                    area: device_rect(select.position()),
                };
                (PendingControl::Select(select), described)
            }
            _ => return,
        };
        let Some(view) = self.view.upgrade() else {
            return;
        };
        let key = view.next_control.get();
        view.next_control.set(key + 1);
        view.controls.borrow_mut().insert(key, pending);
        self.post(WebViewEvent::ControlRequested {
            key,
            control: described,
        });
    }

    fn hide_embedder_control(&self, _webview: ServoWebView, _id: EmbedderControlId) {
        self.post(WebViewEvent::InputMethodArea(None));
    }

    fn show_console_message(&self, _webview: ServoWebView, level: ConsoleLogLevel, text: String) {
        self.post(WebViewEvent::ConsoleMessage {
            level: console_level(level),
            text,
        });
    }
}

/// Servo's tree update (AccessKit 0.24) as the widget takes it (0.25).
///
/// Both versions serialise a node as a map from property name to value and
/// share the names, 0.25 only adding ones 0.24 never writes, so a round trip
/// through serde converts. `None` if a later Servo writes something 0.25
/// cannot read: the page's tree is then not mirrored, and the page still works.
fn page_accessibility(
    update: &servo::accesskit::TreeUpdate,
) -> Option<crate::PageAccessibilityUpdate> {
    let value = serde_json::to_value(update).ok()?;
    let update: teksilo_core::accesskit::TreeUpdate = serde_json::from_value(value).ok()?;
    Some(crate::PageAccessibilityUpdate {
        root: update.tree.map(|tree| tree.root.0),
        nodes: update
            .nodes
            .into_iter()
            .map(|(id, node)| (id.0, node))
            .collect(),
    })
}

/// A `<select>`'s options, its groups flattened into a label on each option.
fn select_options(options: &[SelectElementOptionOrOptgroup]) -> Vec<WebViewSelectOption> {
    let mut out = Vec::new();
    for entry in options {
        match entry {
            SelectElementOptionOrOptgroup::Option(option) => out.push(WebViewSelectOption {
                id: option.id,
                label: option.label.clone(),
                disabled: option.is_disabled,
                group: None,
            }),
            SelectElementOptionOrOptgroup::Optgroup { label, options } => {
                out.extend(options.iter().map(|option| WebViewSelectOption {
                    id: option.id,
                    label: option.label.clone(),
                    disabled: option.is_disabled,
                    group: Some(label.clone()),
                }));
            }
        }
    }
    out
}

/// The nearest of Teksilo's cursors to the one the page asked for.
fn cursor_icon(cursor: Cursor) -> CursorIcon {
    match cursor {
        Cursor::Pointer | Cursor::Alias | Cursor::ContextMenu => CursorIcon::Pointer,
        Cursor::Text | Cursor::VerticalText => CursorIcon::Text,
        Cursor::Crosshair | Cursor::Cell => CursorIcon::Crosshair,
        Cursor::Move | Cursor::AllScroll => CursorIcon::Move,
        Cursor::NotAllowed | Cursor::NoDrop => CursorIcon::NotAllowed,
        Cursor::Grab => CursorIcon::Grab,
        Cursor::Grabbing => CursorIcon::Grabbing,
        Cursor::EResize | Cursor::WResize | Cursor::EwResize | Cursor::ColResize => {
            CursorIcon::ColResize
        }
        Cursor::NResize | Cursor::SResize | Cursor::NsResize | Cursor::RowResize => {
            CursorIcon::RowResize
        }
        Cursor::NeResize | Cursor::SwResize | Cursor::NeswResize => CursorIcon::NeswResize,
        Cursor::NwResize | Cursor::SeResize | Cursor::NwseResize => CursorIcon::NwseResize,
        _ => CursorIcon::Default,
    }
}

/// The widget's three console levels, from Servo's seven.
fn console_level(level: ConsoleLogLevel) -> ConsoleLevel {
    match level {
        ConsoleLogLevel::Warn => ConsoleLevel::Warn,
        ConsoleLogLevel::Error => ConsoleLevel::Error,
        ConsoleLogLevel::Log
        | ConsoleLogLevel::Debug
        | ConsoleLogLevel::Info
        | ConsoleLogLevel::Trace
        | ConsoleLogLevel::Dir => ConsoleLevel::Log,
    }
}

impl WebViewBackend for ServoBackend {
    fn rendering(&self) -> WebViewRendering {
        // A GL readback stores the bottom row first.
        WebViewRendering::Surface {
            orientation: ImageOrientation::FlipVertical,
        }
    }

    fn open(
        &mut self,
        web_view_id: WebViewId,
        window_id: TeksiloWindowId,
        _parent: Option<ParentHandle>,
        attrs: WebViewAttributes,
        poster: Option<Arc<dyn AppEventPoster>>,
        surface: Option<LiveImageWriter>,
    ) -> Box<dyn WebViewHandle> {
        let Some(surface) = surface else {
            return fail(
                &poster,
                window_id,
                web_view_id,
                "ServoBackend: opened without a picture to render into".to_string(),
            );
        };
        let engine_poster = poster.clone();
        let engine = match shared_engine(&mut self.engine, &ENGINE_BUILT, || {
            Engine::start(engine_poster)
        }) {
            Ok(engine) => engine,
            Err(EngineTaken) => {
                return fail(
                    &poster,
                    window_id,
                    web_view_id,
                    "ServoBackend: this process already built its one Servo engine for another \
                     backend, and Servo allows only one; install a single ServoBackend"
                        .to_string(),
                );
            }
        };

        // A real size arrives with the widget's first `set_bounds`.
        let size = PhysicalSize::new(1, 1);
        let gl = match HeadlessGlContext::new(size, Rc::new(engine.clock.driver())) {
            Ok(gl) => Rc::new(gl),
            Err(error) => {
                return fail(
                    &poster,
                    window_id,
                    web_view_id,
                    format!("ServoBackend: no OpenGL context to render into: {error:?}"),
                );
            }
        };
        if gl.adapter() == AdapterKind::Software {
            post_event(
                &poster,
                window_id,
                web_view_id,
                WebViewEvent::ConsoleMessage {
                    level: ConsoleLevel::Warn,
                    text: format!(
                        "ServoBackend: no hardware OpenGL adapter, rendering on {}",
                        gl.renderer()
                    ),
                },
            );
        }

        let view = Rc::new(View {
            gl: gl.clone(),
            webview: RefCell::new(None),
            picture: RefCell::new(LiveImageDiffWriter::new(surface)),
            frame_ready: Cell::new(false),
            shown: Cell::new(true),
            size: Cell::new(size),
            scale: Cell::new(1.0),
            inline_url: RefCell::new(None),
            controls: RefCell::new(std::collections::HashMap::new()),
            next_control: Cell::new(0),
        });
        let delegate: Rc<dyn WebViewDelegate> = Rc::new(ServoEventDelegate {
            view: Rc::downgrade(&view),
            poster: poster.clone(),
            window_id,
            web_view_id,
        });
        let mut builder = WebViewBuilder::new(&engine.servo, gl as Rc<dyn RenderingContext>)
            .delegate(delegate)
            .user_content_manager(engine.user_content.clone())
            .hidpi_scale_factor(Scale::new(1.0));
        if let Some(url) = attrs.source.as_ref().and_then(source_url) {
            if matches!(attrs.source, Some(WebSource::Html { .. })) {
                *view.inline_url.borrow_mut() = Some(url.to_string());
            }
            builder = builder.url(url);
        }
        let webview = builder.build();
        // The page's tree goes to the widget, which mirrors it under its own
        // node; the subtree id Servo returns is for a graft, which the mirror
        // does not need.
        let _ = webview.set_accessibility_active(true);
        engine
            .routes
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .insert(
                webview.id(),
                ipc::Route {
                    web_view_id,
                    window_id,
                    poster: poster.clone(),
                },
            );
        *view.webview.borrow_mut() = Some(webview);
        engine.views.borrow_mut().push(Rc::downgrade(&view));
        // The page starts loading on Servo's threads, which wake the engine
        // when there is something to run.
        Box::new(ServoHandle { engine, view })
    }

    fn pump(&mut self) {
        if let Some(engine) = &self.engine {
            engine.pump();
        }
    }
}

/// The URL that shows `source`: inline HTML travels as a `data:` URL, as
/// Servo has no call to load a string.
fn source_url(source: &WebSource) -> Option<Url> {
    match source {
        WebSource::Url(url) => Url::parse(url).ok(),
        WebSource::Html { html, .. } => html_url(html),
    }
}

/// `html` as a `data:` URL. A `data:` document has an opaque origin, so a
/// base URL cannot apply to it; relative links in it resolve to nothing.
fn html_url(html: &str) -> Option<Url> {
    let mut url = String::with_capacity(html.len() + 32);
    url.push_str("data:text/html;charset=utf-8,");
    for byte in html.bytes() {
        if byte.is_ascii_alphanumeric() || b"-_.~".contains(&byte) {
            url.push(byte as char);
        } else {
            url.push_str(&format!("%{byte:02X}"));
        }
    }
    Url::parse(&url).ok()
}

/// A live web view. Dropping it closes the page; the engine lives on while
/// the backend or another handle holds it.
struct ServoHandle {
    engine: Rc<Engine>,
    view: Rc<View>,
}

impl Drop for ServoHandle {
    fn drop(&mut self) {
        if let Some(webview) = self.view.webview.borrow().as_ref() {
            self.engine
                .routes
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .remove(&webview.id());
        }
    }
}

impl ServoHandle {
    fn with_webview(&self, f: impl FnOnce(&ServoWebView)) {
        if let Some(webview) = self.view.webview.borrow().as_ref() {
            f(webview);
        }
    }
}

impl WebViewHandle for ServoHandle {
    fn set_bounds(&self, bounds: Rect, scale_factor: f32) {
        let scale = if scale_factor.is_finite() && scale_factor > 0.0 {
            scale_factor
        } else {
            1.0
        };
        let size = PhysicalSize::new(
            (bounds.width * scale).round().max(1.0) as u32,
            (bounds.height * scale).round().max(1.0) as u32,
        );
        let view = &self.view;
        if (view.scale.get() - scale).abs() > f32::EPSILON {
            view.scale.set(scale);
            self.with_webview(|w| w.set_hidpi_scale_factor(Scale::new(scale)));
        }
        // Past the GL's largest surface, a framebuffer cannot be complete. A
        // box that wide shows the page's leading part, unscaled.
        let limit = view.gl.max_surface_size();
        let size = PhysicalSize::new(size.width.min(limit), size.height.min(limit));
        if view.size.get() != size {
            view.size.set(size);
            self.with_webview(|w| w.resize(size));
        }
    }
    fn load_url(&self, url: &str) {
        if let Ok(parsed) = Url::parse(url) {
            self.with_webview(|w| w.load(parsed));
        }
    }
    fn load_html(&self, html: &str, _base_url: Option<&str>) {
        if let Some(url) = html_url(html) {
            *self.view.inline_url.borrow_mut() = Some(url.to_string());
            self.with_webview(|w| w.load(url));
        }
    }
    fn eval(&self, script: &str) {
        self.with_webview(|w| w.evaluate_javascript(script.to_string(), |_result| {}));
    }
    fn post_message(&self, msg: &str) {
        // No built-in IPC channel; emulate Rust→JS via a dispatched event,
        // through the shared escaper.
        let script = format!(
            "window.dispatchEvent(new MessageEvent('teksilo-message',{{data:{}}}))",
            js_string(msg)
        );
        self.with_webview(|w| w.evaluate_javascript(script, |_result| {}));
    }
    fn reload(&self) {
        self.with_webview(|w| w.reload());
    }
    fn go_back(&self) {
        self.with_webview(|w| {
            w.go_back(1);
        });
    }
    fn go_forward(&self) {
        self.with_webview(|w| {
            w.go_forward(1);
        });
    }
    fn stop(&self) {
        self.eval("window.stop()");
    }
    fn set_visible(&self, visible: bool) {
        self.view.shown.set(visible);
        self.with_webview(|w| {
            if visible {
                w.show();
            } else {
                w.hide();
            }
            // A hidden page runs no animation frames and no timers it can
            // defer, so a page parked in another tab costs next to nothing.
            w.set_throttled(!visible);
        });
        if visible && self.view.frame_ready.get() {
            // A frame reported while hidden is painted now.
            self.engine.waker.wake();
        }
    }
    fn set_focus(&self) {
        self.with_webview(|w| w.focus());
    }
    fn blur(&self) {
        self.with_webview(|w| w.blur());
    }
    fn answer_control(&self, key: u64, answer: WebViewControlAnswer) {
        let Some(control) = self.view.controls.borrow_mut().remove(&key) else {
            return;
        };
        match (control, answer) {
            (PendingControl::Dialog(SimpleDialog::Alert(alert)), _) => alert.confirm(),
            (
                PendingControl::Dialog(SimpleDialog::Confirm(confirm)),
                WebViewControlAnswer::Confirmed,
            ) => confirm.confirm(),
            (
                PendingControl::Dialog(SimpleDialog::Prompt(mut prompt)),
                WebViewControlAnswer::Text(text),
            ) => {
                prompt.set_current_value(&text);
                prompt.confirm();
            }
            (PendingControl::Select(mut select), WebViewControlAnswer::Selected(id)) => {
                select.select(vec![id]);
                select.submit();
            }
            // Anything else is a cancel: dropping the control answers it so.
            (PendingControl::Dialog(SimpleDialog::Confirm(confirm)), _) => confirm.dismiss(),
            (PendingControl::Dialog(SimpleDialog::Prompt(prompt)), _) => prompt.dismiss(),
            (PendingControl::Select(_), _) => {}
        }
    }
    fn set_input_passthrough(&self, _passthrough: bool) {
        // A surface engine takes no input but what the widget forwards, and
        // the widget never asks it to pass any through.
    }
    fn send_input(&self, event: &WebViewInputEvent) {
        let Some(event) = input::to_servo(event, self.view.scale.get()) else {
            return;
        };
        // Servo answers through `notify_input_event_handled`; the widget has
        // already decided whether the event is the page's, so the answer is
        // not waited for.
        self.with_webview(|w| {
            w.notify_input_event(event);
        });
    }
}

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

    #[test]
    fn a_backend_builds_its_engine_once_and_shares_it() {
        let built = AtomicBool::new(false);
        let mut slot = None;
        let mut builds = 0;
        let mut build = || {
            builds += 1;
            builds
        };
        assert_eq!(shared_engine(&mut slot, &built, &mut build), Ok(1));
        assert_eq!(shared_engine(&mut slot, &built, &mut build), Ok(1));
        assert_eq!(builds, 1);
    }

    #[test]
    fn a_second_backend_in_the_process_gets_no_engine() {
        let built = AtomicBool::new(false);
        let mut first = None;
        let mut second = None;
        assert_eq!(shared_engine(&mut first, &built, || 1), Ok(1));
        assert_eq!(shared_engine(&mut second, &built, || 2), Err(EngineTaken));
        assert_eq!(second, None);
    }

    #[test]
    fn inline_html_travels_as_a_data_url() {
        let url = html_url("<p>a&b # 50% é</p>").expect("a data: URL");
        assert_eq!(url.scheme(), "data");
        assert!(
            !url.as_str().contains('#'),
            "a raw '#' would cut the document at a fragment: {url}"
        );
        assert!(url.as_str().contains("%25"), "a raw '%' is escaped: {url}");
    }
}