Skip to main content

servo/
webview_delegate.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::path::PathBuf;
6use std::rc::Rc;
7
8use embedder_traits::{
9    AlertResponse, AllowOrDeny, AuthenticationResponse, BluetoothDeviceDescription,
10    ConfirmResponse, ConsoleLogLevel, ContextMenuAction, ContextMenuElementInformation,
11    ContextMenuItem, Cursor, EmbedderControlId, EmbedderControlResponse, FilePickerRequest,
12    FilterPattern, InputEventId, InputEventResult, InputMethodType, LoadStatus, MediaSessionEvent,
13    NewWebViewDetails, Notification, PermissionFeature, PromptResponse, RgbColor, ScreenGeometry,
14    SelectElementOptionOrOptgroup, SelectElementRequest, SimpleDialogRequest, TraversalId,
15    WebResourceRequest, WebResourceResponse, WebResourceResponseMsg,
16};
17use paint_api::rendering_context::RenderingContext;
18use servo_base::generic_channel::{GenericCallback, GenericSender, SendError};
19use servo_base::id::PipelineId;
20use servo_constellation_traits::EmbedderToConstellationMessage;
21use tokio::sync::mpsc::UnboundedSender as TokioSender;
22use tokio::sync::oneshot::Sender;
23use url::Url;
24use webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize};
25
26use crate::proxies::ConstellationProxy;
27use crate::responders::{AutomaticResponder, OneshotSender, ServoErrorSender};
28use crate::{RegisterOrUnregister, Servo, WebView, WebViewBuilder};
29
30/// A request to navigate a [`WebView`] or one of its inner frames. This can be handled
31/// asynchronously. If not handled, the request will automatically be allowed.
32pub struct NavigationRequest {
33    pub url: Url,
34    pub(crate) pipeline_id: PipelineId,
35    pub(crate) constellation_proxy: ConstellationProxy,
36    pub(crate) response_sent: bool,
37}
38
39impl NavigationRequest {
40    /// Allow this navigation request to proceed.
41    pub fn allow(mut self) {
42        self.constellation_proxy
43            .send(EmbedderToConstellationMessage::AllowNavigationResponse(
44                self.pipeline_id,
45                true,
46            ));
47        self.response_sent = true;
48    }
49
50    /// Deny this navigation request, preventing the navigation from proceeding.
51    pub fn deny(mut self) {
52        self.constellation_proxy
53            .send(EmbedderToConstellationMessage::AllowNavigationResponse(
54                self.pipeline_id,
55                false,
56            ));
57        self.response_sent = true;
58    }
59}
60
61impl Drop for NavigationRequest {
62    fn drop(&mut self) {
63        if !self.response_sent {
64            self.constellation_proxy
65                .send(EmbedderToConstellationMessage::AllowNavigationResponse(
66                    self.pipeline_id,
67                    true,
68                ));
69        }
70    }
71}
72
73/// A permissions request for a [`WebView`]. The embedder should allow or deny the request,
74/// either by reading a cached value or querying the user for permission via the user
75/// interface.
76pub struct PermissionRequest {
77    pub(crate) requested_feature: PermissionFeature,
78    pub(crate) allow_deny_request: AllowOrDenyRequest,
79}
80
81impl PermissionRequest {
82    /// Get the [`PermissionFeature`] for which permission is being requested by page content.
83    pub fn feature(&self) -> PermissionFeature {
84        self.requested_feature
85    }
86
87    /// Grant permission to the web content to access the requested feature.
88    pub fn allow(self) {
89        self.allow_deny_request.allow();
90    }
91
92    /// Deny permission to the web content to access the requested feature.
93    pub fn deny(self) {
94        self.allow_deny_request.deny();
95    }
96}
97
98/// A type used for communicating an allow-or-deny decision from the embedder
99/// to Servo. This is used as a part of requests from Servo to the embedder
100/// to perform certain actions and the request can either be allowed or denied
101/// by the embedder.
102pub struct AllowOrDenyRequest(AutomaticResponder<AllowOrDeny>, ServoErrorSender);
103
104impl AllowOrDenyRequest {
105    pub(crate) fn new(
106        response_sender: GenericSender<AllowOrDeny>,
107        default_response: AllowOrDeny,
108        error_sender: ServoErrorSender,
109    ) -> Self {
110        Self(
111            AutomaticResponder::new(response_sender, default_response),
112            error_sender,
113        )
114    }
115
116    pub(crate) fn new_from_callback(
117        callback: GenericCallback<AllowOrDeny>,
118        default_response: AllowOrDeny,
119        error_sender: ServoErrorSender,
120    ) -> Self {
121        Self(
122            AutomaticResponder::new_same_process(Box::new(callback), default_response),
123            error_sender,
124        )
125    }
126
127    /// Allow the action requested by Servo.
128    pub fn allow(mut self) {
129        if let Err(error) = self.0.send(AllowOrDeny::Allow) {
130            self.1.raise_response_send_error(error);
131        }
132    }
133
134    /// Deny the action requested by Servo.
135    pub fn deny(mut self) {
136        if let Err(error) = self.0.send(AllowOrDeny::Deny) {
137            self.1.raise_response_send_error(error);
138        }
139    }
140}
141
142/// A request to register or unregister a custom handler for a scheme.
143/// See <https://html.spec.whatwg.org/multipage/#custom-handlers>
144#[derive(Clone, Debug, Eq, PartialEq)]
145pub struct ProtocolHandlerRegistration {
146    /// The scheme for which the hander is being registered or unregistered.
147    pub scheme: String,
148    /// The URL to navigate to when loading resources for the given 'scheme'.
149    /// The string "%s" in this URL is used as a placeholder. It will be replaced
150    /// by the URL of the resource to be handled.
151    pub url: Url,
152    /// Whether this request is for a new registration or unregistering
153    /// a previously registered handler.
154    pub register_or_unregister: RegisterOrUnregister,
155}
156
157/// A request to let the user chose a Bluetooth device.
158pub struct BluetoothDeviceSelectionRequest {
159    devices: Vec<BluetoothDeviceDescription>,
160    responder: AutomaticResponder<Option<String>>,
161}
162
163impl BluetoothDeviceSelectionRequest {
164    pub(crate) fn new(
165        devices: Vec<BluetoothDeviceDescription>,
166        responder: GenericSender<Option<String>>,
167    ) -> Self {
168        Self {
169            devices,
170            responder: AutomaticResponder::new(responder, None),
171        }
172    }
173
174    /// Set the device chosen by the user.
175    pub fn pick_device(mut self, device: &BluetoothDeviceDescription) -> Result<(), SendError> {
176        self.responder.send(Some(device.address.clone()))
177    }
178
179    /// Cancel this request.
180    pub fn cancel(mut self) -> Result<(), SendError> {
181        self.responder.send(None)
182    }
183
184    /// The set of devices that the user can chose from.
185    pub fn devices(&self) -> &Vec<BluetoothDeviceDescription> {
186        &self.devices
187    }
188}
189
190/// A request to authenticate a [`WebView`] navigation. Embedders may choose to prompt
191/// the user to enter credentials or simply ignore this request (in which case credentials
192/// will not be used).
193pub struct AuthenticationRequest {
194    pub(crate) url: Url,
195    pub(crate) for_proxy: bool,
196    pub(crate) responder: AutomaticResponder<Option<AuthenticationResponse>>,
197    pub(crate) error_sender: ServoErrorSender,
198}
199
200impl AuthenticationRequest {
201    pub(crate) fn new(
202        url: Url,
203        for_proxy: bool,
204        response_sender: Sender<Option<AuthenticationResponse>>,
205        error_sender: ServoErrorSender,
206    ) -> Self {
207        Self {
208            url,
209            for_proxy,
210            responder: AutomaticResponder::new_same_process(
211                Box::new(OneshotSender::from(response_sender)),
212                None,
213            ),
214            error_sender,
215        }
216    }
217
218    /// The URL of the request that triggered this authentication.
219    pub fn url(&self) -> &Url {
220        &self.url
221    }
222    /// Whether or not this authentication request is associated with a proxy server authentication.
223    pub fn for_proxy(&self) -> bool {
224        self.for_proxy
225    }
226    /// Respond to the [`AuthenticationRequest`] with the given username and password.
227    pub fn authenticate(mut self, username: String, password: String) {
228        if let Err(error) = self
229            .responder
230            .send(Some(AuthenticationResponse { username, password }))
231        {
232            self.error_sender.raise_response_send_error(error);
233        }
234    }
235}
236
237/// Information related to the loading of a web resource. These are created for all HTTP requests.
238/// The client may choose to intercept the load of web resources and send an alternate response
239/// by calling [`WebResourceLoad::intercept`].
240pub struct WebResourceLoad {
241    pub request: WebResourceRequest,
242    pub(crate) responder: AutomaticResponder<WebResourceResponseMsg>,
243    pub(crate) error_sender: ServoErrorSender,
244}
245
246impl WebResourceLoad {
247    pub(crate) fn new(
248        web_resource_request: WebResourceRequest,
249        response_sender: TokioSender<WebResourceResponseMsg>,
250        error_sender: ServoErrorSender,
251    ) -> Self {
252        Self {
253            request: web_resource_request,
254            responder: AutomaticResponder::new_same_process(
255                Box::new(response_sender),
256                WebResourceResponseMsg::DoNotIntercept,
257            ),
258            error_sender,
259        }
260    }
261
262    /// The [`WebResourceRequest`] associated with this [`WebResourceLoad`].
263    pub fn request(&self) -> &WebResourceRequest {
264        &self.request
265    }
266
267    /// Intercept this [`WebResourceLoad`] and control the response via the returned
268    /// [`InterceptedWebResourceLoad`].
269    pub fn intercept(mut self, response: WebResourceResponse) -> InterceptedWebResourceLoad {
270        if let Err(error) = self.responder.send(WebResourceResponseMsg::Start(response)) {
271            self.error_sender.raise_response_send_error(error);
272        }
273        InterceptedWebResourceLoad {
274            request: self.request.clone(),
275            response_sender: self.responder,
276            finished: false,
277            error_sender: self.error_sender,
278        }
279    }
280}
281
282/// An intercepted web resource load. This struct allows the client to send an alternative response
283/// after calling [`WebResourceLoad::intercept`]. In order to send chunks of body data, the client
284/// must call [`InterceptedWebResourceLoad::send_body_data`]. When the interception is complete, the client
285/// should call [`InterceptedWebResourceLoad::finish`]. If neither `finish()` or `cancel()` are called,
286/// this interception will automatically be finished when dropped.
287pub struct InterceptedWebResourceLoad {
288    pub request: WebResourceRequest,
289    pub(crate) response_sender: AutomaticResponder<WebResourceResponseMsg>,
290    pub(crate) finished: bool,
291    pub(crate) error_sender: ServoErrorSender,
292}
293
294impl InterceptedWebResourceLoad {
295    /// Send a chunk of response body data. It's possible to make subsequent calls to
296    /// this method when streaming body data.
297    pub fn send_body_data(&mut self, data: Vec<u8>) {
298        if let Err(error) = self
299            .response_sender
300            .send(WebResourceResponseMsg::SendBodyData(data))
301        {
302            self.error_sender.raise_response_send_error(error);
303        }
304    }
305    /// Finish this [`InterceptedWebResourceLoad`] and complete the response.
306    pub fn finish(mut self) {
307        if let Err(error) = self
308            .response_sender
309            .send(WebResourceResponseMsg::FinishLoad)
310        {
311            self.error_sender.raise_response_send_error(error);
312        }
313        self.finished = true;
314    }
315    /// Cancel this [`InterceptedWebResourceLoad`], which will trigger a network error.
316    pub fn cancel(mut self) {
317        if let Err(error) = self
318            .response_sender
319            .send(WebResourceResponseMsg::CancelLoad)
320        {
321            self.error_sender.raise_response_send_error(error);
322        }
323        self.finished = true;
324    }
325}
326
327impl Drop for InterceptedWebResourceLoad {
328    fn drop(&mut self) {
329        if !self.finished &&
330            let Err(error) = self
331                .response_sender
332                .send(WebResourceResponseMsg::FinishLoad)
333        {
334            self.error_sender.raise_response_send_error(error);
335        }
336    }
337}
338
339/// The controls of an interactive form element.
340pub enum EmbedderControl {
341    /// The picker of a `<select>` element.
342    SelectElement(SelectElement),
343    /// The picker of a `<input type=color>` element.
344    ColorPicker(ColorPicker),
345    /// The picker of a `<input type=file>` element.
346    FilePicker(FilePicker),
347    /// Request to present an input method (IME) interface to the user when an
348    /// editable element is focused.
349    InputMethod(InputMethodControl),
350    /// A [simple dialog](https://html.spec.whatwg.org/multipage/#simple-dialogs) initiated by
351    /// script (`alert()`, `confirm()`, or `prompt()`). Since their messages are controlled by web
352    /// content, they should be presented to the user in a way that makes them impossible to
353    /// mistake for browser UI.
354    SimpleDialog(SimpleDialog),
355    /// A context menu. This can be triggered by things like right-clicking on web content.
356    /// The menu that is actually shown the user may be customized, but custom menu entries
357    /// must be handled by the embedder.
358    ContextMenu(ContextMenu),
359    /// HTML elements' attributes that are represented as tooltips.
360    Tooltip(TooltipControl),
361}
362
363impl EmbedderControl {
364    /// Return the unique identifier for this embedder control.
365    pub fn id(&self) -> EmbedderControlId {
366        match self {
367            EmbedderControl::SelectElement(select_element) => select_element.id,
368            EmbedderControl::ColorPicker(color_picker) => color_picker.id,
369            EmbedderControl::FilePicker(file_picker) => file_picker.id,
370            EmbedderControl::InputMethod(input_method) => input_method.id,
371            EmbedderControl::SimpleDialog(simple_dialog) => simple_dialog.id(),
372            EmbedderControl::ContextMenu(context_menu) => context_menu.id,
373            EmbedderControl::Tooltip(tooltip) => tooltip.id,
374        }
375    }
376}
377
378pub struct TooltipControl {
379    pub id: EmbedderControlId,
380    pub text: String,
381}
382
383/// Represents a context menu opened on web content.
384pub struct ContextMenu {
385    pub(crate) id: EmbedderControlId,
386    pub(crate) position: DeviceIntRect,
387    pub(crate) items: Vec<ContextMenuItem>,
388    pub(crate) element_info: ContextMenuElementInformation,
389    pub(crate) response_sent: bool,
390    pub(crate) constellation_proxy: ConstellationProxy,
391}
392
393impl ContextMenu {
394    /// Return the [`EmbedderControlId`] associated with this element.
395    pub fn id(&self) -> EmbedderControlId {
396        self.id
397    }
398
399    /// Return the area occupied by the element on which this context menu was triggered.
400    ///
401    /// The embedder should use this value to position the prompt that is shown to the user.
402    pub fn position(&self) -> DeviceIntRect {
403        self.position
404    }
405
406    /// A [`ContextMenuElementInformation`] giving details about the element that this [`ContextMenu`]
407    /// was activated on.
408    pub fn element_info(&self) -> &ContextMenuElementInformation {
409        &self.element_info
410    }
411
412    /// Resolve the context menu by activating the given context menu action.
413    pub fn items(&self) -> &[ContextMenuItem] {
414        &self.items
415    }
416
417    /// Resolve the context menu by activating the given context menu action.
418    pub fn select(mut self, action: ContextMenuAction) {
419        self.constellation_proxy
420            .send(EmbedderToConstellationMessage::EmbedderControlResponse(
421                self.id,
422                EmbedderControlResponse::ContextMenu(Some(action)),
423            ));
424        self.response_sent = true;
425    }
426
427    /// Tell Servo that the context menu was dismissed with no selection.
428    pub fn dismiss(mut self) {
429        self.constellation_proxy
430            .send(EmbedderToConstellationMessage::EmbedderControlResponse(
431                self.id,
432                EmbedderControlResponse::ContextMenu(None),
433            ));
434        self.response_sent = true;
435    }
436}
437
438impl Drop for ContextMenu {
439    fn drop(&mut self) {
440        if !self.response_sent {
441            self.constellation_proxy
442                .send(EmbedderToConstellationMessage::EmbedderControlResponse(
443                    self.id,
444                    EmbedderControlResponse::ContextMenu(None),
445                ));
446        }
447    }
448}
449
450/// Represents a dialog triggered by clicking a `<select>` element.
451pub struct SelectElement {
452    pub(crate) id: EmbedderControlId,
453    pub(crate) position: DeviceIntRect,
454    pub(crate) constellation_proxy: ConstellationProxy,
455    pub(crate) select_element_request: SelectElementRequest,
456    pub(crate) response_sent: bool,
457}
458
459impl SelectElement {
460    /// Return the [`EmbedderControlId`] associated with this element.
461    pub fn id(&self) -> EmbedderControlId {
462        self.id
463    }
464
465    /// Return the area occupied by the `<select>` element that triggered the prompt.
466    ///
467    /// The embedder should use this value to position the prompt that is shown to the user.
468    pub fn position(&self) -> DeviceIntRect {
469        self.position
470    }
471
472    /// Consecutive `<option>` elements outside of an `<optgroup>` will be combined
473    /// into a single anonymous group without a label.
474    pub fn options(&self) -> &[SelectElementOptionOrOptgroup] {
475        &self.select_element_request.options
476    }
477
478    /// Set the options that are selected.
479    ///
480    /// `selected_options` is a vector of indices into the array returned by [`Self::options`].
481    ///
482    /// If other options have previously been selected, this set of options
483    /// will replace them.
484    pub fn select(&mut self, selected_options: Vec<usize>) {
485        self.select_element_request.selected_options = selected_options
486    }
487
488    /// Get the currently selected options, represented by indices into the array
489    /// returned by [`Self::options`].
490    pub fn selected_options(&self) -> Vec<usize> {
491        self.select_element_request.selected_options.clone()
492    }
493
494    /// Whether this `<select>` supports selecting multiple options.
495    pub fn allow_select_multiple(&self) -> bool {
496        self.select_element_request.allow_select_multiple
497    }
498
499    /// Resolve the prompt with the options that have been selected by calling [`Self::select`] previously.
500    pub fn submit(mut self) {
501        self.response_sent = true;
502        self.constellation_proxy
503            .send(EmbedderToConstellationMessage::EmbedderControlResponse(
504                self.id,
505                EmbedderControlResponse::SelectElement(self.selected_options()),
506            ));
507    }
508}
509
510impl Drop for SelectElement {
511    fn drop(&mut self) {
512        if !self.response_sent {
513            self.constellation_proxy
514                .send(EmbedderToConstellationMessage::EmbedderControlResponse(
515                    self.id,
516                    EmbedderControlResponse::SelectElement(self.selected_options()),
517                ));
518        }
519    }
520}
521
522/// Represents a dialog triggered by clicking a `<input type=color>` element.
523pub struct ColorPicker {
524    pub(crate) id: EmbedderControlId,
525    pub(crate) current_color: Option<RgbColor>,
526    pub(crate) position: DeviceIntRect,
527    pub(crate) constellation_proxy: ConstellationProxy,
528    pub(crate) response_sent: bool,
529}
530
531impl ColorPicker {
532    /// Return the [`EmbedderControlId`] associated with this element.
533    pub fn id(&self) -> EmbedderControlId {
534        self.id
535    }
536
537    /// Get the area occupied by the `<input>` element that triggered the prompt.
538    ///
539    /// The embedder should use this value to position the prompt that is shown to the user.
540    pub fn position(&self) -> DeviceIntRect {
541        self.position
542    }
543
544    /// Get the currently selected color for this [`ColorPicker`]. This is initially the selected color
545    /// before the picker is opened.
546    pub fn current_color(&self) -> Option<RgbColor> {
547        self.current_color
548    }
549
550    /// Set the selected color for this [`ColorPicker`]. Passing `None` behaves as if the default
551    /// color was selected.
552    pub fn select(&mut self, color: Option<RgbColor>) {
553        self.current_color = color;
554    }
555
556    /// Resolve the prompt with the options that have been selected by calling [`Self::select`] previously.
557    pub fn submit(mut self) {
558        self.response_sent = true;
559        self.constellation_proxy
560            .send(EmbedderToConstellationMessage::EmbedderControlResponse(
561                self.id,
562                EmbedderControlResponse::ColorPicker(self.current_color),
563            ));
564    }
565}
566
567impl Drop for ColorPicker {
568    fn drop(&mut self) {
569        if !self.response_sent {
570            self.constellation_proxy
571                .send(EmbedderToConstellationMessage::EmbedderControlResponse(
572                    self.id,
573                    EmbedderControlResponse::ColorPicker(self.current_color),
574                ));
575        }
576    }
577}
578
579/// Represents a dialog triggered by clicking a `<input type=file>` element.
580pub struct FilePicker {
581    pub(crate) id: EmbedderControlId,
582    pub(crate) file_picker_request: FilePickerRequest,
583    pub(crate) response_sender: Option<Sender<Option<Vec<PathBuf>>>>,
584}
585
586impl FilePicker {
587    /// Return the [`EmbedderControlId`] associated with this element.
588    pub fn id(&self) -> EmbedderControlId {
589        self.id
590    }
591
592    /// Get the file filter patterns for this [`FilePicker`], which specify the types
593    /// of files that are displayed in the dialog.
594    pub fn filter_patterns(&self) -> &[FilterPattern] {
595        &self.file_picker_request.filter_patterns
596    }
597
598    /// Whether or not this file picker allows selecting multiple files at once.
599    pub fn allow_select_multiple(&self) -> bool {
600        self.file_picker_request.allow_select_multiple
601    }
602
603    /// Whether or not this file picker selects directories instead of files.
604    pub fn select_directory(&self) -> bool {
605        self.file_picker_request.select_directory
606    }
607
608    /// Get the currently selected files in this [`FilePicker`]. This is initially the files that
609    /// were previously selected before the picker is opened.
610    pub fn current_paths(&self) -> &[PathBuf] {
611        &self.file_picker_request.current_paths
612    }
613
614    /// Set the selected files for this [`FilePicker`].
615    pub fn select(&mut self, paths: &[PathBuf]) {
616        self.file_picker_request.current_paths = paths.to_owned();
617    }
618
619    /// Resolve the prompt with the files that have been selected by calling [`Self::select`] previously.
620    pub fn submit(mut self) {
621        if let Some(sender) = self.response_sender.take() {
622            let _ = sender.send(Some(std::mem::take(
623                &mut self.file_picker_request.current_paths,
624            )));
625        }
626    }
627
628    /// Tell Servo that the file picker was dismissed with no selection.
629    pub fn dismiss(mut self) {
630        if let Some(sender) = self.response_sender.take() {
631            let _ = sender.send(None);
632        }
633    }
634}
635
636impl Drop for FilePicker {
637    fn drop(&mut self) {
638        if let Some(sender) = self.response_sender.take() {
639            let _ = sender.send(None);
640        }
641    }
642}
643
644/// Represents a request to enable the system input method interface.
645pub struct InputMethodControl {
646    pub(crate) id: EmbedderControlId,
647    pub(crate) input_method_type: InputMethodType,
648    pub(crate) text: String,
649    pub(crate) insertion_point: Option<u32>,
650    pub(crate) position: DeviceIntRect,
651    pub(crate) multiline: bool,
652    pub(crate) allow_virtual_keyboard: bool,
653}
654
655impl InputMethodControl {
656    /// Return the [`EmbedderControlId`] associated with this element.
657    pub fn id(&self) -> EmbedderControlId {
658        self.id
659    }
660
661    /// Return the type of input method that initated this request.
662    pub fn input_method_type(&self) -> InputMethodType {
663        self.input_method_type
664    }
665
666    /// Return the current string value of the input field.
667    pub fn text(&self) -> String {
668        self.text.clone()
669    }
670
671    /// The current zero-based insertion point / cursor position if it is within the field or `None`
672    /// if it is not.
673    pub fn insertion_point(&self) -> Option<u32> {
674        self.insertion_point
675    }
676
677    /// Get the area occupied by the `<input>` element that triggered the input method.
678    ///
679    /// The embedder should use this value to position the input method interface that is
680    /// shown to the user.
681    pub fn position(&self) -> DeviceIntRect {
682        self.position
683    }
684
685    /// Whether or not this field is a multiline field.
686    pub fn multiline(&self) -> bool {
687        self.multiline
688    }
689
690    /// Whether the virtual keyboard should be shown for this input method event.
691    /// This is currently true for input method events that happen after the user has
692    /// interacted with page contents via an input event.
693    pub fn allow_virtual_keyboard(&self) -> bool {
694        self.allow_virtual_keyboard
695    }
696}
697
698/// [Simple dialogs](https://html.spec.whatwg.org/multipage/#simple-dialogs) are synchronous dialogs
699/// that can be opened by web content. Since their messages are controlled by web content, they
700/// should be presented to the user in a way that makes them impossible to mistake for browser UI.
701pub enum SimpleDialog {
702    Alert(AlertDialog),
703    Confirm(ConfirmDialog),
704    Prompt(PromptDialog),
705}
706
707impl SimpleDialog {
708    #[doc(hidden)]
709    pub fn message(&self) -> &str {
710        match self {
711            SimpleDialog::Alert(alert_dialog) => alert_dialog.message(),
712            SimpleDialog::Confirm(confirm_dialog) => confirm_dialog.message(),
713            SimpleDialog::Prompt(prompt_dialog) => prompt_dialog.message(),
714        }
715    }
716
717    #[doc(hidden)]
718    pub fn confirm(self) {
719        match self {
720            SimpleDialog::Alert(alert_dialog) => alert_dialog.confirm(),
721            SimpleDialog::Confirm(confirm_dialog) => confirm_dialog.confirm(),
722            SimpleDialog::Prompt(prompt_dialog) => prompt_dialog.confirm(),
723        }
724    }
725
726    #[doc(hidden)]
727    pub fn dismiss(self) {
728        match self {
729            SimpleDialog::Alert(alert_dialog) => alert_dialog.confirm(),
730            SimpleDialog::Confirm(confirm_dialog) => confirm_dialog.dismiss(),
731            SimpleDialog::Prompt(prompt_dialog) => prompt_dialog.dismiss(),
732        }
733    }
734}
735
736impl SimpleDialog {
737    fn id(&self) -> EmbedderControlId {
738        match self {
739            SimpleDialog::Alert(alert_dialog) => alert_dialog.id,
740            SimpleDialog::Confirm(confirm_dialog) => confirm_dialog.id,
741            SimpleDialog::Prompt(prompt_dialog) => prompt_dialog.id,
742        }
743    }
744}
745
746impl From<SimpleDialogRequest> for SimpleDialog {
747    fn from(simple_dialog_request: SimpleDialogRequest) -> Self {
748        match simple_dialog_request {
749            SimpleDialogRequest::Alert {
750                id,
751                message,
752                response_sender,
753            } => Self::Alert(AlertDialog {
754                id,
755                message,
756                response_sender,
757                response_sent: false,
758            }),
759            SimpleDialogRequest::Confirm {
760                id,
761                message,
762                response_sender,
763            } => Self::Confirm(ConfirmDialog {
764                id,
765                message,
766                response_sender,
767                response_sent: false,
768            }),
769            SimpleDialogRequest::Prompt {
770                id,
771                message,
772                default,
773                response_sender,
774            } => Self::Prompt(PromptDialog {
775                id,
776                message,
777                current_value: default,
778                response_sender,
779                response_sent: false,
780            }),
781        }
782    }
783}
784
785/// [`alert()`](https://html.spec.whatwg.org/multipage/#dom-alert).
786///
787/// The confirm dialog is expected to be represented by a message and an "Ok" button.
788/// Pressing "Ok" always causes the DOM API to return `undefined`.
789pub struct AlertDialog {
790    id: EmbedderControlId,
791    message: String,
792    response_sender: GenericSender<AlertResponse>,
793    response_sent: bool,
794}
795
796impl Drop for AlertDialog {
797    fn drop(&mut self) {
798        if !self.response_sent {
799            let _ = self.response_sender.send(AlertResponse::Ok);
800        }
801    }
802}
803
804impl AlertDialog {
805    /// Get the message text of this [`AlertDialog`], which is set by web content.
806    pub fn message(&self) -> &str {
807        &self.message
808    }
809
810    /// This should be called when the dialog button is pressed.
811    pub fn confirm(self) {
812        // The result will be send via the `Drop` implementation.
813    }
814}
815
816/// [`confirm()`](https://html.spec.whatwg.org/multipage/#dom-confirm).
817///
818/// The confirm dialog is expected to be represented by a message and "Ok" and "Cancel"
819/// buttons. When "Ok" is selected `true` is sent as a response to the DOM API, while
820/// "Cancel" will send `false`.
821pub struct ConfirmDialog {
822    id: EmbedderControlId,
823    message: String,
824    response_sender: GenericSender<ConfirmResponse>,
825    response_sent: bool,
826}
827
828impl ConfirmDialog {
829    /// Get the message text of this [`ConfirmDialog`], which is set by web content.
830    pub fn message(&self) -> &str {
831        &self.message
832    }
833
834    /// This should be called when the dialog "Cancel" button is pressed.
835    pub fn dismiss(mut self) {
836        let _ = self.response_sender.send(ConfirmResponse::Cancel);
837        self.response_sent = true;
838    }
839
840    /// This should be called when the dialog "Ok" button is pressed.
841    pub fn confirm(mut self) {
842        let _ = self.response_sender.send(ConfirmResponse::Ok);
843        self.response_sent = true;
844    }
845}
846
847impl Drop for ConfirmDialog {
848    fn drop(&mut self) {
849        if !self.response_sent {
850            let _ = self.response_sender.send(ConfirmResponse::Cancel);
851        }
852    }
853}
854
855/// A [`prompt()`](https://html.spec.whatwg.org/multipage/#dom-prompt).
856///
857/// The prompt dialog is expected to be represented by a message, a text entry field, and
858/// an "Ok" and "Cancel" buttons. When "Ok" is selected the current prompt value is sent
859/// as the response to the DOM API. A default value may be sent with the [`PromptDialog`],
860/// which be be retrieved by calling [`Self::current_value`]. Before calling [`Self::confirm`]
861/// or as the prompt field changes, the embedder is expected to call
862/// [`Self::set_current_value`].
863pub struct PromptDialog {
864    id: EmbedderControlId,
865    message: String,
866    current_value: String,
867    response_sender: GenericSender<PromptResponse>,
868    response_sent: bool,
869}
870
871impl Drop for PromptDialog {
872    fn drop(&mut self) {
873        if !self.response_sent {
874            let _ = self.response_sender.send(PromptResponse::Cancel);
875        }
876    }
877}
878
879impl PromptDialog {
880    /// Get the message text of this [`PromptDialog`], which is set by web content.
881    pub fn message(&self) -> &str {
882        &self.message
883    }
884
885    /// Get the current value of the prompt's text entry field.
886    pub fn current_value(&self) -> &str {
887        &self.current_value
888    }
889
890    /// Set the current value of the prompt's text entry field.
891    pub fn set_current_value(&mut self, new_value: &str) {
892        self.current_value = new_value.to_owned()
893    }
894
895    /// This should be called when the dialog "Cancel" button is pressed.
896    pub fn dismiss(mut self) {
897        let _ = self.response_sender.send(PromptResponse::Cancel);
898        self.response_sent = true;
899    }
900
901    /// This should be called when the dialog "Ok" button is pressed, the current prompt value will
902    /// be sent to web content.
903    pub fn confirm(mut self) {
904        let _ = self
905            .response_sender
906            .send(PromptResponse::Ok(self.current_value.clone()));
907        self.response_sent = true;
908    }
909}
910
911/// A request from Servo to embedder to open a new auxiliary [`WebView`], typically
912/// triggered by page content calling DOM APIs like `window.open()`.
913///
914/// Refer to the documentation of [`WebViewDelegate::request_create_new`] for more information.
915pub struct CreateNewWebViewRequest {
916    pub(crate) servo: Servo,
917    pub(crate) responder: AutomaticResponder<Option<NewWebViewDetails>>,
918}
919
920impl CreateNewWebViewRequest {
921    /// Returns a [`WebViewBuilder`] that can be used to create a new auxiliary [`WebView`].
922    pub fn builder(self, rendering_context: Rc<dyn RenderingContext>) -> WebViewBuilder {
923        WebViewBuilder::new_for_create_request(&self.servo, rendering_context, self.responder)
924    }
925}
926
927/// A trait that the embedder can implement to customize the behaviour of a [`WebView`] or to
928/// listen to events from a [`WebView`]. Multiple [`WebView`]s can share the same delegate
929/// instance. A [`WebView`]'s delegate needs to be set at the time of creation using
930/// [`WebViewBuilder::delegate`].
931pub trait WebViewDelegate {
932    /// Get the [`ScreenGeometry`] for this [`WebView`]. If this is unimplemented or returns `None`
933    /// the screen will have the size of the [`WebView`]'s `RenderingContext` and `WebView` will be
934    /// considered to be positioned at the screen's origin.
935    fn screen_geometry(&self, _webview: WebView) -> Option<ScreenGeometry> {
936        None
937    }
938    /// The URL of the currently loaded page in this [`WebView`] has changed. The new
939    /// URL can accessed via [`WebView::url`].
940    fn notify_url_changed(&self, _webview: WebView, _url: Url) {}
941    /// The page title of the currently loaded page in this [`WebView`] has changed. The new
942    /// title can accessed via [`WebView::page_title`].
943    fn notify_page_title_changed(&self, _webview: WebView, _title: Option<String>) {}
944    /// The status text of the currently loaded page in this [`WebView`] has changed. The new
945    /// status text can accessed via [`WebView::status_text`].
946    fn notify_status_text_changed(&self, _webview: WebView, _status: Option<String>) {}
947    /// This [`WebView`] has either started to animate or stopped animating. When a
948    /// [`WebView`] is animating, it is up to the embedding application ensure that
949    /// `Servo::spin_event_loop` is called at regular intervals in order to update the
950    /// painted contents of the [`WebView`].
951    fn notify_animating_changed(&self, _webview: WebView, _animating: bool) {}
952    /// The `LoadStatus` of the currently loading or loaded page in this [`WebView`] has changed. The new
953    /// status can accessed via [`WebView::load_status`].
954    fn notify_load_status_changed(&self, _webview: WebView, _status: LoadStatus) {}
955    /// The [`Cursor`] of the currently loaded page in this [`WebView`] has changed. The new
956    /// cursor can be accessed via [`WebView::cursor`].
957    fn notify_cursor_changed(&self, _webview: WebView, _cursor: Cursor) {}
958    /// The favicon of the currently loaded page in this [`WebView`] has changed. The new
959    /// favicon [`Image`](embedder_traits::Image) can accessed via [`WebView::favicon`].
960    fn notify_favicon_changed(&self, _webview: WebView) {}
961    /// Notify the embedder that it needs to present a new frame.
962    fn notify_new_frame_ready(&self, _webview: WebView) {}
963    /// The navigation history of this [`WebView`] has changed. The navigation history is represented
964    /// as a `Vec<Url>` and `_current` denotes the current index in the history. New navigations,
965    /// back navigation, and forward navigation modify this index.
966    fn notify_history_changed(&self, _webview: WebView, _entries: Vec<Url>, _current: usize) {}
967    /// A history traversal operation is complete.
968    fn notify_traversal_complete(&self, _webview: WebView, _traversal_id: TraversalId) {}
969    /// Page content has closed this [`WebView`] via `window.close()`. It's the embedder's
970    /// responsibility to remove the [`WebView`] from the interface when this notification
971    /// occurs.
972    fn notify_closed(&self, _webview: WebView) {}
973
974    /// An input event passed to this [`WebView`] via [`WebView::notify_input_event`] has been handled
975    /// by Servo. This allows post-procesing of input events, such as chaining up unhandled events
976    /// to parent UI elements.
977    fn notify_input_event_handled(
978        &self,
979        _webview: WebView,
980        _event_id: InputEventId,
981        _result: InputEventResult,
982    ) {
983    }
984    /// A pipeline in the webview panicked. First string is the reason, second one is the backtrace.
985    fn notify_crashed(&self, _webview: WebView, _reason: String, _backtrace: Option<String>) {}
986    /// Notifies the embedder about media session events
987    /// (i.e. when there is metadata for the active media session, playback state changes...).
988    fn notify_media_session_event(&self, _webview: WebView, _event: MediaSessionEvent) {}
989    /// A notification that the [`WebView`] has entered or exited fullscreen mode. This is an
990    /// opportunity for the embedder to transition the containing window into or out of fullscreen
991    /// mode and to show or hide extra UI elements. Regardless of how the notification is handled,
992    /// the page will enter or leave fullscreen state internally according to the [Fullscreen
993    /// API](https://fullscreen.spec.whatwg.org/).
994    fn notify_fullscreen_state_changed(&self, _webview: WebView, _is_fullscreen: bool) {}
995
996    /// Whether or not to allow a [`WebView`] to load a URL in its main frame or one of its
997    /// nested `<iframe>`s. [`NavigationRequest`]s are accepted by default.
998    fn request_navigation(&self, _webview: WebView, _navigation_request: NavigationRequest) {}
999    /// Whether or not to allow a [`WebView`]  to unload a `Document` in its main frame or one
1000    /// of its nested `<iframe>`s. By default, unloads are allowed.
1001    fn request_unload(&self, _webview: WebView, _unload_request: AllowOrDenyRequest) {}
1002    /// Move the window to a point.
1003    fn request_move_to(&self, _webview: WebView, _point: DeviceIntPoint) {}
1004    /// Whether or not to allow a [`WebView`] to (un)register a protocol handler (e.g. `mailto:`).
1005    /// Typically an embedder application will show a permissions prompt when this happens
1006    /// to confirm a protocol handler is allowed. By default, requests are denied.
1007    /// For more information, see the specification:
1008    /// <https://html.spec.whatwg.org/multipage/#custom-handlers>
1009    fn request_protocol_handler(
1010        &self,
1011        _webview: WebView,
1012        _protocol_handler_registration: ProtocolHandlerRegistration,
1013        _allow_deny_request: AllowOrDenyRequest,
1014    ) {
1015    }
1016    /// Try to resize the window that contains this [`WebView`] to the provided outer
1017    /// size. These resize requests can come from page content. Servo will ensure that the
1018    /// values are greater than zero, but it is up to the embedder to limit the maximum
1019    /// size. For instance, a reasonable limitation might be that the final size is no
1020    /// larger than the screen size.
1021    fn request_resize_to(&self, _webview: WebView, _requested_outer_size: DeviceIntSize) {}
1022    /// This method is called when web content makes a request to open a new
1023    /// `WebView`, such as via the [`window.open`] DOM API. If this request is
1024    /// ignored, no new `WebView` will be opened. Embedders can handle this method by
1025    /// using the provided [`CreateNewWebViewRequest`] to build a new `WebView`.
1026    ///
1027    /// ```ignore
1028    /// fn request_create_new(&self, parent_webview: WebView, request: CreateNewWebViewRequest) {
1029    ///     let webview = request
1030    ///         .builder(self.rendering_context())
1031    ///         .delegate(parent_webview.delegate())
1032    ///         .build();
1033    ///     self.register_webview(webview);
1034    /// }
1035    /// ```
1036    ///
1037    /// **Important:** It is important to keep a live handle to the new `WebView` in the application or
1038    /// it will be immediately destroyed.
1039    ///
1040    /// [`window.open`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/open
1041    fn request_create_new(&self, _parent_webview: WebView, _request: CreateNewWebViewRequest) {}
1042    /// Content in a [`WebView`] is requesting permission to access a feature requiring
1043    /// permission from the user. The embedder should allow or deny the request, either by
1044    /// reading a cached value or querying the user for permission via the user interface.
1045    fn request_permission(&self, _webview: WebView, _request: PermissionRequest) {}
1046
1047    /// Request that the embedder supply credentials to use for HTTP authentication.
1048    fn request_authentication(
1049        &self,
1050        _webview: WebView,
1051        _authentication_request: AuthenticationRequest,
1052    ) {
1053    }
1054
1055    /// Open dialog to select bluetooth device.
1056    fn show_bluetooth_device_dialog(
1057        &self,
1058        _webview: WebView,
1059        _request: BluetoothDeviceSelectionRequest,
1060    ) {
1061    }
1062
1063    /// Request that the embedder show UI elements for form controls that are not integrated
1064    /// into page content, such as dropdowns for `<select>` elements.
1065    fn show_embedder_control(&self, _webview: WebView, _embedder_control: EmbedderControl) {}
1066
1067    /// Request that the embedder hide and ignore a previous [`EmbedderControl`] request, if it hasn’t
1068    /// already responded to it.
1069    ///
1070    /// After this point, any further responses to that request will be ignored.
1071    fn hide_embedder_control(&self, _webview: WebView, _control_id: EmbedderControlId) {}
1072
1073    /// Triggered when this [`WebView`] will load a web (HTTP/HTTPS) resource. The load may be
1074    /// intercepted and alternate contents can be loaded by the client by calling
1075    /// [`WebResourceLoad::intercept`]. If not handled, the load will continue as normal.
1076    ///
1077    /// Note: This delegate method is called for all resource loads associated with a [`WebView`].
1078    /// For loads not associated with a [`WebView`], such as those for service workers, Servo
1079    /// will call [`crate::ServoDelegate::load_web_resource`].
1080    fn load_web_resource(&self, _webview: WebView, _load: WebResourceLoad) {}
1081
1082    /// Request to display a notification.
1083    fn show_notification(&self, _webview: WebView, _notification: Notification) {}
1084
1085    /// A console message was logged by content in this [`WebView`].
1086    /// <https://developer.mozilla.org/en-US/docs/Web/API/Console_API>
1087    fn show_console_message(&self, _webview: WebView, _level: ConsoleLogLevel, _message: String) {}
1088
1089    /// There is a new accessibility tree update from this [`WebView`].
1090    ///
1091    /// Generally the impl should send this update to an AccessKit adapter, but it may need to queue
1092    /// the update for later, if the [graft node] for this [`WebView`] has not yet been created
1093    /// *and* your impl is unable to create it (and send that update to AccessKit) before sending
1094    /// this update to AccessKit. For more details, see [`WebView::set_accessibility_active`].
1095    fn notify_accessibility_tree_update(
1096        &self,
1097        _webview: WebView,
1098        _tree_update: accesskit::TreeUpdate,
1099    ) {
1100    }
1101}
1102
1103pub(crate) struct DefaultWebViewDelegate;
1104impl WebViewDelegate for DefaultWebViewDelegate {}
1105
1106#[cfg(test)]
1107mod test {
1108    use super::*;
1109
1110    #[test]
1111    fn test_allow_deny_request() {
1112        use servo_base::generic_channel;
1113
1114        use crate::responders::ServoErrorChannel;
1115
1116        for default_response in [AllowOrDeny::Allow, AllowOrDeny::Deny] {
1117            // Explicit allow yields allow and nothing else
1118            let errors = ServoErrorChannel::default();
1119            let (sender, receiver) =
1120                generic_channel::channel().expect("Failed to create IPC channel");
1121            let request = AllowOrDenyRequest::new(sender, default_response, errors.sender());
1122            request.allow();
1123            assert_eq!(receiver.try_recv().ok(), Some(AllowOrDeny::Allow));
1124            assert_eq!(receiver.try_recv().ok(), None);
1125            assert!(errors.try_recv().is_none());
1126
1127            // Explicit deny yields deny and nothing else
1128            let errors = ServoErrorChannel::default();
1129            let (sender, receiver) =
1130                generic_channel::channel().expect("Failed to create IPC channel");
1131            let request = AllowOrDenyRequest::new(sender, default_response, errors.sender());
1132            request.deny();
1133            assert_eq!(receiver.try_recv().ok(), Some(AllowOrDeny::Deny));
1134            assert_eq!(receiver.try_recv().ok(), None);
1135            assert!(errors.try_recv().is_none());
1136
1137            // No response yields default response and nothing else
1138            let errors = ServoErrorChannel::default();
1139            let (sender, receiver) =
1140                generic_channel::channel().expect("Failed to create IPC channel");
1141            let request = AllowOrDenyRequest::new(sender, default_response, errors.sender());
1142            drop(request);
1143            assert_eq!(receiver.try_recv().ok(), Some(default_response));
1144            assert_eq!(receiver.try_recv().ok(), None);
1145            assert!(errors.try_recv().is_none());
1146
1147            // Explicit allow when receiver disconnected yields error
1148            let errors = ServoErrorChannel::default();
1149            let (sender, receiver) =
1150                generic_channel::channel().expect("Failed to create IPC channel");
1151            let request = AllowOrDenyRequest::new(sender, default_response, errors.sender());
1152            drop(receiver);
1153            request.allow();
1154            assert!(errors.try_recv().is_some());
1155
1156            // Explicit deny when receiver disconnected yields error
1157            let errors = ServoErrorChannel::default();
1158            let (sender, receiver) =
1159                generic_channel::channel().expect("Failed to create IPC channel");
1160            let request = AllowOrDenyRequest::new(sender, default_response, errors.sender());
1161            drop(receiver);
1162            request.deny();
1163            assert!(errors.try_recv().is_some());
1164
1165            // No response when receiver disconnected yields no error
1166            let errors = ServoErrorChannel::default();
1167            let (sender, receiver) =
1168                generic_channel::channel().expect("Failed to create IPC channel");
1169            let request = AllowOrDenyRequest::new(sender, default_response, errors.sender());
1170            drop(receiver);
1171            drop(request);
1172            assert!(errors.try_recv().is_none());
1173        }
1174    }
1175
1176    #[test]
1177    fn test_authentication_request() {
1178        use crate::responders::ServoErrorChannel;
1179
1180        let url = Url::parse("https://example.com").expect("Guaranteed by argument");
1181
1182        // Explicit response yields that response and nothing else
1183        let errors = ServoErrorChannel::default();
1184        let (sender, mut receiver) = tokio::sync::oneshot::channel();
1185        let request = AuthenticationRequest::new(url.clone(), false, sender, errors.sender());
1186        request.authenticate("diffie".to_owned(), "hunter2".to_owned());
1187        assert_eq!(
1188            receiver.try_recv().ok(),
1189            Some(Some(AuthenticationResponse {
1190                username: "diffie".to_owned(),
1191                password: "hunter2".to_owned(),
1192            }))
1193        );
1194        assert_eq!(receiver.try_recv().ok(), None);
1195        assert!(errors.try_recv().is_none());
1196
1197        // No response yields None response and nothing else
1198        let errors = ServoErrorChannel::default();
1199        let (sender, mut receiver) = tokio::sync::oneshot::channel();
1200        let request = AuthenticationRequest::new(url.clone(), false, sender, errors.sender());
1201        drop(request);
1202        assert_eq!(receiver.try_recv().ok(), Some(None));
1203        assert_eq!(receiver.try_recv().ok(), None);
1204        assert!(errors.try_recv().is_none());
1205
1206        // Explicit response when receiver disconnected yields error
1207        let errors = ServoErrorChannel::default();
1208        let (sender, receiver) = tokio::sync::oneshot::channel();
1209        let request = AuthenticationRequest::new(url.clone(), false, sender, errors.sender());
1210        drop(receiver);
1211        request.authenticate("diffie".to_owned(), "hunter2".to_owned());
1212        assert!(errors.try_recv().is_some());
1213
1214        // No response when receiver disconnected yields no error
1215        let errors = ServoErrorChannel::default();
1216        let (sender, receiver) = tokio::sync::oneshot::channel();
1217        let request = AuthenticationRequest::new(url.clone(), false, sender, errors.sender());
1218        drop(receiver);
1219        drop(request);
1220        assert!(errors.try_recv().is_none());
1221    }
1222
1223    #[test]
1224    fn test_web_resource_load() {
1225        use http::{HeaderMap, Method, StatusCode};
1226
1227        use crate::responders::ServoErrorChannel;
1228
1229        let web_resource_request = || WebResourceRequest {
1230            method: Method::GET,
1231            headers: HeaderMap::default(),
1232            url: Url::parse("https://example.com")
1233                .expect("Guaranteed by argument")
1234                .into(),
1235            destination: content_security_policy::Destination::Document,
1236            referrer_url: None,
1237            is_for_main_frame: false,
1238            is_redirect: false,
1239        };
1240        let web_resource_response = || {
1241            WebResourceResponse::new(
1242                Url::parse("https://diffie.test").expect("Guaranteed by argument"),
1243            )
1244            .status_code(StatusCode::IM_A_TEAPOT)
1245        };
1246
1247        // Explicit intercept with explicit cancel yields Start and Cancel and nothing else
1248        let errors = ServoErrorChannel::default();
1249        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
1250        let request = WebResourceLoad::new(web_resource_request(), sender, errors.sender());
1251        request.intercept(web_resource_response()).cancel();
1252        assert!(matches!(
1253            receiver.try_recv(),
1254            Ok(WebResourceResponseMsg::Start(_))
1255        ));
1256        assert!(matches!(
1257            receiver.try_recv(),
1258            Ok(WebResourceResponseMsg::CancelLoad)
1259        ));
1260        assert!(matches!(receiver.try_recv(), Err(_)));
1261        assert!(errors.try_recv().is_none());
1262
1263        // Explicit intercept with no further action yields Start and FinishLoad and nothing else
1264        let errors = ServoErrorChannel::default();
1265        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
1266        let request = WebResourceLoad::new(web_resource_request(), sender, errors.sender());
1267        drop(request.intercept(web_resource_response()));
1268        assert!(matches!(
1269            receiver.try_recv(),
1270            Ok(WebResourceResponseMsg::Start(_))
1271        ));
1272        assert!(matches!(
1273            receiver.try_recv(),
1274            Ok(WebResourceResponseMsg::FinishLoad)
1275        ));
1276        assert!(matches!(receiver.try_recv(), Err(_)));
1277        assert!(errors.try_recv().is_none());
1278
1279        // No response yields DoNotIntercept and nothing else
1280        let errors = ServoErrorChannel::default();
1281        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
1282        let request = WebResourceLoad::new(web_resource_request(), sender, errors.sender());
1283        drop(request);
1284        assert!(matches!(
1285            receiver.try_recv(),
1286            Ok(WebResourceResponseMsg::DoNotIntercept)
1287        ));
1288        assert!(matches!(receiver.try_recv(), Err(_)));
1289        assert!(errors.try_recv().is_none());
1290
1291        // Explicit intercept with explicit cancel when receiver disconnected yields error
1292        let errors = ServoErrorChannel::default();
1293        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
1294        let request = WebResourceLoad::new(web_resource_request(), sender, errors.sender());
1295        drop(receiver);
1296        request.intercept(web_resource_response()).cancel();
1297        assert!(errors.try_recv().is_some());
1298
1299        // Explicit intercept with no further action when receiver disconnected yields error
1300        let errors = ServoErrorChannel::default();
1301        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
1302        let request = WebResourceLoad::new(web_resource_request(), sender, errors.sender());
1303        drop(receiver);
1304        drop(request.intercept(web_resource_response()));
1305        assert!(errors.try_recv().is_some());
1306
1307        // No response when receiver disconnected yields no error
1308        let errors = ServoErrorChannel::default();
1309        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
1310        let request = WebResourceLoad::new(web_resource_request(), sender, errors.sender());
1311        drop(receiver);
1312        drop(request);
1313        assert!(errors.try_recv().is_none());
1314    }
1315}