script/
script_window_proxies.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 base::id::{BrowsingContextId, PipelineId, WebViewId};
6use constellation_traits::ScriptToConstellationMessage;
7use ipc_channel::ipc;
8use rustc_hash::FxBuildHasher;
9use script_bindings::inheritance::Castable;
10use script_bindings::root::{Dom, DomRoot};
11use script_bindings::str::DOMString;
12
13use crate::document_collection::DocumentCollection;
14use crate::dom::bindings::cell::DomRefCell;
15use crate::dom::bindings::trace::HashMapTracedValues;
16use crate::dom::node::NodeTraits;
17use crate::dom::types::{GlobalScope, Window};
18use crate::dom::windowproxy::{CreatorBrowsingContextInfo, WindowProxy};
19use crate::messaging::ScriptThreadSenders;
20
21#[derive(JSTraceable, Default, MallocSizeOf)]
22#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_in_rc)]
23#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
24pub(crate) struct ScriptWindowProxies {
25    map: DomRefCell<HashMapTracedValues<BrowsingContextId, Dom<WindowProxy>, FxBuildHasher>>,
26}
27
28impl ScriptWindowProxies {
29    pub(crate) fn find_window_proxy(&self, id: BrowsingContextId) -> Option<DomRoot<WindowProxy>> {
30        self.map
31            .borrow()
32            .get(&id)
33            .map(|context| DomRoot::from_ref(&**context))
34    }
35
36    pub(crate) fn find_window_proxy_by_name(
37        &self,
38        name: &DOMString,
39    ) -> Option<DomRoot<WindowProxy>> {
40        for (_, proxy) in self.map.borrow().iter() {
41            if proxy.get_name() == *name {
42                return Some(DomRoot::from_ref(&**proxy));
43            }
44        }
45        None
46    }
47
48    pub(crate) fn insert(&self, id: BrowsingContextId, proxy: DomRoot<WindowProxy>) {
49        self.map.borrow_mut().insert(id, Dom::from_ref(&*proxy));
50    }
51
52    pub(crate) fn remove(&self, id: BrowsingContextId) {
53        self.map.borrow_mut().remove(&id);
54    }
55
56    // Get the browsing context for a pipeline that may exist in another
57    // script thread.  If the browsing context already exists in the
58    // `window_proxies` map, we return it, otherwise we recursively
59    // get the browsing context for the parent if there is one,
60    // construct a new dissimilar-origin browsing context, add it
61    // to the `window_proxies` map, and return it.
62    pub(crate) fn remote_window_proxy(
63        &self,
64        cx: &mut js::context::JSContext,
65        senders: &ScriptThreadSenders,
66        global_to_clone: &GlobalScope,
67        webview_id: WebViewId,
68        pipeline_id: PipelineId,
69        opener: Option<BrowsingContextId>,
70    ) -> Option<DomRoot<WindowProxy>> {
71        let (browsing_context_id, parent_pipeline_id) =
72            self.ask_constellation_for_browsing_context_info(senders, webview_id, pipeline_id)?;
73        if let Some(window_proxy) = self.find_window_proxy(browsing_context_id) {
74            return Some(window_proxy);
75        }
76
77        let parent_browsing_context = parent_pipeline_id.and_then(|parent_id| {
78            self.remote_window_proxy(cx, senders, global_to_clone, webview_id, parent_id, opener)
79        });
80
81        let opener_browsing_context = opener.and_then(|id| self.find_window_proxy(id));
82
83        let creator = CreatorBrowsingContextInfo::from(
84            parent_browsing_context.as_deref(),
85            opener_browsing_context.as_deref(),
86        );
87
88        let window_proxy = WindowProxy::new_dissimilar_origin(
89            cx,
90            global_to_clone,
91            browsing_context_id,
92            webview_id,
93            parent_browsing_context.as_deref(),
94            opener,
95            creator,
96        );
97        self.insert(browsing_context_id, DomRoot::from_ref(&*window_proxy));
98        Some(window_proxy)
99    }
100
101    // Get the browsing context for a pipeline that exists in this
102    // script thread.  If the browsing context already exists in the
103    // `window_proxies` map, we return it, otherwise we recursively
104    // get the browsing context for the parent if there is one,
105    // construct a new similar-origin browsing context, add it
106    // to the `window_proxies` map, and return it.
107    #[expect(clippy::too_many_arguments)]
108    pub(crate) fn local_window_proxy(
109        &self,
110        cx: &mut js::context::JSContext,
111        senders: &ScriptThreadSenders,
112        documents: &DomRefCell<DocumentCollection>,
113        window: &Window,
114        browsing_context_id: BrowsingContextId,
115        webview_id: WebViewId,
116        parent_info: Option<PipelineId>,
117        opener: Option<BrowsingContextId>,
118    ) -> DomRoot<WindowProxy> {
119        if let Some(window_proxy) = self.find_window_proxy(browsing_context_id) {
120            // Note: we do not set the window to be the currently-active one,
121            // this will be done instead when the script-thread handles the `SetDocumentActivity` msg.
122            return window_proxy;
123        }
124        let iframe = parent_info.and_then(|parent_id| {
125            documents
126                .borrow()
127                .find_iframe(parent_id, browsing_context_id)
128        });
129        let parent_browsing_context = match (parent_info, iframe.as_ref()) {
130            (_, Some(iframe)) => Some(iframe.owner_window().window_proxy()),
131            (Some(parent_id), _) => self.remote_window_proxy(
132                cx,
133                senders,
134                window.upcast(),
135                webview_id,
136                parent_id,
137                opener,
138            ),
139            _ => None,
140        };
141
142        let opener_browsing_context = opener.and_then(|id| self.find_window_proxy(id));
143
144        let creator = CreatorBrowsingContextInfo::from(
145            parent_browsing_context.as_deref(),
146            opener_browsing_context.as_deref(),
147        );
148
149        let window_proxy = WindowProxy::new(
150            window,
151            browsing_context_id,
152            webview_id,
153            iframe.as_deref().map(Castable::upcast),
154            parent_browsing_context.as_deref(),
155            opener,
156            creator,
157        );
158        self.insert(browsing_context_id, DomRoot::from_ref(&*window_proxy));
159        window_proxy
160    }
161
162    fn ask_constellation_for_browsing_context_info(
163        &self,
164        senders: &ScriptThreadSenders,
165        webview_id: WebViewId,
166        pipeline_id: PipelineId,
167    ) -> Option<(BrowsingContextId, Option<PipelineId>)> {
168        let (result_sender, result_receiver) = ipc::channel().unwrap();
169        let msg = ScriptToConstellationMessage::GetBrowsingContextInfo(pipeline_id, result_sender);
170        senders
171            .pipeline_to_constellation_sender
172            .send((webview_id, pipeline_id, msg))
173            .expect("Failed to send to constellation.");
174        result_receiver
175            .recv()
176            .expect("Failed to get browsing context info from constellation.")
177    }
178}