servo/
webview_delegate.rs

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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use std::path::PathBuf;

use base::id::PipelineId;
use compositing_traits::ConstellationMsg;
use embedder_traits::{
    AllowOrDeny, AuthenticationResponse, ContextMenuResult, Cursor, FilterPattern,
    GamepadHapticEffectType, InputMethodType, LoadStatus, MediaSessionEvent, PermissionFeature,
    SimpleDialog, WebResourceRequest, WebResourceResponse, WebResourceResponseMsg,
};
use ipc_channel::ipc::IpcSender;
use keyboard_types::KeyboardEvent;
use serde::Serialize;
use url::Url;
use webrender_api::units::{DeviceIntPoint, DeviceIntRect, DeviceIntSize};

use crate::{ConstellationProxy, WebView};

/// A request to navigate a [`WebView`] or one of its inner frames. This can be handled
/// asynchronously. If not handled, the request will automatically be allowed.
pub struct NavigationRequest {
    pub url: Url,
    pub(crate) pipeline_id: PipelineId,
    pub(crate) constellation_proxy: ConstellationProxy,
    pub(crate) response_sent: bool,
}

impl NavigationRequest {
    pub fn allow(mut self) {
        self.constellation_proxy
            .send(ConstellationMsg::AllowNavigationResponse(
                self.pipeline_id,
                true,
            ));
        self.response_sent = true;
    }

    pub fn deny(mut self) {
        self.constellation_proxy
            .send(ConstellationMsg::AllowNavigationResponse(
                self.pipeline_id,
                false,
            ));
        self.response_sent = true;
    }
}

impl Drop for NavigationRequest {
    fn drop(&mut self) {
        if !self.response_sent {
            self.constellation_proxy
                .send(ConstellationMsg::AllowNavigationResponse(
                    self.pipeline_id,
                    true,
                ));
        }
    }
}

/// Sends a response over an IPC channel, or a default response on [`Drop`] if no response was sent.
pub(crate) struct IpcResponder<T: Serialize> {
    response_sender: IpcSender<T>,
    response_sent: bool,
    /// Always present, except when taken by [`Drop`].
    default_response: Option<T>,
}

impl<T: Serialize> IpcResponder<T> {
    pub(crate) fn new(response_sender: IpcSender<T>, default_response: T) -> Self {
        Self {
            response_sender,
            response_sent: false,
            default_response: Some(default_response),
        }
    }

    pub(crate) fn send(&mut self, response: T) -> bincode::Result<()> {
        let result = self.response_sender.send(response);
        self.response_sent = true;
        result
    }

    pub(crate) fn into_inner(self) -> IpcSender<T> {
        self.response_sender.clone()
    }
}

impl<T: Serialize> Drop for IpcResponder<T> {
    fn drop(&mut self) {
        if !self.response_sent {
            let response = self
                .default_response
                .take()
                .expect("Guaranteed by inherent impl");
            let _ = self.response_sender.send(response);
        }
    }
}

/// A permissions request for a [`WebView`] The embedder should allow or deny the request,
/// either by reading a cached value or querying the user for permission via the user
/// interface.
pub struct PermissionRequest {
    pub(crate) requested_feature: PermissionFeature,
    pub(crate) allow_deny_request: AllowOrDenyRequest,
}

impl PermissionRequest {
    pub fn feature(&self) -> PermissionFeature {
        self.requested_feature
    }

    pub fn allow(self) {
        self.allow_deny_request.allow();
    }

    pub fn deny(self) {
        self.allow_deny_request.deny();
    }
}

pub struct AllowOrDenyRequest(IpcResponder<AllowOrDeny>);

impl AllowOrDenyRequest {
    pub(crate) fn new(
        response_sender: IpcSender<AllowOrDeny>,
        default_response: AllowOrDeny,
    ) -> Self {
        Self(IpcResponder::new(response_sender, default_response))
    }

    pub fn allow(mut self) {
        let _ = self.0.send(AllowOrDeny::Allow);
    }

    pub fn deny(mut self) {
        let _ = self.0.send(AllowOrDeny::Deny);
    }
}

