aboutsummaryrefslogtreecommitdiffstats
path: root/components/script/dom/browsercontext.rs
blob: f51930f3f633f838f50b40ca86d63bda6953b714 (plain) (blame)
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
/* 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 http://mozilla.org/MPL/2.0/. */

use dom::bindings::conversions::native_from_reflector_jsmanaged;
use dom::bindings::conversions::{ToJSValConvertible};
use dom::bindings::js::{JS, JSRef, Temporary, Root};
use dom::bindings::js::{OptionalRootable, OptionalOptionalRootable};
use dom::bindings::js::{ResultRootable, Rootable};
use dom::bindings::proxyhandler::{get_property_descriptor, fill_property_descriptor};
use dom::bindings::utils::{Reflectable, WindowProxyHandler};
use dom::bindings::utils::get_array_index_from_id;
use dom::document::{Document, DocumentHelpers};
use dom::element::Element;
use dom::window::Window;
use dom::window::WindowHelpers;

use js::jsapi::{JSContext, JSObject, jsid, JSPropertyDescriptor};
use js::jsapi::{JS_AlreadyHasOwnPropertyById, JS_ForwardGetPropertyTo};
use js::jsapi::{JS_GetPropertyDescriptorById, JS_DefinePropertyById};
use js::jsapi::{JS_SetPropertyById};
use js::jsval::JSVal;
use js::glue::{GetProxyPrivate};
use js::glue::{WrapperNew, CreateWrapperProxyHandler, ProxyTraps};
use js::rust::with_compartment;
use js::{JSRESOLVE_QUALIFIED, JSRESOLVE_ASSIGNING};

use std::ptr;

#[allow(raw_pointer_derive)]
#[jstraceable]
#[privatize]
pub struct BrowserContext {
    history: Vec<SessionHistoryEntry>,
    active_index: usize,
    window_proxy: *mut JSObject,
    frame_element: Option<JS<Element>>,
}

impl BrowserContext {
    pub fn new(document: JSRef<Document>, frame_element: Option<JSRef<Element>>) -> BrowserContext {
        let mut context = BrowserContext {
            history: vec!(SessionHistoryEntry::new(document)),
            active_index: 0,
            window_proxy: ptr::null_mut(),
            frame_element: frame_element.map(JS::from_rooted),
        };
        context.create_window_proxy();
        context
    }

    pub fn active_document(&self) -> Temporary<Document> {
        Temporary::from_rooted(self.history[self.active_index].document.clone())
    }

    pub fn active_window(&self) -> Temporary<Window> {
        let doc = self.active_document().root();
        doc.r().window()
    }

    pub fn frame_element(&self) -> Option<Temporary<Element>> {
        self.frame_element.map(Temporary::from_rooted)
    }

    pub fn window_proxy(&self) -> *mut JSObject {
        assert!(!self.window_proxy.is_null());
        self.window_proxy
    }

    #[allow(unsafe_code)]
    fn create_window_proxy(&mut self) {
        let win = self.active_window().root();
        let win = win.r();

        let WindowProxyHandler(handler) = win.windowproxy_handler();
        assert!(!handler.is_null());

        let parent = win.reflector().get_jsobject();
        let cx = win.get_cx();
        let wrapper = with_compartment(cx, parent, || unsafe {
            WrapperNew(cx, parent, handler)
        });
        assert!(!wrapper.is_null());
        self.window_proxy = wrapper;
    }
}

// This isn't a DOM struct, just a convenience struct
// without a reflector, so we don't mark this as #[dom_struct]
#[must_root]
#[privatize]
#[jstraceable]
pub struct SessionHistoryEntry {
    document: JS<Document>,
    children: Vec<BrowserContext>
}

impl SessionHistoryEntry {
    fn new(document: JSRef<Document>) -> SessionHistoryEntry {
        SessionHistoryEntry {
            document: JS::from_rooted(document),
            children: vec!()
        }
    }
}

#[allow(unsafe_code)]
unsafe fn GetSubframeWindow(cx: *mut JSContext, proxy: *mut JSObject, id: jsid) -> Option<Temporary<Window>> {
    let index = get_array_index_from_id(cx, id);
    if let Some(index) = index {
        let target = GetProxyPrivate(proxy).to_object();
        let win: Root<Window> = native_from_reflector_jsmanaged(target).unwrap().root();
        let mut found = false;
        return win.r().IndexedGetter(index, &mut found);
    }

    None
}

