script/dom/
document_embedder_controls.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::cell::Cell;
6
7use base::Epoch;
8use base::generic_channel::GenericSend;
9use constellation_traits::{LoadData, NavigationHistoryBehavior};
10use embedder_traits::{
11    ContextMenuAction, ContextMenuElementInformation, ContextMenuElementInformationFlags,
12    ContextMenuItem, ContextMenuRequest, EditingActionEvent, EmbedderControlId,
13    EmbedderControlRequest, EmbedderControlResponse, EmbedderMsg,
14};
15use euclid::{Point2D, Rect, Size2D};
16use ipc_channel::router::ROUTER;
17use net_traits::CoreResourceMsg;
18use net_traits::filemanager_thread::FileManagerThreadMsg;
19use rustc_hash::FxHashMap;
20use script_bindings::codegen::GenericBindings::HTMLAnchorElementBinding::HTMLAnchorElementMethods;
21use script_bindings::codegen::GenericBindings::HTMLImageElementBinding::HTMLImageElementMethods;
22use script_bindings::codegen::GenericBindings::HistoryBinding::HistoryMethods;
23use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
24use script_bindings::inheritance::Castable;
25use script_bindings::root::{Dom, DomRoot};
26use script_bindings::script_runtime::CanGc;
27use servo_url::ServoUrl;
28use webrender_api::units::{DeviceIntRect, DevicePoint};
29
30use crate::dom::activation::Activatable;
31use crate::dom::bindings::cell::DomRefCell;
32use crate::dom::bindings::refcounted::Trusted;
33use crate::dom::bindings::trace::NoTrace;
34use crate::dom::inputevent::HitTestResult;
35use crate::dom::node::{Node, NodeTraits, ShadowIncluding};
36use crate::dom::textcontrol::TextControlElement;
37use crate::dom::types::{
38    Element, HTMLAnchorElement, HTMLElement, HTMLImageElement, HTMLInputElement, HTMLSelectElement,
39    HTMLTextAreaElement, Window,
40};
41use crate::messaging::MainThreadScriptMsg;
42
43#[derive(JSTraceable, MallocSizeOf)]
44pub(crate) enum ControlElement {
45    Select(DomRoot<HTMLSelectElement>),
46    ColorInput(DomRoot<HTMLInputElement>),
47    FileInput(DomRoot<HTMLInputElement>),
48    Ime(DomRoot<HTMLElement>),
49    ContextMenu(ContextMenuNodes),
50}
51
52impl ControlElement {
53    fn node(&self) -> &Node {
54        match self {
55            ControlElement::Select(element) => element.upcast::<Node>(),
56            ControlElement::ColorInput(element) => element.upcast::<Node>(),
57            ControlElement::FileInput(element) => element.upcast::<Node>(),
58            ControlElement::Ime(element) => element.upcast::<Node>(),
59            ControlElement::ContextMenu(context_menu_nodes) => &context_menu_nodes.node,
60        }
61    }
62}
63
64#[derive(JSTraceable, MallocSizeOf)]
65#[cfg_attr(crown, expect(crown::unrooted_must_root))]
66pub(crate) struct DocumentEmbedderControls {
67    /// The [`Window`] element for this [`DocumentUserInterfaceElements`].
68    window: Dom<Window>,
69    /// The id of the next user interface element that the `Document` requests that the
70    /// embedder show. This is used to track user interface elements in the API.
71    #[no_trace]
72    user_interface_element_index: Cell<Epoch>,
73    /// A map of visible user interface elements.
74    visible_elements: DomRefCell<FxHashMap<NoTrace<Epoch>, ControlElement>>,
75}
76
77impl DocumentEmbedderControls {
78    pub fn new(window: &Window) -> Self {
79        Self {
80            window: Dom::from_ref(window),
81            user_interface_element_index: Default::default(),
82            visible_elements: Default::default(),
83        }
84    }
85
86    /// Generate the next unused [`EmbedderControlId`]. This method is only needed for some older
87    /// types of controls that are still being migrated, and it will eventually be removed.
88    pub(crate) fn next_control_id(&self) -> EmbedderControlId {
89        let index = self.user_interface_element_index.get();
90        self.user_interface_element_index.set(index.next());
91        EmbedderControlId {
92            webview_id: self.window.webview_id(),
93            pipeline_id: self.window.pipeline_id(),
94            index,
95        }
96    }
97
98    pub(crate) fn show_embedder_control(
99        &self,
100        element: ControlElement,
101        request: EmbedderControlRequest,
102        point: Option<DevicePoint>,
103    ) -> EmbedderControlId {
104        let id = self.next_control_id();
105        let rect = point
106            .map(|point| DeviceIntRect::from_origin_and_size(point.to_i32(), Size2D::zero()))
107            .unwrap_or_else(|| {
108                let rect = element
109                    .node()
110                    .upcast::<Node>()
111                    .border_box()
112                    .unwrap_or_default();
113
114                let rect = Rect::new(
115                    Point2D::new(rect.origin.x.to_px(), rect.origin.y.to_px()),
116                    Size2D::new(rect.size.width.to_px(), rect.size.height.to_px()),
117                );
118
119                // FIXME: This is a CSS pixel rect relative to this frame, we need a DevicePixel rectangle
120                // relative to the entire WebView!
121                DeviceIntRect::from_untyped(&rect.to_box2d())
122            });
123
124        self.visible_elements
125            .borrow_mut()
126            .insert(id.index.into(), element);
127
128        match request {
129            EmbedderControlRequest::SelectElement(..) |
130            EmbedderControlRequest::ColorPicker(..) |
131            EmbedderControlRequest::InputMethod(..) |
132            EmbedderControlRequest::ContextMenu(..) => self
133                .window
134                .send_to_embedder(EmbedderMsg::ShowEmbedderControl(id, rect, request)),
135            EmbedderControlRequest::FilePicker(file_picker_request) => {
136                let (sender, receiver) = profile_traits::ipc::channel(
137                    self.window.as_global_scope().time_profiler_chan().clone(),
138                )
139                .expect("Error initializing channel");
140                let main_thread_sender = self.window.main_thread_script_chan().clone();
141                ROUTER.add_typed_route(
142                    receiver.to_ipc_receiver(),
143                    Box::new(move |result| {
144                        let Ok(embedder_control_response) = result else {
145                            return;
146                        };
147                        if let Err(error) = main_thread_sender.send(
148                            MainThreadScriptMsg::ForwardEmbedderControlResponseFromFileManager(
149                                id,
150                                embedder_control_response,
151                            ),
152                        ) {
153                            warn!("Could not send FileManager response to main thread: {error}")
154                        }
155                    }),
156                );
157                self.window
158                    .as_global_scope()
159                    .resource_threads()
160                    .sender()
161                    .send(CoreResourceMsg::ToFileManager(
162                        FileManagerThreadMsg::SelectFiles(id, file_picker_request, sender),
163                    ))
164                    .unwrap();
165            },
166        }
167
168        id
169    }
170
171    pub(crate) fn hide_embedder_control(&self, element: &Element) {
172        self.visible_elements
173            .borrow_mut()
174            .retain(|index, control_element| {
175                if control_element.node() != element.upcast() {
176                    return true;
177                }
178                let id = EmbedderControlId {
179                    webview_id: self.window.webview_id(),
180                    pipeline_id: self.window.pipeline_id(),
181                    index: index.0,
182                };
183                self.window
184                    .send_to_embedder(EmbedderMsg::HideEmbedderControl(id));
185                false
186            });
187    }
188
189    pub(crate) fn handle_embedder_control_response(
190        &self,
191        id: EmbedderControlId,
192        response: EmbedderControlResponse,
193        can_gc: CanGc,
194    ) {
195        assert_eq!(self.window.pipeline_id(), id.pipeline_id);
196        assert_eq!(self.window.webview_id(), id.webview_id);
197
198        let Some(element) = self.visible_elements.borrow_mut().remove(&id.index.into()) else {
199            return;
200        };
201
202        // Never process embedder responses on inactive `Document`s.
203        if !element.node().owner_doc().is_active() {
204            return;
205        }
206
207        match (element, response) {
208            (
209                ControlElement::Select(select_element),
210                EmbedderControlResponse::SelectElement(response),
211            ) => {
212                select_element.handle_menu_response(response, can_gc);
213            },
214            (
215                ControlElement::ColorInput(input_element),
216                EmbedderControlResponse::ColorPicker(response),
217            ) => {
218                input_element.handle_color_picker_response(response, can_gc);
219            },
220            (
221                ControlElement::FileInput(input_element),
222                EmbedderControlResponse::FilePicker(response),
223            ) => {
224                input_element.handle_file_picker_response(response, can_gc);
225            },
226            (
227                ControlElement::ContextMenu(context_menu_nodes),
228                EmbedderControlResponse::ContextMenu(action),
229            ) => {
230                context_menu_nodes.handle_context_menu_action(action, can_gc);
231            },
232            (_, _) => unreachable!(
233                "The response to a form control should always match it's originating type."
234            ),
235        }
236    }
237
238    pub(crate) fn show_context_menu(&self, hit_test_result: &HitTestResult) {
239        let mut anchor_element = None;
240        let mut image_element = None;
241        let mut text_input_element = None;
242        for node in hit_test_result
243            .node
244            .inclusive_ancestors(ShadowIncluding::Yes)
245        {
246            if anchor_element.is_none() {
247                if let Some(candidate_anchor_element) = node.downcast::<HTMLAnchorElement>() {
248                    if candidate_anchor_element.is_instance_activatable() {
249                        anchor_element = Some(DomRoot::from_ref(candidate_anchor_element));
250                    }
251                }
252            }
253
254            if image_element.is_none() {
255                if let Some(candidate_image_element) = node.downcast::<HTMLImageElement>() {
256                    image_element = Some(DomRoot::from_ref(candidate_image_element))
257                }
258            }
259
260            if text_input_element.is_none() {
261                if let Some(candidate_text_input_element) = node.as_text_input() {
262                    text_input_element = Some(candidate_text_input_element);
263                }
264            }
265        }
266
267        let mut info = ContextMenuElementInformation::default();
268        let mut items = Vec::new();
269        if let Some(anchor_element) = anchor_element.as_ref() {
270            info.flags.insert(ContextMenuElementInformationFlags::Link);
271            info.link_url = anchor_element
272                .full_href_url_for_user_interface()
273                .map(ServoUrl::into_url);
274
275            items.extend(vec![
276                ContextMenuItem::Item {
277                    label: "Open Link in New View".into(),
278                    action: ContextMenuAction::OpenLinkInNewWebView,
279                    enabled: true,
280                },
281                ContextMenuItem::Item {
282                    label: "Copy Link".into(),
283                    action: ContextMenuAction::CopyLink,
284                    enabled: true,
285                },
286                ContextMenuItem::Separator,
287            ]);
288        }
289
290        if let Some(image_element) = image_element.as_ref() {
291            info.flags.insert(ContextMenuElementInformationFlags::Image);
292            info.image_url = image_element
293                .full_image_url_for_user_interface()
294                .map(ServoUrl::into_url);
295
296            items.extend(vec![
297                ContextMenuItem::Item {
298                    label: "Open Image in New View".into(),
299                    action: ContextMenuAction::OpenImageInNewView,
300                    enabled: true,
301                },
302                ContextMenuItem::Item {
303                    label: "Copy Image Link".into(),
304                    action: ContextMenuAction::CopyImageLink,
305                    enabled: true,
306                },
307                ContextMenuItem::Separator,
308            ]);
309        }
310
311        if let Some(text_input_element) = &text_input_element {
312            let has_selection = text_input_element.has_uncollapsed_selection();
313
314            info.flags
315                .insert(ContextMenuElementInformationFlags::EditableText);
316            if has_selection {
317                info.flags
318                    .insert(ContextMenuElementInformationFlags::Selection);
319            }
320
321            items.extend(vec![
322                ContextMenuItem::Item {
323                    label: "Cut".into(),
324                    action: ContextMenuAction::Cut,
325                    enabled: has_selection,
326                },
327                ContextMenuItem::Item {
328                    label: "Copy".into(),
329                    action: ContextMenuAction::Copy,
330                    enabled: has_selection,
331                },
332                ContextMenuItem::Item {
333                    label: "Paste".into(),
334                    action: ContextMenuAction::Paste,
335                    enabled: true,
336                },
337                ContextMenuItem::Item {
338                    label: "Select All".into(),
339                    action: ContextMenuAction::SelectAll,
340                    enabled: text_input_element.has_selectable_text(),
341                },
342                ContextMenuItem::Separator,
343            ]);
344        }
345
346        items.extend(vec![
347            ContextMenuItem::Item {
348                label: "Back".into(),
349                action: ContextMenuAction::GoBack,
350                enabled: true,
351            },
352            ContextMenuItem::Item {
353                label: "Forward".into(),
354                action: ContextMenuAction::GoForward,
355                enabled: true,
356            },
357            ContextMenuItem::Item {
358                label: "Reload".into(),
359                action: ContextMenuAction::Reload,
360                enabled: true,
361            },
362        ]);
363
364        let context_menu_nodes = ContextMenuNodes {
365            node: hit_test_result.node.clone(),
366            anchor_element,
367            image_element,
368            text_input_element,
369        };
370
371        self.show_embedder_control(
372            ControlElement::ContextMenu(context_menu_nodes),
373            EmbedderControlRequest::ContextMenu(ContextMenuRequest {
374                element_info: info,
375                items,
376            }),
377            Some(hit_test_result.point_in_frame.cast_unit()),
378        );
379    }
380}
381
382#[derive(JSTraceable, MallocSizeOf)]
383pub(crate) struct ContextMenuNodes {
384    /// The node that this menu was triggered on.
385    node: DomRoot<Node>,
386    /// The first inclusive ancestor of this node that is an `<a>` if one exists.
387    anchor_element: Option<DomRoot<HTMLAnchorElement>>,
388    /// The first inclusive ancestor of this node that is an `<img>` if one exists.
389    image_element: Option<DomRoot<HTMLImageElement>>,
390    /// The first inclusive ancestor of this node which is a text entry field.
391    text_input_element: Option<DomRoot<Element>>,
392}
393
394impl ContextMenuNodes {
395    fn handle_context_menu_action(&self, action: Option<ContextMenuAction>, can_gc: CanGc) {
396        let Some(action) = action else {
397            return;
398        };
399
400        let window = self.node.owner_window();
401        let document = window.Document();
402        let set_clipboard_text = |string: String| {
403            if string.is_empty() {
404                return;
405            }
406            window.send_to_embedder(EmbedderMsg::SetClipboardText(window.webview_id(), string));
407        };
408
409        let open_url_in_new_webview = |url: ServoUrl| {
410            let Some(browsing_context) = document.browsing_context() else {
411                return;
412            };
413            let (browsing_context, new) = browsing_context
414                .choose_browsing_context("_blank".into(), true /* nooopener */);
415            let Some(browsing_context) = browsing_context else {
416                return;
417            };
418            assert!(new);
419            let Some(target_document) = browsing_context.document() else {
420                return;
421            };
422
423            let target_window = target_document.window();
424            let target = Trusted::new(target_window);
425            let load_data = LoadData::new_for_new_unrelated_webview(url);
426            let task = task!(open_link_in_new_webview: move || {
427                target.root().load_url(NavigationHistoryBehavior::Replace, false, load_data, CanGc::note());
428            });
429            target_document
430                .owner_global()
431                .task_manager()
432                .dom_manipulation_task_source()
433                .queue(task);
434        };
435
436        match action {
437            ContextMenuAction::GoBack => {
438                let _ = window.History().Back();
439            },
440            ContextMenuAction::GoForward => {
441                let _ = window.History().Forward();
442            },
443            ContextMenuAction::Reload => {
444                window.Location().reload_without_origin_check(can_gc);
445            },
446            ContextMenuAction::CopyLink => {
447                let Some(anchor_element) = &self.anchor_element else {
448                    return;
449                };
450
451                let url_string = anchor_element
452                    .full_href_url_for_user_interface()
453                    .as_ref()
454                    .map(ServoUrl::to_string)
455                    .unwrap_or_else(|| anchor_element.Href().to_string());
456                set_clipboard_text(url_string);
457            },
458            ContextMenuAction::OpenLinkInNewWebView => {
459                let Some(anchor_element) = &self.anchor_element else {
460                    return;
461                };
462                if let Some(url) = anchor_element.full_href_url_for_user_interface() {
463                    open_url_in_new_webview(url);
464                };
465            },
466            ContextMenuAction::CopyImageLink => {
467                let Some(image_element) = &self.image_element else {
468                    return;
469                };
470                let url_string = image_element
471                    .full_image_url_for_user_interface()
472                    .as_ref()
473                    .map(ServoUrl::to_string)
474                    .unwrap_or_else(|| image_element.CurrentSrc().to_string());
475                set_clipboard_text(url_string.to_string());
476            },
477            ContextMenuAction::OpenImageInNewView => {
478                let Some(image_element) = &self.image_element else {
479                    return;
480                };
481                if let Some(url) = image_element.full_image_url_for_user_interface() {
482                    open_url_in_new_webview(url);
483                }
484            },
485            ContextMenuAction::Cut => {
486                window.Document().event_handler().handle_editing_action(
487                    self.text_input_element.clone(),
488                    EditingActionEvent::Cut,
489                    can_gc,
490                );
491            },
492            ContextMenuAction::Copy => {
493                window.Document().event_handler().handle_editing_action(
494                    self.text_input_element.clone(),
495                    EditingActionEvent::Copy,
496                    can_gc,
497                );
498            },
499            ContextMenuAction::Paste => {
500                window.Document().event_handler().handle_editing_action(
501                    self.text_input_element.clone(),
502                    EditingActionEvent::Paste,
503                    can_gc,
504                );
505            },
506            ContextMenuAction::SelectAll => {
507                if let Some(text_input_element) = &self.text_input_element {
508                    text_input_element.select_all();
509                }
510            },
511        }
512    }
513}
514
515impl Node {
516    fn as_text_input(&self) -> Option<DomRoot<Element>> {
517        if let Some(input_element) = self
518            .downcast::<HTMLInputElement>()
519            .filter(|input_element| input_element.renders_as_text_input_widget())
520        {
521            return Some(DomRoot::from_ref(input_element.upcast::<Element>()));
522        }
523        self.downcast::<HTMLTextAreaElement>()
524            .map(Castable::upcast)
525            .map(DomRoot::from_ref)
526    }
527}
528
529impl Element {
530    fn has_uncollapsed_selection(&self) -> bool {
531        self.downcast::<HTMLTextAreaElement>()
532            .map(TextControlElement::has_uncollapsed_selection)
533            .or(self
534                .downcast::<HTMLInputElement>()
535                .map(TextControlElement::has_uncollapsed_selection))
536            .unwrap_or_default()
537    }
538
539    fn has_selectable_text(&self) -> bool {
540        self.downcast::<HTMLTextAreaElement>()
541            .map(TextControlElement::has_selectable_text)
542            .or(self
543                .downcast::<HTMLInputElement>()
544                .map(TextControlElement::has_selectable_text))
545            .unwrap_or_default()
546    }
547
548    fn select_all(&self) {
549        self.downcast::<HTMLTextAreaElement>()
550            .map(TextControlElement::select_all)
551            .or(self
552                .downcast::<HTMLInputElement>()
553                .map(TextControlElement::select_all))
554            .unwrap_or_default()
555    }
556}