/// A request to authenticate a [`WebView`] navigation. Embedders may choose to prompt
/// the user to enter credentials or simply ignore this request (in which case credentials
/// will not be used).
pub struct AuthenticationRequest {
    pub(crate) url: Url,
    pub(crate) for_proxy: bool,
    pub(crate) responder: IpcResponder<Option<AuthenticationResponse>>,
}

impl AuthenticationRequest {
    pub(crate) fn new(
        url: Url,
        for_proxy: bool,
        response_sender: IpcSender<Option<AuthenticationResponse>>,
    ) -> Self {
        Self {
            url,
            for_proxy,
            responder: IpcResponder::new(response_sender, None),
        }
    }

    /// The URL of the request that triggered this authentication.
    pub fn url(&self) -> &Url {
        &self.url
    }
    /// Whether or not this authentication request is associated with a proxy server authentication.
    pub fn for_proxy(&self) -> bool {
        self.for_proxy
    }
    /// Respond to the [`AuthenticationRequest`] with the given username and password.
    pub fn authenticate(mut self, username: String, password: String) {
        let _ = self
            .responder
            .send(Some(AuthenticationResponse { username, password }));
    }
}

/// Information related to the loading of a web resource. These are created for all HTTP requests.
/// The client may choose to intercept the load of web resources and send an alternate response
/// by calling [`WebResourceLoad::intercept`].
pub struct WebResourceLoad {
    pub request: WebResourceRequest,
    pub(crate) responder: IpcResponder<WebResourceResponseMsg>,
}

impl WebResourceLoad {
    pub(crate) fn new(
        web_resource_request: WebResourceRequest,
        response_sender: IpcSender<WebResourceResponseMsg>,
    ) -> Self {
        Self {
            request: web_resource_request,
            responder: IpcResponder::new(response_sender, WebResourceResponseMsg::DoNotIntercept),
        }
    }

    /// The [`WebResourceRequest`] associated with this [`WebResourceLoad`].
    pub fn request(&self) -> &WebResourceRequest {
        &self.request
    }
    /// Intercept this [`WebResourceLoad`] and control the response via the returned
    /// [`InterceptedWebResourceLoad`].
    pub fn intercept(mut self, response: WebResourceResponse) -> InterceptedWebResourceLoad {
        let _ = self.responder.send(WebResourceResponseMsg::Start(response));
        InterceptedWebResourceLoad {
            request: self.request.clone(),
            response_sender: self.responder.into_inner(),
            finished: false,
        }
    }
}

/// An intercepted web resource load. This struct allows the client to send an alternative response
/// after calling [`WebResourceLoad::intercept`]. In order to send chunks of body data, the client
/// must call [`InterceptedWebResourceLoad::send_body_data`]. When the interception is complete, the client
/// should call [`InterceptedWebResourceLoad::finish`]. If neither `finish()` or `cancel()` are called,
/// this interception will automatically be finished when dropped.
pub struct InterceptedWebResourceLoad {
    pub request: WebResourceRequest,
    pub(crate) response_sender: IpcSender<WebResourceResponseMsg>,
    pub(crate) finished: bool,
}

impl InterceptedWebResourceLoad {
    /// Send a chunk of response body data. It's possible to make subsequent calls to
    /// this method when streaming body data.
    pub fn send_body_data(&self, data: Vec<u8>) {
        let _ = self
            .response_sender
            .send(WebResourceResponseMsg::SendBodyData(data));
    }
    /// Finish this [`InterceptedWebResourceLoad`] and complete the response.
    pub fn finish(mut self) {
        let _ = self
            .response_sender
            .send(WebResourceResponseMsg::FinishLoad);
        self.finished = true;
    }
    /// Cancel this [`InterceptedWebResourceLoad`], which will trigger a network error.
    pub fn cancel(mut self) {
        let _ = self
            .response_sender
            .send(WebResourceResponseMsg::CancelLoad);
        self.finished = true;
    }
}

impl Drop for InterceptedWebResourceLoad {
    fn drop(&mut self) {
        if !self.finished {
            let _ = self
                .response_sender
                .send(WebResourceResponseMsg::FinishLoad);
        }
    }
}

