Skip to main content

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