#[allow(unsafe_code)]
unsafe extern fn getOwnPropertyDescriptor(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
                                          set: bool, desc: *mut JSPropertyDescriptor) -> bool {
    let window = GetSubframeWindow(cx, proxy, id);
    if let Some(window) = window {
        let window = window.root();
        (*desc).value = window.to_jsval(cx);
        fill_property_descriptor(&mut *desc, proxy, true);
        return true;
    }

    let target = GetProxyPrivate(proxy).to_object();
    let flags = if set { JSRESOLVE_ASSIGNING } else { 0 } | JSRESOLVE_QUALIFIED;
    // XXX This should be JS_GetOwnPropertyDescriptorById
    if JS_GetPropertyDescriptorById(cx, target, id, flags, desc) == 0 {
        return false;
    }

    if (*desc).obj != target {
        // Not an own property
        (*desc).obj = ptr::null_mut();
    } else {
        (*desc).obj = proxy;
    }

    true
}

#[allow(unsafe_code)]
unsafe extern fn defineProperty(cx: *mut JSContext, proxy: *mut JSObject, id: jsid,
                                desc: *mut JSPropertyDescriptor) -> bool {
    if get_array_index_from_id(cx, id).is_some() {
        // Spec says to Reject whether this is a supported index or not,
        // since we have no indexed setter or indexed creator.  That means
        // throwing in strict mode (FIXME: Bug 828137), doing nothing in
        // non-strict mode.
        return true;
    }

    let target = GetProxyPrivate(proxy).to_object();
    JS_DefinePropertyById(cx, target, id, (*desc).value, (*desc).getter,
                          (*desc).setter, (*desc).attrs) != 0
}

#[allow(unsafe_code)]
unsafe extern fn hasOwn(cx: *mut JSContext, proxy: *mut JSObject, id: jsid, bp: *mut bool) -> bool {
    let window = GetSubframeWindow(cx, proxy, id);
    if window.is_some() {
        *bp = true;
        return true;
    }

    let target = GetProxyPrivate(proxy).to_object();
    let mut found = 0;
    if JS_AlreadyHasOwnPropertyById(cx, target, id, &mut found) == 0 {
        return false;
    }

    *bp = found != 0;
    return true;
}

#[allow(unsafe_code)]
unsafe extern fn get(cx: *mut JSContext, proxy: *mut JSObject, receiver: *mut JSObject, id: jsid,
                     vp: *mut JSVal) -> bool {
    let window = GetSubframeWindow(cx, proxy, id);
    if let Some(window) = window {
        let window = window.root();
        *vp = window.to_jsval(cx);
        return true;
    }

    let target = GetProxyPrivate(proxy).to_object();
    JS_ForwardGetPropertyTo(cx, target, id, receiver, vp) != 0
}

#[allow(unsafe_code)]
unsafe extern fn set(cx: *mut JSContext, proxy: *mut JSObject, _receiver: *mut JSObject,
                     id: jsid, _strict: bool, vp: *mut JSVal) -> bool {
    if get_array_index_from_id(cx, id).is_some() {
        // Reject (which means throw if and only if strict) the set.
        // FIXME: Throw
        return true;
    }

    // FIXME: The receiver should be used, we need something like JS_ForwardSetPropertyTo.
    let target = GetProxyPrivate(proxy).to_object();
    JS_SetPropertyById(cx, target, id, vp) != 0
}

static PROXY_HANDLER: ProxyTraps = ProxyTraps {
    getPropertyDescriptor: Some(get_property_descriptor
                                as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, bool,
                                                        *mut JSPropertyDescriptor) -> bool),
    getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor
                                   as unsafe extern "C" fn(*mut JSContext, *mut JSObject,
                                                           jsid, bool, *mut JSPropertyDescriptor)
                                                           -> bool),
    defineProperty: Some(defineProperty as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid,
                                                                *mut JSPropertyDescriptor) -> bool),
    getOwnPropertyNames: None,
    delete_: None,
    enumerate: None,

    has: None,
    hasOwn: Some(hasOwn as unsafe extern "C" fn(*mut JSContext, *mut JSObject, jsid, *mut bool) -> bool),
    get: Some(get as unsafe extern "C" fn(*mut JSContext, *mut JSObject, *mut JSObject, jsid, *mut JSVal) -> bool),
    set: Some(set as unsafe extern "C" fn(*mut JSContext, *mut JSObject, *mut JSObject,
                                          jsid, bool, *mut JSVal) -> bool),
    keys: None,
    iterate: None,

    call: None,
    construct: None,
    nativeCall: 0 as *const u8,
    hasInstance: None,
    typeOf: None,
    objectClassIs: None,
    obj_toString: None,
    fun_toString: None,
    //regexp_toShared: 0 as *u8,
    defaultValue: None,
    iteratorNext: None,
    finalize: None,
    getElementIfPresent: None,
    getPrototypeOf: None,
    trace: None
};

#[allow(unsafe_code)]
pub fn new_window_proxy_handler() -> WindowProxyHandler {
    unsafe {
        WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER))
    }
}