pub trait WebViewDelegate {
    /// The URL of the currently loaded page in this [`WebView`] has changed. The new
    /// URL can accessed via [`WebView::url`].
    fn notify_url_changed(&self, _webview: WebView, _url: Url) {}
    /// The page title of the currently loaded page in this [`WebView`] has changed. The new
    /// title can accessed via [`WebView::page_title`].
    fn notify_page_title_changed(&self, _webview: WebView, _title: Option<String>) {}
    /// The status text of the currently loaded page in this [`WebView`] has changed. The new
    /// status text can accessed via [`WebView::status_text`].
    fn notify_status_text_changed(&self, _webview: WebView, _status: Option<String>) {}
    /// This [`WebView`] has either become focused or lost focus. Whether or not the
    /// [`WebView`] is focused can be accessed via [`WebView::focused`].
    fn notify_focus_changed(&self, _webview: WebView, _focused: bool) {}
    /// The `LoadStatus` of the currently loading or loaded page in this [`WebView`] has changed. The new
    /// status can accessed via [`WebView::load_status`].
    fn notify_load_status_changed(&self, _webview: WebView, _status: LoadStatus) {}
    /// The [`Cursor`] of the currently loaded page in this [`WebView`] has changed. The new
    /// cursor can accessed via [`WebView::cursor`].
    fn notify_cursor_changed(&self, _webview: WebView, _: Cursor) {}
    /// The favicon [`Url`] of the currently loaded page in this [`WebView`] has changed. The new
    /// favicon [`Url`] can accessed via [`WebView::favicon_url`].
    fn notify_favicon_url_changed(&self, _webview: WebView, _: Url) {}

    /// Notify the embedder that it needs to present a new frame.
    fn notify_new_frame_ready(&self, _webview: WebView) {}
    /// The history state has changed.
    // changed pattern; maybe wasteful if embedder doesn’t care?
    fn notify_history_changed(&self, _webview: WebView, _: Vec<Url>, _: usize) {}
    /// Page content has closed this [`WebView`] via `window.close()`. It's the embedder's
    /// responsibility to remove the [`WebView`] from the interface when this notification
    /// occurs.
    fn notify_closed(&self, _webview: WebView) {}

    /// A keyboard event has been sent to Servo, but remains unprocessed. This allows the
    /// embedding application to handle key events while first letting the [`WebView`]
    /// have an opportunity to handle it first. Apart from builtin keybindings, page
    /// content may expose custom keybindings as well.
    fn notify_keyboard_event(&self, _webview: WebView, _: KeyboardEvent) {}
    /// A pipeline in the webview panicked. First string is the reason, second one is the backtrace.
    fn notify_crashed(&self, _webview: WebView, _reason: String, _backtrace: Option<String>) {}
    /// Notifies the embedder about media session events
    /// (i.e. when there is metadata for the active media session, playback state changes...).
    fn notify_media_session_event(&self, _webview: WebView, _event: MediaSessionEvent) {}
    /// A notification that the [`WebView`] has entered or exited fullscreen mode. This is an
    /// opportunity for the embedder to transition the containing window into or out of fullscreen
    /// mode and to show or hide extra UI elements. Regardless of how the notification is handled,
    /// the page will enter or leave fullscreen state internally according to the [Fullscreen
    /// API](https://fullscreen.spec.whatwg.org/).
    fn notify_fullscreen_state_changed(&self, _webview: WebView, _: bool) {}

    /// Whether or not to allow a [`WebView`] to load a URL in its main frame or one of its
    /// nested `<iframe>`s. [`NavigationRequest`]s are accepted by default.
    fn request_navigation(&self, _webview: WebView, _navigation_request: NavigationRequest) {}
    /// Whether or not to allow a [`WebView`]  to unload a `Document` in its main frame or one
    /// of its nested `<iframe>`s. By default, unloads are allowed.
    fn request_unload(&self, _webview: WebView, _unload_request: AllowOrDenyRequest) {}
    /// Move the window to a point
    fn request_move_to(&self, _webview: WebView, _: DeviceIntPoint) {}
    /// Resize the window to size
    fn request_resize_to(&self, _webview: WebView, _: DeviceIntSize) {}
    /// Whether or not to allow script to open a new `WebView`. If not handled by the
    /// embedder, these requests are automatically denied.
    fn request_open_auxiliary_webview(&self, _parent_webview: WebView) -> Option<WebView> {
        None
    }

    /// Content in a [`WebView`] is requesting permission to access a feature requiring
    /// permission from the user. The embedder should allow or deny the request, either by
    /// reading a cached value or querying the user for permission via the user interface.
    fn request_permission(&self, _webview: WebView, _: PermissionRequest) {}

    fn request_authentication(
        &self,
        _webview: WebView,
        _authentication_request: AuthenticationRequest,
    ) {
    }

    /// Show the user a [simple dialog](https://html.spec.whatwg.org/multipage/#simple-dialogs) (`alert()`, `confirm()`,
    /// or `prompt()`). Since their messages are controlled by web content, they should be presented to the user in a
    /// way that makes them impossible to mistake for browser UI.
    /// TODO: This API needs to be reworked to match the new model of how responses are sent.
    fn show_simple_dialog(&self, _webview: WebView, dialog: SimpleDialog) {
        // Return the DOM-specified default value for when we **cannot show simple dialogs**.
        let _ = match dialog {
            SimpleDialog::Alert {
                response_sender, ..
            } => response_sender.send(Default::default()),
            SimpleDialog::Confirm {
                response_sender, ..
            } => response_sender.send(Default::default()),
            SimpleDialog::Prompt {
                response_sender, ..
            } => response_sender.send(Default::default()),
        };
    }

    /// Show a context menu to the user
    fn show_context_menu(
        &self,
        _webview: WebView,
        result_sender: IpcSender<ContextMenuResult>,
        _: Option<String>,
        _: Vec<String>,
    ) {
        let _ = result_sender.send(ContextMenuResult::Ignored);
    }

    /// Open dialog to select bluetooth device.
    /// TODO: This API needs to be reworked to match the new model of how responses are sent.
    fn show_bluetooth_device_dialog(
        &self,
        _webview: WebView,
        _: Vec<String>,
        response_sender: IpcSender<Option<String>>,
    ) {
        let _ = response_sender.send(None);
    }

    /// Open file dialog to select files. Set boolean flag to true allows to select multiple files.
    fn show_file_selection_dialog(
        &self,
        _webview: WebView,
        _filter_pattern: Vec<FilterPattern>,
        _allow_select_mutiple: bool,
        response_sender: IpcSender<Option<Vec<PathBuf>>>,
    ) {
        let _ = response_sender.send(None);
    }

    /// Request to present an IME to the user when an editable element is focused.
    /// If `type` is [`InputMethodType::Text`], then the `text` parameter specifies
    /// the pre-existing text content and the zero-based index into the string
    /// of the insertion point.
    fn show_ime(
        &self,
        _webview: WebView,
        _type: InputMethodType,
        _text: Option<(String, i32)>,
        _multiline: bool,
        _position: DeviceIntRect,
    ) {
    }

    /// Request to hide the IME when the editable element is blurred.
    fn hide_ime(&self, _webview: WebView) {}

    /// Request to play a haptic effect on a connected gamepad.
    fn play_gamepad_haptic_effect(
        &self,
        _webview: WebView,
        _: usize,
        _: GamepadHapticEffectType,
        _: IpcSender<bool>,
    ) {
    }
    /// Request to stop a haptic effect on a connected gamepad.
    fn stop_gamepad_haptic_effect(&self, _webview: WebView, _: usize, _: IpcSender<bool>) {}

    /// Triggered when this [`WebView`] will load a web (HTTP/HTTPS) resource. The load may be
    /// intercepted and alternate contents can be loaded by the client by calling
    /// [`WebResourceLoad::intercept`]. If not handled, the load will continue as normal.
    ///
    /// Note: This delegate method is called for all resource loads associated with a [`WebView`].
    /// For loads not associated with a [`WebView`], such as those for service workers, Servo
    /// will call [`crate::ServoDelegate::load_web_resource`].
    fn load_web_resource(&self, _webview: WebView, _load: WebResourceLoad) {}
}

pub(crate) struct DefaultWebViewDelegate;
impl WebViewDelegate for DefaultWebViewDelegate {}