Convert CGTraitInterface to use safe JSContext instead of raw JSContext

This commit is contained in:
marmeladema 2019-07-22 01:09:24 +01:00
parent 808fa65aef
commit 2c5d0a6ebc
43 changed files with 443 additions and 528 deletions

View file

@ -13,6 +13,7 @@ use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::DomRoot;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext as SafeJSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::JS_GetArrayBufferViewBuffer; use js::jsapi::JS_GetArrayBufferViewBuffer;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSContext, JSObject};
@ -230,22 +231,20 @@ impl AudioBufferMethods for AudioBuffer {
// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-getchanneldata // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-getchanneldata
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn GetChannelData( fn GetChannelData(&self, cx: SafeJSContext, channel: u32) -> Fallible<NonNull<JSObject>> {
&self,
cx: *mut JSContext,
channel: u32,
) -> Fallible<NonNull<JSObject>> {
if channel >= self.number_of_channels { if channel >= self.number_of_channels {
return Err(Error::IndexSize); return Err(Error::IndexSize);
} }
if !self.restore_js_channel_data(cx) { unsafe {
return Err(Error::JSFailed); if !self.restore_js_channel_data(*cx) {
} return Err(Error::JSFailed);
}
Ok(NonNull::new_unchecked( Ok(NonNull::new_unchecked(
self.js_channels.borrow()[channel as usize].get(), self.js_channels.borrow()[channel as usize].get(),
)) ))
}
} }
// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-copyfromchannel // https://webaudio.github.io/web-audio-api/#dom-audiobuffer-copyfromchannel

View file

@ -3332,7 +3332,7 @@ class CGCallGenerator(CGThing):
needsCx = needCx(returnType, (a for (a, _) in arguments), True) needsCx = needCx(returnType, (a for (a, _) in arguments), True)
if "cx" not in argsPre and needsCx: if "cx" not in argsPre and needsCx:
args.prepend(CGGeneric("*cx")) args.prepend(CGGeneric("cx"))
if nativeMethodName in descriptor.inCompartmentMethods: if nativeMethodName in descriptor.inCompartmentMethods:
args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(*cx))")) args.append(CGGeneric("InCompartment::in_compartment(&AlreadyInCompartment::assert_for_cx(*cx))"))
@ -5649,7 +5649,7 @@ class CGInterfaceTrait(CGThing):
def attribute_arguments(needCx, argument=None, inCompartment=False): def attribute_arguments(needCx, argument=None, inCompartment=False):
if needCx: if needCx:
yield "cx", "*mut JSContext" yield "cx", "SafeJSContext"
if argument: if argument:
yield "value", argument_type(descriptor, argument) yield "value", argument_type(descriptor, argument)
@ -6720,7 +6720,7 @@ def argument_type(descriptorProvider, ty, optional=False, defaultValue=None, var
def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, trailing=None, inCompartment=False): def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, trailing=None, inCompartment=False):
if needCx(returnType, arguments, passJSBits): if needCx(returnType, arguments, passJSBits):
yield "cx", "*mut JSContext" yield "cx", "SafeJSContext"
for argument in arguments: for argument in arguments:
ty = argument_type(descriptorProvider, argument.type, argument.optional, ty = argument_type(descriptorProvider, argument.type, argument.optional,

View file

@ -76,41 +76,41 @@ impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> {
/// Return the next value from the iterable object. /// Return the next value from the iterable object.
#[allow(non_snake_case)] #[allow(non_snake_case)]
pub fn Next(&self, cx: *mut JSContext) -> Fallible<NonNull<JSObject>> { pub fn Next(&self, cx: SafeJSContext) -> Fallible<NonNull<JSObject>> {
let index = self.index.get(); let index = self.index.get();
rooted!(in(cx) let mut value = UndefinedValue()); rooted!(in(*cx) let mut value = UndefinedValue());
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let result = if index >= self.iterable.get_iterable_length() { let result = if index >= self.iterable.get_iterable_length() {
dict_return(cx, rval.handle_mut(), true, value.handle()) dict_return(*cx, rval.handle_mut(), true, value.handle())
} else { } else {
match self.type_ { match self.type_ {
IteratorType::Keys => { IteratorType::Keys => {
unsafe { unsafe {
self.iterable self.iterable
.get_key_at_index(index) .get_key_at_index(index)
.to_jsval(cx, value.handle_mut()); .to_jsval(*cx, value.handle_mut());
} }
dict_return(cx, rval.handle_mut(), false, value.handle()) dict_return(*cx, rval.handle_mut(), false, value.handle())
}, },
IteratorType::Values => { IteratorType::Values => {
unsafe { unsafe {
self.iterable self.iterable
.get_value_at_index(index) .get_value_at_index(index)
.to_jsval(cx, value.handle_mut()); .to_jsval(*cx, value.handle_mut());
} }
dict_return(cx, rval.handle_mut(), false, value.handle()) dict_return(*cx, rval.handle_mut(), false, value.handle())
}, },
IteratorType::Entries => { IteratorType::Entries => {
rooted!(in(cx) let mut key = UndefinedValue()); rooted!(in(*cx) let mut key = UndefinedValue());
unsafe { unsafe {
self.iterable self.iterable
.get_key_at_index(index) .get_key_at_index(index)
.to_jsval(cx, key.handle_mut()); .to_jsval(*cx, key.handle_mut());
self.iterable self.iterable
.get_value_at_index(index) .get_value_at_index(index)
.to_jsval(cx, value.handle_mut()); .to_jsval(*cx, value.handle_mut());
} }
key_and_value_return(cx, rval.handle_mut(), key.handle(), value.handle()) key_and_value_return(*cx, rval.handle_mut(), key.handle(), value.handle())
}, },
} }
}; };

View file

@ -9,9 +9,10 @@ use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::DomRoot;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::JSObject;
use js::jsapi::Type; use js::jsapi::Type;
use js::jsapi::{JSContext, JSObject};
use js::rust::CustomAutoRooterGuard; use js::rust::CustomAutoRooterGuard;
use js::typedarray::ArrayBufferView; use js::typedarray::ArrayBufferView;
use servo_rand::{Rng, ServoRng}; use servo_rand::{Rng, ServoRng};
@ -47,9 +48,9 @@ impl Crypto {
impl CryptoMethods for Crypto { impl CryptoMethods for Crypto {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#Crypto-method-getRandomValues
unsafe fn GetRandomValues( fn GetRandomValues(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
mut input: CustomAutoRooterGuard<ArrayBufferView>, mut input: CustomAutoRooterGuard<ArrayBufferView>,
) -> Fallible<NonNull<JSObject>> { ) -> Fallible<NonNull<JSObject>> {
let array_type = input.get_array_type(); let array_type = input.get_array_type();
@ -57,14 +58,14 @@ impl CryptoMethods for Crypto {
if !is_integer_buffer(array_type) { if !is_integer_buffer(array_type) {
return Err(Error::TypeMismatch); return Err(Error::TypeMismatch);
} else { } else {
let mut data = input.as_mut_slice(); let mut data = unsafe { input.as_mut_slice() };
if data.len() > 65536 { if data.len() > 65536 {
return Err(Error::QuotaExceeded); return Err(Error::QuotaExceeded);
} }
self.rng.borrow_mut().fill_bytes(&mut data); self.rng.borrow_mut().fill_bytes(&mut data);
} }
Ok(NonNull::new_unchecked(*input.underlying_object())) unsafe { Ok(NonNull::new_unchecked(*input.underlying_object())) }
} }
} }

View file

@ -405,13 +405,13 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-get> /// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-get>
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn Get(&self, cx: *mut JSContext, name: DOMString) -> JSVal { fn Get(&self, cx: SafeJSContext, name: DOMString) -> JSVal {
match self.definitions.borrow().get(&LocalName::from(&*name)) { match self.definitions.borrow().get(&LocalName::from(&*name)) {
Some(definition) => { Some(definition) => unsafe {
rooted!(in(cx) let mut constructor = UndefinedValue()); rooted!(in(*cx) let mut constructor = UndefinedValue());
definition definition
.constructor .constructor
.to_jsval(cx, constructor.handle_mut()); .to_jsval(*cx, constructor.handle_mut());
constructor.get() constructor.get()
}, },
None => UndefinedValue(), None => UndefinedValue(),

View file

@ -13,8 +13,9 @@ use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::bindings::trace::RootedTraceableBox;
use crate::dom::event::Event; use crate::dom::event::Event;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -87,17 +88,15 @@ impl CustomEvent {
} }
impl CustomEventMethods for CustomEvent { impl CustomEventMethods for CustomEvent {
#[allow(unsafe_code)]
// https://dom.spec.whatwg.org/#dom-customevent-detail // https://dom.spec.whatwg.org/#dom-customevent-detail
unsafe fn Detail(&self, _cx: *mut JSContext) -> JSVal { fn Detail(&self, _cx: JSContext) -> JSVal {
self.detail.get() self.detail.get()
} }
#[allow(unsafe_code)]
// https://dom.spec.whatwg.org/#dom-customevent-initcustomevent // https://dom.spec.whatwg.org/#dom-customevent-initcustomevent
unsafe fn InitCustomEvent( fn InitCustomEvent(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
type_: DOMString, type_: DOMString,
can_bubble: bool, can_bubble: bool,
cancelable: bool, cancelable: bool,

View file

@ -560,10 +560,9 @@ unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool {
} }
impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope { impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage // https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { fn PostMessage(&self, cx: SafeJSContext, message: HandleValue) -> ErrorResult {
let data = StructuredCloneData::write(cx, message)?; let data = StructuredCloneData::write(*cx, message)?;
let worker = self.worker.borrow().as_ref().unwrap().clone(); let worker = self.worker.borrow().as_ref().unwrap().clone();
let pipeline_id = self.upcast::<GlobalScope>().pipeline_id(); let pipeline_id = self.upcast::<GlobalScope>().pipeline_id();
let task = Box::new(task!(post_worker_message: move || { let task = Box::new(task!(post_worker_message: move || {

View file

@ -11,10 +11,9 @@ use crate::dom::bindings::structuredclone::StructuredCloneData;
use crate::dom::dissimilaroriginlocation::DissimilarOriginLocation; use crate::dom::dissimilaroriginlocation::DissimilarOriginLocation;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::windowproxy::WindowProxy; use crate::dom::windowproxy::WindowProxy;
use crate::script_runtime::JSContext as SafeJSContext; use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use ipc_channel::ipc; use ipc_channel::ipc;
use js::jsapi::JSContext;
use js::jsval::{JSVal, UndefinedValue}; use js::jsval::{JSVal, UndefinedValue};
use js::rust::HandleValue; use js::rust::HandleValue;
use msg::constellation_msg::PipelineId; use msg::constellation_msg::PipelineId;
@ -69,7 +68,7 @@ impl DissimilarOriginWindow {
window_proxy: Dom::from_ref(window_proxy), window_proxy: Dom::from_ref(window_proxy),
location: Default::default(), location: Default::default(),
}); });
unsafe { DissimilarOriginWindowBinding::Wrap(SafeJSContext::from_ptr(cx), win) } unsafe { DissimilarOriginWindowBinding::Wrap(JSContext::from_ptr(cx), win) }
} }
pub fn window_proxy(&self) -> DomRoot<WindowProxy> { pub fn window_proxy(&self) -> DomRoot<WindowProxy> {
@ -134,14 +133,8 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
false false
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-window-postmessage // https://html.spec.whatwg.org/multipage/#dom-window-postmessage
unsafe fn PostMessage( fn PostMessage(&self, cx: JSContext, message: HandleValue, origin: DOMString) -> ErrorResult {
&self,
cx: *mut JSContext,
message: HandleValue,
origin: DOMString,
) -> ErrorResult {
// Step 3-5. // Step 3-5.
let origin = match &origin[..] { let origin = match &origin[..] {
"*" => None, "*" => None,
@ -157,23 +150,21 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
// Step 1-2, 6-8. // Step 1-2, 6-8.
// TODO(#12717): Should implement the `transfer` argument. // TODO(#12717): Should implement the `transfer` argument.
let data = StructuredCloneData::write(cx, message)?; let data = StructuredCloneData::write(*cx, message)?;
// Step 9. // Step 9.
self.post_message(origin, data); self.post_message(origin, data);
Ok(()) Ok(())
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener // https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn Opener(&self, _: *mut JSContext) -> JSVal { fn Opener(&self, _: JSContext) -> JSVal {
// TODO: Implement x-origin opener // TODO: Implement x-origin opener
UndefinedValue() UndefinedValue()
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener // https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn SetOpener(&self, _: *mut JSContext, _: HandleValue) { fn SetOpener(&self, _: JSContext, _: HandleValue) {
// TODO: Implement x-origin opener // TODO: Implement x-origin opener
} }

View file

@ -102,6 +102,7 @@ use crate::dom::wheelevent::WheelEvent;
use crate::dom::window::{ReflowReason, Window}; use crate::dom::window::{ReflowReason, Window};
use crate::dom::windowproxy::WindowProxy; use crate::dom::windowproxy::WindowProxy;
use crate::fetch::FetchCanceller; use crate::fetch::FetchCanceller;
use crate::script_runtime::JSContext;
use crate::script_runtime::{CommonScriptMsg, ScriptThreadEventCategory}; use crate::script_runtime::{CommonScriptMsg, ScriptThreadEventCategory};
use crate::script_thread::{MainThreadScriptMsg, ScriptThread}; use crate::script_thread::{MainThreadScriptMsg, ScriptThread};
use crate::stylesheet_set::StylesheetSetRef; use crate::stylesheet_set::StylesheetSetRef;
@ -117,7 +118,7 @@ use euclid::default::Point2D;
use html5ever::{LocalName, Namespace, QualName}; use html5ever::{LocalName, Namespace, QualName};
use hyper_serde::Serde; use hyper_serde::Serde;
use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::ipc::{self, IpcSender};
use js::jsapi::{JSContext, JSObject, JSRuntime}; use js::jsapi::{JSObject, JSRuntime};
use keyboard_types::{Key, KeyState, Modifiers}; use keyboard_types::{Key, KeyState, Modifiers};
use metrics::{ use metrics::{
InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory, InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory,
@ -4218,11 +4219,7 @@ impl DocumentMethods for Document {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter
unsafe fn NamedGetter( fn NamedGetter(&self, _cx: JSContext, name: DOMString) -> Option<NonNull<JSObject>> {
&self,
_cx: *mut JSContext,
name: DOMString,
) -> Option<NonNull<JSObject>> {
#[derive(JSTraceable, MallocSizeOf)] #[derive(JSTraceable, MallocSizeOf)]
struct NamedElementFilter { struct NamedElementFilter {
name: Atom, name: Atom,
@ -4270,7 +4267,7 @@ impl DocumentMethods for Document {
} }
let name = Atom::from(name); let name = Atom::from(name);
let root = self.upcast::<Node>(); let root = self.upcast::<Node>();
{ unsafe {
// Step 1. // Step 1.
let mut elements = root let mut elements = root
.traverse_preorder(ShadowIncluding::No) .traverse_preorder(ShadowIncluding::No)
@ -4291,9 +4288,11 @@ impl DocumentMethods for Document {
// Step 4. // Step 4.
let filter = NamedElementFilter { name: name }; let filter = NamedElementFilter { name: name };
let collection = HTMLCollection::create(self.window(), root, Box::new(filter)); let collection = HTMLCollection::create(self.window(), root, Box::new(filter));
Some(NonNull::new_unchecked( unsafe {
collection.reflector().get_jsobject().get(), Some(NonNull::new_unchecked(
)) collection.reflector().get_jsobject().get(),
))
}
} }
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names

View file

@ -18,10 +18,11 @@ use crate::dom::dommatrix::DOMMatrix;
use crate::dom::dompoint::DOMPoint; use crate::dom::dompoint::DOMPoint;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext;
use cssparser::{Parser, ParserInput}; use cssparser::{Parser, ParserInput};
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::{default::Transform3D, Angle}; use euclid::{default::Transform3D, Angle};
use js::jsapi::{JSContext, JSObject}; use js::jsapi::JSObject;
use js::rust::CustomAutoRooterGuard; use js::rust::CustomAutoRooterGuard;
use js::typedarray::CreateWith; use js::typedarray::CreateWith;
use js::typedarray::{Float32Array, Float64Array}; use js::typedarray::{Float32Array, Float64Array};
@ -667,7 +668,7 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly {
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-tofloat32array // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-tofloat32array
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn ToFloat32Array(&self, cx: *mut JSContext) -> NonNull<JSObject> { fn ToFloat32Array(&self, cx: JSContext) -> NonNull<JSObject> {
let vec: Vec<f32> = self let vec: Vec<f32> = self
.matrix .matrix
.borrow() .borrow()
@ -675,18 +676,22 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly {
.iter() .iter()
.map(|&x| x as f32) .map(|&x| x as f32)
.collect(); .collect();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); unsafe {
let _ = Float32Array::create(cx, CreateWith::Slice(&vec), array.handle_mut()).unwrap(); rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
NonNull::new_unchecked(array.get()) let _ = Float32Array::create(*cx, CreateWith::Slice(&vec), array.handle_mut()).unwrap();
NonNull::new_unchecked(array.get())
}
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-tofloat64array // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-tofloat64array
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn ToFloat64Array(&self, cx: *mut JSContext) -> NonNull<JSObject> { fn ToFloat64Array(&self, cx: JSContext) -> NonNull<JSObject> {
let arr = self.matrix.borrow().to_row_major_array(); let arr = self.matrix.borrow().to_row_major_array();
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); unsafe {
let _ = Float64Array::create(cx, CreateWith::Slice(&arr), array.handle_mut()).unwrap(); rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
NonNull::new_unchecked(array.get()) let _ = Float64Array::create(*cx, CreateWith::Slice(&arr), array.handle_mut()).unwrap();
NonNull::new_unchecked(array.get())
}
} }
} }

View file

@ -14,8 +14,9 @@ use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::trace::RootedTraceableBox; use crate::dom::bindings::trace::RootedTraceableBox;
use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -135,9 +136,8 @@ impl ErrorEventMethods for ErrorEvent {
self.filename.borrow().clone() self.filename.borrow().clone()
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-errorevent-error // https://html.spec.whatwg.org/multipage/#dom-errorevent-error
unsafe fn Error(&self, _cx: *mut JSContext) -> JSVal { fn Error(&self, _cx: JSContext) -> JSVal {
self.error.get() self.error.get()
} }

View file

@ -169,7 +169,7 @@ impl CompiledEventListener {
CommonEventHandler::ErrorEventHandler(ref handler) => { CommonEventHandler::ErrorEventHandler(ref handler) => {
if let Some(event) = event.downcast::<ErrorEvent>() { if let Some(event) = event.downcast::<ErrorEvent>() {
let cx = object.global().get_cx(); let cx = object.global().get_cx();
rooted!(in(cx) let error = unsafe { event.Error(cx) }); rooted!(in(cx) let error = unsafe { event.Error(JSContext::from_ptr(cx)) });
let return_value = handler.Call_( let return_value = handler.Call_(
object, object,
EventOrString::String(event.Message()), EventOrString::String(event.Message()),

View file

@ -11,8 +11,8 @@ use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString; use crate::dom::bindings::str::DOMString;
use crate::dom::event::Event; use crate::dom::event::Event;
use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::JSContext;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -62,7 +62,7 @@ impl ExtendableEvent {
} }
// https://w3c.github.io/ServiceWorker/#wait-until-method // https://w3c.github.io/ServiceWorker/#wait-until-method
pub fn WaitUntil(&self, _cx: *mut JSContext, _val: HandleValue) -> ErrorResult { pub fn WaitUntil(&self, _cx: JSContext, _val: HandleValue) -> ErrorResult {
// Step 1 // Step 1
if !self.extensions_allowed { if !self.extensions_allowed {
return Err(Error::InvalidState); return Err(Error::InvalidState);

View file

@ -15,8 +15,9 @@ use crate::dom::eventtarget::EventTarget;
use crate::dom::extendableevent::ExtendableEvent; use crate::dom::extendableevent::ExtendableEvent;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -91,9 +92,8 @@ impl ExtendableMessageEvent {
} }
impl ExtendableMessageEventMethods for ExtendableMessageEvent { impl ExtendableMessageEventMethods for ExtendableMessageEvent {
#[allow(unsafe_code)]
// https://w3c.github.io/ServiceWorker/#extendablemessage-event-data-attribute // https://w3c.github.io/ServiceWorker/#extendablemessage-event-data-attribute
unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { fn Data(&self, _cx: JSContext) -> JSVal {
self.data.get() self.data.get()
} }

View file

@ -22,6 +22,7 @@ use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::eventtarget::EventTarget; use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::progressevent::ProgressEvent; use crate::dom::progressevent::ProgressEvent;
use crate::script_runtime::JSContext as SafeJSContext;
use crate::task::TaskCanceller; use crate::task::TaskCanceller;
use crate::task_source::file_reading::{FileReadingTask, FileReadingTaskSource}; use crate::task_source::file_reading::{FileReadingTask, FileReadingTaskSource};
use crate::task_source::{TaskSource, TaskSourceName}; use crate::task_source::{TaskSource, TaskSourceName};
@ -391,12 +392,14 @@ impl FileReaderMethods for FileReader {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/FileAPI/#dfn-result // https://w3c.github.io/FileAPI/#dfn-result
unsafe fn GetResult(&self, _: *mut JSContext) -> Option<StringOrObject> { fn GetResult(&self, _: SafeJSContext) -> Option<StringOrObject> {
self.result.borrow().as_ref().map(|r| match *r { self.result.borrow().as_ref().map(|r| match *r {
FileReaderResult::String(ref string) => StringOrObject::String(string.clone()), FileReaderResult::String(ref string) => StringOrObject::String(string.clone()),
FileReaderResult::ArrayBuffer(ref arr_buffer) => { FileReaderResult::ArrayBuffer(ref arr_buffer) => {
let result = RootedTraceableBox::new(Heap::default()); let result = RootedTraceableBox::new(Heap::default());
result.set((*arr_buffer.ptr.get()).to_object()); unsafe {
result.set((*arr_buffer.ptr.get()).to_object());
}
StringOrObject::Object(result) StringOrObject::Object(result)
}, },
}) })

View file

@ -13,8 +13,9 @@ use crate::dom::bindings::str::DOMString;
use crate::dom::blob::Blob; use crate::dom::blob::Blob;
use crate::dom::filereader::FileReaderSharedFunctionality; use crate::dom::filereader::FileReaderSharedFunctionality;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::JSObject;
use js::typedarray::{ArrayBuffer, CreateWith}; use js::typedarray::{ArrayBuffer, CreateWith};
use std::ptr; use std::ptr;
use std::ptr::NonNull; use std::ptr::NonNull;
@ -87,23 +88,21 @@ impl FileReaderSyncMethods for FileReaderSync {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/FileAPI/#readAsArrayBufferSyncSection // https://w3c.github.io/FileAPI/#readAsArrayBufferSyncSection
unsafe fn ReadAsArrayBuffer( fn ReadAsArrayBuffer(&self, cx: JSContext, blob: &Blob) -> Fallible<NonNull<JSObject>> {
&self,
cx: *mut JSContext,
blob: &Blob,
) -> Fallible<NonNull<JSObject>> {
// step 1 // step 1
let blob_contents = FileReaderSync::get_blob_bytes(blob)?; let blob_contents = FileReaderSync::get_blob_bytes(blob)?;
// step 2 // step 2
rooted!(in(cx) let mut array_buffer = ptr::null_mut::<JSObject>()); unsafe {
assert!(ArrayBuffer::create( rooted!(in(*cx) let mut array_buffer = ptr::null_mut::<JSObject>());
cx, assert!(ArrayBuffer::create(
CreateWith::Slice(&blob_contents), *cx,
array_buffer.handle_mut() CreateWith::Slice(&blob_contents),
) array_buffer.handle_mut()
.is_ok()); )
.is_ok());
Ok(NonNull::new_unchecked(array_buffer.get())) Ok(NonNull::new_unchecked(array_buffer.get()))
}
} }
} }

View file

@ -15,8 +15,9 @@ use crate::dom::gamepadbuttonlist::GamepadButtonList;
use crate::dom::gamepadevent::{GamepadEvent, GamepadEventType}; use crate::dom::gamepadevent::{GamepadEvent, GamepadEventType};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::vrpose::VRPose; use crate::dom::vrpose::VRPose;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use js::typedarray::{CreateWith, Float64Array}; use js::typedarray::{CreateWith, Float64Array};
use std::cell::Cell; use std::cell::Cell;
use std::ptr; use std::ptr;
@ -136,8 +137,8 @@ impl GamepadMethods for Gamepad {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/gamepad/#dom-gamepad-axes // https://w3c.github.io/gamepad/#dom-gamepad-axes
unsafe fn Axes(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn Axes(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.axes.get()) unsafe { NonNull::new_unchecked(self.axes.get()) }
} }
// https://w3c.github.io/gamepad/#dom-gamepad-buttons // https://w3c.github.io/gamepad/#dom-gamepad-buttons

View file

@ -18,6 +18,7 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::hashchangeevent::HashChangeEvent; use crate::dom::hashchangeevent::HashChangeEvent;
use crate::dom::popstateevent::PopStateEvent; use crate::dom::popstateevent::PopStateEvent;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext as SafeJSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::{Heap, JSContext};
use js::jsval::{JSVal, NullValue, UndefinedValue}; use js::jsval::{JSVal, NullValue, UndefinedValue};
@ -279,8 +280,7 @@ impl History {
impl HistoryMethods for History { impl HistoryMethods for History {
// https://html.spec.whatwg.org/multipage/#dom-history-state // https://html.spec.whatwg.org/multipage/#dom-history-state
#[allow(unsafe_code)] fn GetState(&self, _cx: SafeJSContext) -> Fallible<JSVal> {
unsafe fn GetState(&self, _cx: *mut JSContext) -> Fallible<JSVal> {
if !self.window.Document().is_fully_active() { if !self.window.Document().is_fully_active() {
return Err(Error::Security); return Err(Error::Security);
} }
@ -327,26 +327,24 @@ impl HistoryMethods for History {
} }
// https://html.spec.whatwg.org/multipage/#dom-history-pushstate // https://html.spec.whatwg.org/multipage/#dom-history-pushstate
#[allow(unsafe_code)] fn PushState(
unsafe fn PushState(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
data: HandleValue, data: HandleValue,
title: DOMString, title: DOMString,
url: Option<USVString>, url: Option<USVString>,
) -> ErrorResult { ) -> ErrorResult {
self.push_or_replace_state(cx, data, title, url, PushOrReplace::Push) self.push_or_replace_state(*cx, data, title, url, PushOrReplace::Push)
} }
// https://html.spec.whatwg.org/multipage/#dom-history-replacestate // https://html.spec.whatwg.org/multipage/#dom-history-replacestate
#[allow(unsafe_code)] fn ReplaceState(
unsafe fn ReplaceState(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
data: HandleValue, data: HandleValue,
title: DOMString, title: DOMString,
url: Option<USVString>, url: Option<USVString>,
) -> ErrorResult { ) -> ErrorResult {
self.push_or_replace_state(cx, data, title, url, PushOrReplace::Replace) self.push_or_replace_state(*cx, data, title, url, PushOrReplace::Replace)
} }
} }

View file

@ -330,9 +330,9 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement {
// https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn GetContext( fn GetContext(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
id: DOMString, id: DOMString,
options: HandleValue, options: HandleValue,
) -> Option<RenderingContext> { ) -> Option<RenderingContext> {
@ -340,21 +340,22 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement {
"2d" => self "2d" => self
.get_or_init_2d_context() .get_or_init_2d_context()
.map(RenderingContext::CanvasRenderingContext2D), .map(RenderingContext::CanvasRenderingContext2D),
"webgl" | "experimental-webgl" => self "webgl" | "experimental-webgl" => unsafe {
.get_or_init_webgl_context(cx, options) self.get_or_init_webgl_context(*cx, options)
.map(RenderingContext::WebGLRenderingContext), .map(RenderingContext::WebGLRenderingContext)
"webgl2" | "experimental-webgl2" => self },
.get_or_init_webgl2_context(cx, options) "webgl2" | "experimental-webgl2" => unsafe {
.map(RenderingContext::WebGL2RenderingContext), self.get_or_init_webgl2_context(*cx, options)
.map(RenderingContext::WebGL2RenderingContext)
},
_ => None, _ => None,
} }
} }
// https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl // https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl
#[allow(unsafe_code)] fn ToDataURL(
unsafe fn ToDataURL(
&self, &self,
_context: *mut JSContext, _context: SafeJSContext,
_mime_type: Option<DOMString>, _mime_type: Option<DOMString>,
_quality: HandleValue, _quality: HandleValue,
) -> Fallible<USVString> { ) -> Fallible<USVString> {

View file

@ -8,10 +8,11 @@ use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::DomRoot;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::default::{Rect, Size2D}; use euclid::default::{Rect, Size2D};
use ipc_channel::ipc::IpcSharedMemory; use ipc_channel::ipc::IpcSharedMemory;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use js::rust::Runtime; use js::rust::Runtime;
use js::typedarray::{CreateWith, Uint8ClampedArray}; use js::typedarray::{CreateWith, Uint8ClampedArray};
use std::borrow::Cow; use std::borrow::Cow;
@ -131,7 +132,7 @@ impl ImageData {
#[allow(unsafe_code)] #[allow(unsafe_code)]
#[allow(unused_variables)] #[allow(unused_variables)]
pub unsafe fn Constructor_( pub unsafe fn Constructor_(
cx: *mut JSContext, cx: JSContext,
global: &GlobalScope, global: &GlobalScope,
jsobject: *mut JSObject, jsobject: *mut JSObject,
width: u32, width: u32,
@ -183,9 +184,8 @@ impl ImageDataMethods for ImageData {
self.height self.height
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-imagedata-data // https://html.spec.whatwg.org/multipage/#dom-imagedata-data
unsafe fn Data(&self, _: *mut JSContext) -> NonNull<JSObject> { fn Data(&self, _: JSContext) -> NonNull<JSObject> {
NonNull::new(self.data.get()).expect("got a null pointer") NonNull::new(self.data.get()).expect("got a null pointer")
} }
} }

View file

@ -15,8 +15,9 @@ use crate::dom::event::Event;
use crate::dom::eventtarget::EventTarget; use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::windowproxy::WindowProxy; use crate::dom::windowproxy::WindowProxy;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -127,9 +128,8 @@ impl MessageEvent {
} }
impl MessageEventMethods for MessageEvent { impl MessageEventMethods for MessageEvent {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-messageevent-data // https://html.spec.whatwg.org/multipage/#dom-messageevent-data
unsafe fn Data(&self, _cx: *mut JSContext) -> JSVal { fn Data(&self, _cx: JSContext) -> JSVal {
self.data.get() self.data.get()
} }
@ -139,8 +139,7 @@ impl MessageEventMethods for MessageEvent {
} }
// https://html.spec.whatwg.org/multipage/#dom-messageevent-source // https://html.spec.whatwg.org/multipage/#dom-messageevent-source
#[allow(unsafe_code)] fn GetSource(&self, _cx: JSContext) -> Option<NonNull<JSObject>> {
unsafe fn GetSource(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> {
self.source self.source
.as_ref() .as_ref()
.and_then(|source| NonNull::new(source.reflector().get_jsobject().get())) .and_then(|source| NonNull::new(source.reflector().get_jsobject().get()))

View file

@ -15,9 +15,9 @@ use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlcanvaselement::HTMLCanvasElement; use crate::dom::htmlcanvaselement::HTMLCanvasElement;
use crate::dom::offscreencanvasrenderingcontext2d::OffscreenCanvasRenderingContext2D; use crate::dom::offscreencanvasrenderingcontext2d::OffscreenCanvasRenderingContext2D;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::default::Size2D; use euclid::default::Size2D;
use js::jsapi::JSContext;
use js::rust::HandleValue; use js::rust::HandleValue;
use ref_filter_map; use ref_filter_map;
use std::cell::Cell; use std::cell::Cell;
@ -108,10 +108,9 @@ impl OffscreenCanvas {
impl OffscreenCanvasMethods for OffscreenCanvas { impl OffscreenCanvasMethods for OffscreenCanvas {
// https://html.spec.whatwg.org/multipage/#dom-offscreencanvas-getcontext // https://html.spec.whatwg.org/multipage/#dom-offscreencanvas-getcontext
#[allow(unsafe_code)] fn GetContext(
unsafe fn GetContext(
&self, &self,
_cx: *mut JSContext, _cx: JSContext,
id: DOMString, id: DOMString,
_options: HandleValue, _options: HandleValue,
) -> Option<OffscreenRenderingContext> { ) -> Option<OffscreenRenderingContext> {

View file

@ -200,22 +200,19 @@ impl Permissions {
} }
impl PermissionsMethods for Permissions { impl PermissionsMethods for Permissions {
#[allow(unsafe_code)]
// https://w3c.github.io/permissions/#dom-permissions-query // https://w3c.github.io/permissions/#dom-permissions-query
unsafe fn Query(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { fn Query(&self, cx: SafeJSContext, permissionDesc: *mut JSObject) -> Rc<Promise> {
self.manipulate(Operation::Query, cx, permissionDesc, None) self.manipulate(Operation::Query, *cx, permissionDesc, None)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/permissions/#dom-permissions-request // https://w3c.github.io/permissions/#dom-permissions-request
unsafe fn Request(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { fn Request(&self, cx: SafeJSContext, permissionDesc: *mut JSObject) -> Rc<Promise> {
self.manipulate(Operation::Request, cx, permissionDesc, None) self.manipulate(Operation::Request, *cx, permissionDesc, None)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/permissions/#dom-permissions-revoke // https://w3c.github.io/permissions/#dom-permissions-revoke
unsafe fn Revoke(&self, cx: *mut JSContext, permissionDesc: *mut JSObject) -> Rc<Promise> { fn Revoke(&self, cx: SafeJSContext, permissionDesc: *mut JSObject) -> Rc<Promise> {
self.manipulate(Operation::Revoke, cx, permissionDesc, None) self.manipulate(Operation::Revoke, *cx, permissionDesc, None)
} }
} }

View file

@ -14,8 +14,9 @@ use crate::dom::bindings::trace::RootedTraceableBox;
use crate::dom::event::Event; use crate::dom::event::Event;
use crate::dom::eventtarget::EventTarget; use crate::dom::eventtarget::EventTarget;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -81,9 +82,8 @@ impl PopStateEvent {
} }
impl PopStateEventMethods for PopStateEvent { impl PopStateEventMethods for PopStateEvent {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-popstateevent-state // https://html.spec.whatwg.org/multipage/#dom-popstateevent-state
unsafe fn State(&self, _cx: *mut JSContext) -> JSVal { fn State(&self, _cx: JSContext) -> JSVal {
self.state.get() self.state.get()
} }

View file

@ -14,8 +14,9 @@ use crate::dom::bindings::trace::RootedTraceableBox;
use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::promise::Promise; use crate::dom::promise::Promise;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::HandleValue; use js::rust::HandleValue;
use servo_atoms::Atom; use servo_atoms::Atom;
@ -100,9 +101,8 @@ impl PromiseRejectionEventMethods for PromiseRejectionEvent {
self.promise.clone() self.promise.clone()
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-promiserejectionevent-reason // https://html.spec.whatwg.org/multipage/#dom-promiserejectionevent-reason
unsafe fn Reason(&self, _cx: *mut JSContext) -> JSVal { fn Reason(&self, _cx: JSContext) -> JSVal {
self.reason.get() self.reason.get()
} }

View file

@ -14,9 +14,10 @@ use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString; use crate::dom::bindings::str::DOMString;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::conversions::ToJSValConvertible; use js::conversions::ToJSValConvertible;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::JSObject;
use js::jsval::UndefinedValue; use js::jsval::UndefinedValue;
use std::ptr::NonNull; use std::ptr::NonNull;
@ -73,13 +74,15 @@ impl RTCSessionDescriptionMethods for RTCSessionDescription {
#[allow(unsafe_code)] #[allow(unsafe_code)]
/// https://w3c.github.io/webrtc-pc/#dom-rtcsessiondescription-tojson /// https://w3c.github.io/webrtc-pc/#dom-rtcsessiondescription-tojson
unsafe fn ToJSON(&self, cx: *mut JSContext) -> NonNull<JSObject> { fn ToJSON(&self, cx: JSContext) -> NonNull<JSObject> {
let init = RTCSessionDescriptionInit { let init = RTCSessionDescriptionInit {
type_: self.ty, type_: self.ty,
sdp: self.sdp.clone(), sdp: self.sdp.clone(),
}; };
rooted!(in(cx) let mut jsval = UndefinedValue()); unsafe {
init.to_jsval(cx, jsval.handle_mut()); rooted!(in(*cx) let mut jsval = UndefinedValue());
NonNull::new(jsval.to_object()).unwrap() init.to_jsval(*cx, jsval.handle_mut());
NonNull::new(jsval.to_object()).unwrap()
}
} }
} }

View file

@ -16,9 +16,9 @@ use crate::dom::bindings::str::USVString;
use crate::dom::bindings::structuredclone::StructuredCloneData; use crate::dom::bindings::structuredclone::StructuredCloneData;
use crate::dom::eventtarget::EventTarget; use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use crate::task::TaskOnce; use crate::task::TaskOnce;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::JSContext;
use js::rust::HandleValue; use js::rust::HandleValue;
use script_traits::{DOMMessage, ScriptMsg}; use script_traits::{DOMMessage, ScriptMsg};
use servo_url::ServoUrl; use servo_url::ServoUrl;
@ -90,15 +90,14 @@ impl ServiceWorkerMethods for ServiceWorker {
USVString(self.script_url.borrow().clone()) USVString(self.script_url.borrow().clone())
} }
#[allow(unsafe_code)]
// https://w3c.github.io/ServiceWorker/#service-worker-postmessage // https://w3c.github.io/ServiceWorker/#service-worker-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { fn PostMessage(&self, cx: JSContext, message: HandleValue) -> ErrorResult {
// Step 1 // Step 1
if let ServiceWorkerState::Redundant = self.state.get() { if let ServiceWorkerState::Redundant = self.state.get() {
return Err(Error::InvalidState); return Err(Error::InvalidState);
} }
// Step 7 // Step 7
let data = StructuredCloneData::write(cx, message)?; let data = StructuredCloneData::write(*cx, message)?;
let msg_vec = DOMMessage(data.move_to_arraybuffer()); let msg_vec = DOMMessage(data.move_to_arraybuffer());
let _ = self let _ = self
.global() .global()

View file

@ -49,6 +49,7 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::promise::Promise; use crate::dom::promise::Promise;
use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler}; use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
use crate::dom::url::URL; use crate::dom::url::URL;
use crate::script_runtime::JSContext as SafeJSContext;
use crate::timers::OneshotTimerCallback; use crate::timers::OneshotTimerCallback;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSContext, JSObject};
@ -215,23 +216,24 @@ impl TestBindingMethods for TestBinding {
} }
fn SetUnion9Attribute(&self, _: ByteStringOrLong) {} fn SetUnion9Attribute(&self, _: ByteStringOrLong) {}
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn ArrayAttribute(&self, cx: *mut JSContext) -> NonNull<JSObject> { fn ArrayAttribute(&self, cx: SafeJSContext) -> NonNull<JSObject> {
rooted!(in(cx) let array = JS_NewUint8ClampedArray(cx, 16)); unsafe {
NonNull::new(array.get()).expect("got a null pointer") rooted!(in(*cx) let array = JS_NewUint8ClampedArray(*cx, 16));
NonNull::new(array.get()).expect("got a null pointer")
}
} }
#[allow(unsafe_code)] fn AnyAttribute(&self, _: SafeJSContext) -> JSVal {
unsafe fn AnyAttribute(&self, _: *mut JSContext) -> JSVal {
NullValue() NullValue()
} }
fn SetAnyAttribute(&self, _: SafeJSContext, _: HandleValue) {}
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn SetAnyAttribute(&self, _: *mut JSContext, _: HandleValue) {} fn ObjectAttribute(&self, cx: SafeJSContext) -> NonNull<JSObject> {
#[allow(unsafe_code)] unsafe {
unsafe fn ObjectAttribute(&self, cx: *mut JSContext) -> NonNull<JSObject> { rooted!(in(*cx) let obj = JS_NewPlainObject(*cx));
rooted!(in(cx) let obj = JS_NewPlainObject(cx)); NonNull::new(obj.get()).expect("got a null pointer")
NonNull::new(obj.get()).expect("got a null pointer") }
} }
#[allow(unsafe_code)] fn SetObjectAttribute(&self, _: SafeJSContext, _: *mut JSObject) {}
unsafe fn SetObjectAttribute(&self, _: *mut JSContext, _: *mut JSObject) {}
fn GetBooleanAttributeNullable(&self) -> Option<bool> { fn GetBooleanAttributeNullable(&self) -> Option<bool> {
Some(false) Some(false)
@ -329,12 +331,10 @@ impl TestBindingMethods for TestBinding {
fn SetInterfaceAttributeWeak(&self, url: Option<&URL>) { fn SetInterfaceAttributeWeak(&self, url: Option<&URL>) {
self.url.set(url); self.url.set(url);
} }
#[allow(unsafe_code)] fn GetObjectAttributeNullable(&self, _: SafeJSContext) -> Option<NonNull<JSObject>> {
unsafe fn GetObjectAttributeNullable(&self, _: *mut JSContext) -> Option<NonNull<JSObject>> {
None None
} }
#[allow(unsafe_code)] fn SetObjectAttributeNullable(&self, _: SafeJSContext, _: *mut JSObject) {}
unsafe fn SetObjectAttributeNullable(&self, _: *mut JSContext, _: *mut JSObject) {}
fn GetUnionAttributeNullable(&self) -> Option<HTMLElementOrLong> { fn GetUnionAttributeNullable(&self) -> Option<HTMLElementOrLong> {
Some(HTMLElementOrLong::Long(0)) Some(HTMLElementOrLong::Long(0))
} }
@ -419,12 +419,10 @@ impl TestBindingMethods for TestBinding {
"".to_owned(), "".to_owned(),
) )
} }
#[allow(unsafe_code)] fn ReceiveAny(&self, _: SafeJSContext) -> JSVal {
unsafe fn ReceiveAny(&self, _: *mut JSContext) -> JSVal {
NullValue() NullValue()
} }
#[allow(unsafe_code)] fn ReceiveObject(&self, cx: SafeJSContext) -> NonNull<JSObject> {
unsafe fn ReceiveObject(&self, cx: *mut JSContext) -> NonNull<JSObject> {
self.ObjectAttribute(cx) self.ObjectAttribute(cx)
} }
fn ReceiveUnion(&self) -> HTMLElementOrLong { fn ReceiveUnion(&self) -> HTMLElementOrLong {
@ -470,10 +468,9 @@ impl TestBindingMethods for TestBinding {
"".to_owned(), "".to_owned(),
)] )]
} }
#[allow(unsafe_code)] fn ReceiveUnionIdentity(
unsafe fn ReceiveUnionIdentity(
&self, &self,
_: *mut JSContext, _: SafeJSContext,
arg: UnionTypes::StringOrObject, arg: UnionTypes::StringOrObject,
) -> UnionTypes::StringOrObject { ) -> UnionTypes::StringOrObject {
arg arg
@ -537,8 +534,7 @@ impl TestBindingMethods for TestBinding {
"".to_owned(), "".to_owned(),
)) ))
} }
#[allow(unsafe_code)] fn ReceiveNullableObject(&self, cx: SafeJSContext) -> Option<NonNull<JSObject>> {
unsafe fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option<NonNull<JSObject>> {
self.GetObjectAttributeNullable(cx) self.GetObjectAttributeNullable(cx)
} }
fn ReceiveNullableUnion(&self) -> Option<HTMLElementOrLong> { fn ReceiveNullableUnion(&self) -> Option<HTMLElementOrLong> {
@ -666,35 +662,24 @@ impl TestBindingMethods for TestBinding {
fn PassUnion7(&self, _: StringSequenceOrUnsignedLong) {} fn PassUnion7(&self, _: StringSequenceOrUnsignedLong) {}
fn PassUnion8(&self, _: ByteStringSequenceOrLong) {} fn PassUnion8(&self, _: ByteStringSequenceOrLong) {}
fn PassUnion9(&self, _: UnionTypes::TestDictionaryOrLong) {} fn PassUnion9(&self, _: UnionTypes::TestDictionaryOrLong) {}
#[allow(unsafe_code)] fn PassUnion10(&self, _: SafeJSContext, _: UnionTypes::StringOrObject) {}
unsafe fn PassUnion10(&self, _: *mut JSContext, _: UnionTypes::StringOrObject) {}
fn PassUnion11(&self, _: UnionTypes::ArrayBufferOrArrayBufferView) {} fn PassUnion11(&self, _: UnionTypes::ArrayBufferOrArrayBufferView) {}
fn PassUnionWithTypedef(&self, _: DocumentOrTestTypedef) {} fn PassUnionWithTypedef(&self, _: DocumentOrTestTypedef) {}
fn PassUnionWithTypedef2(&self, _: LongSequenceOrTestTypedef) {} fn PassUnionWithTypedef2(&self, _: LongSequenceOrTestTypedef) {}
#[allow(unsafe_code)] fn PassAny(&self, _: SafeJSContext, _: HandleValue) {}
unsafe fn PassAny(&self, _: *mut JSContext, _: HandleValue) {} fn PassObject(&self, _: SafeJSContext, _: *mut JSObject) {}
#[allow(unsafe_code)]
unsafe fn PassObject(&self, _: *mut JSContext, _: *mut JSObject) {}
fn PassCallbackFunction(&self, _: Rc<Function>) {} fn PassCallbackFunction(&self, _: Rc<Function>) {}
fn PassCallbackInterface(&self, _: Rc<EventListener>) {} fn PassCallbackInterface(&self, _: Rc<EventListener>) {}
fn PassSequence(&self, _: Vec<i32>) {} fn PassSequence(&self, _: Vec<i32>) {}
#[allow(unsafe_code)] fn PassAnySequence(&self, _: SafeJSContext, _: CustomAutoRooterGuard<Vec<JSVal>>) {}
unsafe fn PassAnySequence(&self, _: *mut JSContext, _: CustomAutoRooterGuard<Vec<JSVal>>) {} fn AnySequencePassthrough(
#[allow(unsafe_code)]
unsafe fn AnySequencePassthrough(
&self, &self,
_: *mut JSContext, _: SafeJSContext,
seq: CustomAutoRooterGuard<Vec<JSVal>>, seq: CustomAutoRooterGuard<Vec<JSVal>>,
) -> Vec<JSVal> { ) -> Vec<JSVal> {
(*seq).clone() (*seq).clone()
} }
#[allow(unsafe_code)] fn PassObjectSequence(&self, _: SafeJSContext, _: CustomAutoRooterGuard<Vec<*mut JSObject>>) {}
unsafe fn PassObjectSequence(
&self,
_: *mut JSContext,
_: CustomAutoRooterGuard<Vec<*mut JSObject>>,
) {
}
fn PassStringSequence(&self, _: Vec<DOMString>) {} fn PassStringSequence(&self, _: Vec<DOMString>) {}
fn PassInterfaceSequence(&self, _: Vec<DomRoot<Blob>>) {} fn PassInterfaceSequence(&self, _: Vec<DomRoot<Blob>>) {}
@ -719,8 +704,7 @@ impl TestBindingMethods for TestBinding {
fn PassNullableByteString(&self, _: Option<ByteString>) {} fn PassNullableByteString(&self, _: Option<ByteString>) {}
// fn PassNullableEnum(self, _: Option<TestEnum>) {} // fn PassNullableEnum(self, _: Option<TestEnum>) {}
fn PassNullableInterface(&self, _: Option<&Blob>) {} fn PassNullableInterface(&self, _: Option<&Blob>) {}
#[allow(unsafe_code)] fn PassNullableObject(&self, _: SafeJSContext, _: *mut JSObject) {}
unsafe fn PassNullableObject(&self, _: *mut JSContext, _: *mut JSObject) {}
fn PassNullableTypedArray(&self, _: CustomAutoRooterGuard<Option<typedarray::Int8Array>>) {} fn PassNullableTypedArray(&self, _: CustomAutoRooterGuard<Option<typedarray::Int8Array>>) {}
fn PassNullableUnion(&self, _: Option<HTMLElementOrLong>) {} fn PassNullableUnion(&self, _: Option<HTMLElementOrLong>) {}
fn PassNullableUnion2(&self, _: Option<EventOrString>) {} fn PassNullableUnion2(&self, _: Option<EventOrString>) {}
@ -756,10 +740,8 @@ impl TestBindingMethods for TestBinding {
fn PassOptionalUnion4(&self, _: Option<LongSequenceOrBoolean>) {} fn PassOptionalUnion4(&self, _: Option<LongSequenceOrBoolean>) {}
fn PassOptionalUnion5(&self, _: Option<UnsignedLongOrBoolean>) {} fn PassOptionalUnion5(&self, _: Option<UnsignedLongOrBoolean>) {}
fn PassOptionalUnion6(&self, _: Option<ByteStringOrLong>) {} fn PassOptionalUnion6(&self, _: Option<ByteStringOrLong>) {}
#[allow(unsafe_code)] fn PassOptionalAny(&self, _: SafeJSContext, _: HandleValue) {}
unsafe fn PassOptionalAny(&self, _: *mut JSContext, _: HandleValue) {} fn PassOptionalObject(&self, _: SafeJSContext, _: Option<*mut JSObject>) {}
#[allow(unsafe_code)]
unsafe fn PassOptionalObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {}
fn PassOptionalCallbackFunction(&self, _: Option<Rc<Function>>) {} fn PassOptionalCallbackFunction(&self, _: Option<Rc<Function>>) {}
fn PassOptionalCallbackInterface(&self, _: Option<Rc<EventListener>>) {} fn PassOptionalCallbackInterface(&self, _: Option<Rc<EventListener>>) {}
fn PassOptionalSequence(&self, _: Option<Vec<i32>>) {} fn PassOptionalSequence(&self, _: Option<Vec<i32>>) {}
@ -782,8 +764,7 @@ impl TestBindingMethods for TestBinding {
fn PassOptionalNullableByteString(&self, _: Option<Option<ByteString>>) {} fn PassOptionalNullableByteString(&self, _: Option<Option<ByteString>>) {}
// fn PassOptionalNullableEnum(self, _: Option<Option<TestEnum>>) {} // fn PassOptionalNullableEnum(self, _: Option<Option<TestEnum>>) {}
fn PassOptionalNullableInterface(&self, _: Option<Option<&Blob>>) {} fn PassOptionalNullableInterface(&self, _: Option<Option<&Blob>>) {}
#[allow(unsafe_code)] fn PassOptionalNullableObject(&self, _: SafeJSContext, _: Option<*mut JSObject>) {}
unsafe fn PassOptionalNullableObject(&self, _: *mut JSContext, _: Option<*mut JSObject>) {}
fn PassOptionalNullableUnion(&self, _: Option<Option<HTMLElementOrLong>>) {} fn PassOptionalNullableUnion(&self, _: Option<Option<HTMLElementOrLong>>) {}
fn PassOptionalNullableUnion2(&self, _: Option<Option<EventOrString>>) {} fn PassOptionalNullableUnion2(&self, _: Option<Option<EventOrString>>) {}
fn PassOptionalNullableUnion3(&self, _: Option<Option<StringOrLongSequence>>) {} fn PassOptionalNullableUnion3(&self, _: Option<Option<StringOrLongSequence>>) {}
@ -827,14 +808,12 @@ impl TestBindingMethods for TestBinding {
fn PassOptionalNullableByteStringWithDefault(&self, _: Option<ByteString>) {} fn PassOptionalNullableByteStringWithDefault(&self, _: Option<ByteString>) {}
// fn PassOptionalNullableEnumWithDefault(self, _: Option<TestEnum>) {} // fn PassOptionalNullableEnumWithDefault(self, _: Option<TestEnum>) {}
fn PassOptionalNullableInterfaceWithDefault(&self, _: Option<&Blob>) {} fn PassOptionalNullableInterfaceWithDefault(&self, _: Option<&Blob>) {}
#[allow(unsafe_code)] fn PassOptionalNullableObjectWithDefault(&self, _: SafeJSContext, _: *mut JSObject) {}
unsafe fn PassOptionalNullableObjectWithDefault(&self, _: *mut JSContext, _: *mut JSObject) {}
fn PassOptionalNullableUnionWithDefault(&self, _: Option<HTMLElementOrLong>) {} fn PassOptionalNullableUnionWithDefault(&self, _: Option<HTMLElementOrLong>) {}
fn PassOptionalNullableUnion2WithDefault(&self, _: Option<EventOrString>) {} fn PassOptionalNullableUnion2WithDefault(&self, _: Option<EventOrString>) {}
// fn PassOptionalNullableCallbackFunctionWithDefault(self, _: Option<Function>) {} // fn PassOptionalNullableCallbackFunctionWithDefault(self, _: Option<Function>) {}
fn PassOptionalNullableCallbackInterfaceWithDefault(&self, _: Option<Rc<EventListener>>) {} fn PassOptionalNullableCallbackInterfaceWithDefault(&self, _: Option<Rc<EventListener>>) {}
#[allow(unsafe_code)] fn PassOptionalAnyWithDefault(&self, _: SafeJSContext, _: HandleValue) {}
unsafe fn PassOptionalAnyWithDefault(&self, _: *mut JSContext, _: HandleValue) {}
fn PassOptionalNullableBooleanWithNonNullDefault(&self, _: Option<bool>) {} fn PassOptionalNullableBooleanWithNonNullDefault(&self, _: Option<bool>) {}
fn PassOptionalNullableByteWithNonNullDefault(&self, _: Option<i8>) {} fn PassOptionalNullableByteWithNonNullDefault(&self, _: Option<i8>) {}
@ -883,10 +862,8 @@ impl TestBindingMethods for TestBinding {
fn PassVariadicUnion5(&self, _: Vec<StringOrUnsignedLong>) {} fn PassVariadicUnion5(&self, _: Vec<StringOrUnsignedLong>) {}
fn PassVariadicUnion6(&self, _: Vec<UnsignedLongOrBoolean>) {} fn PassVariadicUnion6(&self, _: Vec<UnsignedLongOrBoolean>) {}
fn PassVariadicUnion7(&self, _: Vec<ByteStringOrLong>) {} fn PassVariadicUnion7(&self, _: Vec<ByteStringOrLong>) {}
#[allow(unsafe_code)] fn PassVariadicAny(&self, _: SafeJSContext, _: Vec<HandleValue>) {}
unsafe fn PassVariadicAny(&self, _: *mut JSContext, _: Vec<HandleValue>) {} fn PassVariadicObject(&self, _: SafeJSContext, _: Vec<*mut JSObject>) {}
#[allow(unsafe_code)]
unsafe fn PassVariadicObject(&self, _: *mut JSContext, _: Vec<*mut JSObject>) {}
fn BooleanMozPreference(&self, pref_name: DOMString) -> bool { fn BooleanMozPreference(&self, pref_name: DOMString) -> bool {
prefs::pref_map() prefs::pref_map()
.get(pref_name.as_ref()) .get(pref_name.as_ref())
@ -965,32 +942,28 @@ impl TestBindingMethods for TestBinding {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn ReturnResolvedPromise( fn ReturnResolvedPromise(&self, cx: SafeJSContext, v: HandleValue) -> Fallible<Rc<Promise>> {
&self, unsafe { Promise::new_resolved(&self.global(), *cx, v) }
cx: *mut JSContext,
v: HandleValue,
) -> Fallible<Rc<Promise>> {
Promise::new_resolved(&self.global(), cx, v)
} }
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn ReturnRejectedPromise( fn ReturnRejectedPromise(&self, cx: SafeJSContext, v: HandleValue) -> Fallible<Rc<Promise>> {
&self, unsafe { Promise::new_rejected(&self.global(), *cx, v) }
cx: *mut JSContext,
v: HandleValue,
) -> Fallible<Rc<Promise>> {
Promise::new_rejected(&self.global(), cx, v)
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn PromiseResolveNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { fn PromiseResolveNative(&self, cx: SafeJSContext, p: &Promise, v: HandleValue) {
p.resolve(cx, v); unsafe {
p.resolve(*cx, v);
}
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn PromiseRejectNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { fn PromiseRejectNative(&self, cx: SafeJSContext, p: &Promise, v: HandleValue) {
p.reject(cx, v); unsafe {
p.reject(*cx, v);
}
} }
fn PromiseRejectWithTypeError(&self, p: &Promise, s: USVString) { fn PromiseRejectWithTypeError(&self, p: &Promise, s: USVString) {

View file

@ -9,8 +9,9 @@ use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::JSObject;
use js::typedarray::{CreateWith, Uint8Array}; use js::typedarray::{CreateWith, Uint8Array};
use std::ptr; use std::ptr;
use std::ptr::NonNull; use std::ptr::NonNull;
@ -49,14 +50,17 @@ impl TextEncoderMethods for TextEncoder {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://encoding.spec.whatwg.org/#dom-textencoder-encode // https://encoding.spec.whatwg.org/#dom-textencoder-encode
unsafe fn Encode(&self, cx: *mut JSContext, input: USVString) -> NonNull<JSObject> { fn Encode(&self, cx: JSContext, input: USVString) -> NonNull<JSObject> {
let encoded = input.0.as_bytes(); let encoded = input.0.as_bytes();
rooted!(in(cx) let mut js_object = ptr::null_mut::<JSObject>()); unsafe {
assert!( rooted!(in(*cx) let mut js_object = ptr::null_mut::<JSObject>());
Uint8Array::create(cx, CreateWith::Slice(&encoded), js_object.handle_mut()).is_ok() assert!(
); Uint8Array::create(*cx, CreateWith::Slice(&encoded), js_object.handle_mut())
.is_ok()
);
NonNull::new_unchecked(js_object.get()) NonNull::new_unchecked(js_object.get())
}
} }
} }

View file

@ -9,8 +9,9 @@ use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::vrfieldofview::VRFieldOfView; use crate::dom::vrfieldofview::VRFieldOfView;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use js::typedarray::{CreateWith, Float32Array}; use js::typedarray::{CreateWith, Float32Array};
use std::default::Default; use std::default::Default;
use std::ptr; use std::ptr;
@ -67,8 +68,8 @@ impl VREyeParameters {
impl VREyeParametersMethods for VREyeParameters { impl VREyeParametersMethods for VREyeParameters {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vreyeparameters-offset // https://w3c.github.io/webvr/#dom-vreyeparameters-offset
unsafe fn Offset(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn Offset(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.offset.get()) unsafe { NonNull::new_unchecked(self.offset.get()) }
} }
// https://w3c.github.io/webvr/#dom-vreyeparameters-fieldofview // https://w3c.github.io/webvr/#dom-vreyeparameters-fieldofview

View file

@ -11,8 +11,9 @@ use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::vrpose::VRPose; use crate::dom::vrpose::VRPose;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use js::typedarray::{CreateWith, Float32Array}; use js::typedarray::{CreateWith, Float32Array};
use std::cell::Cell; use std::cell::Cell;
use std::ptr; use std::ptr;
@ -61,13 +62,11 @@ impl VRFrameData {
global, global,
VRFrameDataBinding::Wrap, VRFrameDataBinding::Wrap,
); );
let cx = global.get_cx(); let cx = unsafe { JSContext::from_ptr(global.get_cx()) };
unsafe { create_typed_array(cx, &matrix, &root.left_proj);
create_typed_array(cx, &matrix, &root.left_proj); create_typed_array(cx, &matrix, &root.left_view);
create_typed_array(cx, &matrix, &root.left_view); create_typed_array(cx, &matrix, &root.right_proj);
create_typed_array(cx, &matrix, &root.right_proj); create_typed_array(cx, &matrix, &root.right_view);
create_typed_array(cx, &matrix, &root.right_view);
}
root root
} }
@ -79,9 +78,11 @@ impl VRFrameData {
/// FIXME(#22526) this should be in a better place /// FIXME(#22526) this should be in a better place
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub unsafe fn create_typed_array(cx: *mut JSContext, src: &[f32], dst: &Heap<*mut JSObject>) { pub fn create_typed_array(cx: JSContext, src: &[f32], dst: &Heap<*mut JSObject>) {
rooted!(in (cx) let mut array = ptr::null_mut::<JSObject>()); rooted!(in (*cx) let mut array = ptr::null_mut::<JSObject>());
let _ = Float32Array::create(cx, CreateWith::Slice(src), array.handle_mut()); unsafe {
let _ = Float32Array::create(*cx, CreateWith::Slice(src), array.handle_mut());
}
(*dst).set(array.get()); (*dst).set(array.get());
} }
@ -89,28 +90,28 @@ impl VRFrameData {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn update(&self, data: &WebVRFrameData) { pub fn update(&self, data: &WebVRFrameData) {
unsafe { unsafe {
let cx = self.global().get_cx(); let cx = JSContext::from_ptr(self.global().get_cx());
typedarray!(in(cx) let left_proj_array: Float32Array = self.left_proj.get()); typedarray!(in(*cx) let left_proj_array: Float32Array = self.left_proj.get());
if let Ok(mut array) = left_proj_array { if let Ok(mut array) = left_proj_array {
array.update(&data.left_projection_matrix); array.update(&data.left_projection_matrix);
} }
typedarray!(in(cx) let left_view_array: Float32Array = self.left_view.get()); typedarray!(in(*cx) let left_view_array: Float32Array = self.left_view.get());
if let Ok(mut array) = left_view_array { if let Ok(mut array) = left_view_array {
array.update(&data.left_view_matrix); array.update(&data.left_view_matrix);
} }
typedarray!(in(cx) let right_proj_array: Float32Array = self.right_proj.get()); typedarray!(in(*cx) let right_proj_array: Float32Array = self.right_proj.get());
if let Ok(mut array) = right_proj_array { if let Ok(mut array) = right_proj_array {
array.update(&data.right_projection_matrix); array.update(&data.right_projection_matrix);
} }
typedarray!(in(cx) let right_view_array: Float32Array = self.right_view.get()); typedarray!(in(*cx) let right_view_array: Float32Array = self.right_view.get());
if let Ok(mut array) = right_view_array { if let Ok(mut array) = right_view_array {
array.update(&data.right_view_matrix); array.update(&data.right_view_matrix);
} }
} self.pose.update(&data.pose);
self.pose.update(&data.pose); self.timestamp.set(data.timestamp);
self.timestamp.set(data.timestamp); if self.first_timestamp.get() == 0.0 {
if self.first_timestamp.get() == 0.0 { self.first_timestamp.set(data.timestamp);
self.first_timestamp.set(data.timestamp); }
} }
} }
} }
@ -123,26 +124,26 @@ impl VRFrameDataMethods for VRFrameData {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-leftprojectionmatrix // https://w3c.github.io/webvr/#dom-vrframedata-leftprojectionmatrix
unsafe fn LeftProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn LeftProjectionMatrix(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.left_proj.get()) unsafe { NonNull::new_unchecked(self.left_proj.get()) }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-leftviewmatrix // https://w3c.github.io/webvr/#dom-vrframedata-leftviewmatrix
unsafe fn LeftViewMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn LeftViewMatrix(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.left_view.get()) unsafe { NonNull::new_unchecked(self.left_view.get()) }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-rightprojectionmatrix // https://w3c.github.io/webvr/#dom-vrframedata-rightprojectionmatrix
unsafe fn RightProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn RightProjectionMatrix(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.right_proj.get()) unsafe { NonNull::new_unchecked(self.right_proj.get()) }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrframedata-rightviewmatrix // https://w3c.github.io/webvr/#dom-vrframedata-rightviewmatrix
unsafe fn RightViewMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn RightViewMatrix(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.right_view.get()) unsafe { NonNull::new_unchecked(self.right_view.get()) }
} }
// https://w3c.github.io/webvr/#dom-vrframedata-pose // https://w3c.github.io/webvr/#dom-vrframedata-pose

View file

@ -7,6 +7,7 @@ use crate::dom::bindings::codegen::Bindings::VRPoseBinding::VRPoseMethods;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::DomRoot;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext as SafeJSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSContext, JSObject};
use js::typedarray::{CreateWith, Float32Array}; use js::typedarray::{CreateWith, Float32Array};
@ -131,39 +132,33 @@ impl VRPose {
} }
impl VRPoseMethods for VRPose { impl VRPoseMethods for VRPose {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-position // https://w3c.github.io/webvr/#dom-vrpose-position
unsafe fn GetPosition(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetPosition(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.position) heap_to_option(&self.position)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-linearvelocity // https://w3c.github.io/webvr/#dom-vrpose-linearvelocity
unsafe fn GetLinearVelocity(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetLinearVelocity(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.linear_vel) heap_to_option(&self.linear_vel)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-linearacceleration // https://w3c.github.io/webvr/#dom-vrpose-linearacceleration
unsafe fn GetLinearAcceleration(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetLinearAcceleration(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.linear_acc) heap_to_option(&self.linear_acc)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-orientation // https://w3c.github.io/webvr/#dom-vrpose-orientation
unsafe fn GetOrientation(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetOrientation(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.orientation) heap_to_option(&self.orientation)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-angularvelocity // https://w3c.github.io/webvr/#dom-vrpose-angularvelocity
unsafe fn GetAngularVelocity(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetAngularVelocity(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.angular_vel) heap_to_option(&self.angular_vel)
} }
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrpose-angularacceleration // https://w3c.github.io/webvr/#dom-vrpose-angularacceleration
unsafe fn GetAngularAcceleration(&self, _cx: *mut JSContext) -> Option<NonNull<JSObject>> { fn GetAngularAcceleration(&self, _cx: SafeJSContext) -> Option<NonNull<JSObject>> {
heap_to_option(&self.angular_acc) heap_to_option(&self.angular_acc)
} }
} }

View file

@ -9,8 +9,9 @@ use crate::dom::bindings::num::Finite;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::root::DomRoot;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use js::typedarray::{CreateWith, Float32Array}; use js::typedarray::{CreateWith, Float32Array};
use std::ptr; use std::ptr;
use std::ptr::NonNull; use std::ptr::NonNull;
@ -78,8 +79,8 @@ impl VRStageParameters {
impl VRStageParametersMethods for VRStageParameters { impl VRStageParametersMethods for VRStageParameters {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform // https://w3c.github.io/webvr/#dom-vrstageparameters-sittingtostandingtransform
unsafe fn SittingToStandingTransform(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn SittingToStandingTransform(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new_unchecked(self.transform.get()) unsafe { NonNull::new_unchecked(self.transform.get()) }
} }
// https://w3c.github.io/webvr/#dom-vrstageparameters-sizex // https://w3c.github.io/webvr/#dom-vrstageparameters-sizex

View file

@ -29,11 +29,12 @@ use crate::dom::webglshaderprecisionformat::WebGLShaderPrecisionFormat;
use crate::dom::webgltexture::WebGLTexture; use crate::dom::webgltexture::WebGLTexture;
use crate::dom::webgluniformlocation::WebGLUniformLocation; use crate::dom::webgluniformlocation::WebGLUniformLocation;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext;
/// https://www.khronos.org/registry/webgl/specs/latest/2.0/webgl.idl /// https://www.khronos.org/registry/webgl/specs/latest/2.0/webgl.idl
use canvas_traits::webgl::{GLContextAttributes, WebGLVersion}; use canvas_traits::webgl::{GLContextAttributes, WebGLVersion};
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::default::Size2D; use euclid::default::Size2D;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::JSObject;
use js::jsval::JSVal; use js::jsval::JSVal;
use js::rust::CustomAutoRooterGuard; use js::rust::CustomAutoRooterGuard;
use js::typedarray::ArrayBufferView; use js::typedarray::ArrayBufferView;
@ -109,21 +110,19 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
self.base.DrawingBufferHeight() self.base.DrawingBufferHeight()
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5
unsafe fn GetBufferParameter(&self, _cx: *mut JSContext, target: u32, parameter: u32) -> JSVal { fn GetBufferParameter(&self, cx: JSContext, target: u32, parameter: u32) -> JSVal {
self.base.GetBufferParameter(_cx, target, parameter) self.base.GetBufferParameter(cx, target, parameter)
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3
unsafe fn GetParameter(&self, cx: *mut JSContext, parameter: u32) -> JSVal { fn GetParameter(&self, cx: JSContext, parameter: u32) -> JSVal {
self.base.GetParameter(cx, parameter) self.base.GetParameter(cx, parameter)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8
unsafe fn GetTexParameter(&self, cx: *mut JSContext, target: u32, pname: u32) -> JSVal { fn GetTexParameter(&self, cx: JSContext, target: u32, pname: u32) -> JSVal {
self.base.GetTexParameter(cx, target, pname) self.base.GetTexParameter(cx, target, pname)
} }
@ -142,21 +141,15 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
self.base.GetSupportedExtensions() self.base.GetSupportedExtensions()
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14
unsafe fn GetExtension( fn GetExtension(&self, cx: JSContext, name: DOMString) -> Option<NonNull<JSObject>> {
&self,
cx: *mut JSContext,
name: DOMString,
) -> Option<NonNull<JSObject>> {
self.base.GetExtension(cx, name) self.base.GetExtension(cx, name)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/2.0/#3.7.4 /// https://www.khronos.org/registry/webgl/specs/latest/2.0/#3.7.4
unsafe fn GetFramebufferAttachmentParameter( fn GetFramebufferAttachmentParameter(
&self, &self,
cx: *mut JSContext, cx: JSContext,
target: u32, target: u32,
attachment: u32, attachment: u32,
pname: u32, pname: u32,
@ -165,14 +158,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
.GetFramebufferAttachmentParameter(cx, target, attachment, pname) .GetFramebufferAttachmentParameter(cx, target, attachment, pname)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7
unsafe fn GetRenderbufferParameter( fn GetRenderbufferParameter(&self, cx: JSContext, target: u32, pname: u32) -> JSVal {
&self,
cx: *mut JSContext,
target: u32,
pname: u32,
) -> JSVal {
self.base.GetRenderbufferParameter(cx, target, pname) self.base.GetRenderbufferParameter(cx, target, pname)
} }
@ -505,14 +492,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
self.base.GetProgramInfoLog(program) self.base.GetProgramInfoLog(program)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetProgramParameter( fn GetProgramParameter(&self, cx: JSContext, program: &WebGLProgram, param_id: u32) -> JSVal {
&self,
cx: *mut JSContext,
program: &WebGLProgram,
param_id: u32,
) -> JSVal {
self.base.GetProgramParameter(cx, program, param_id) self.base.GetProgramParameter(cx, program, param_id)
} }
@ -521,14 +502,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
self.base.GetShaderInfoLog(shader) self.base.GetShaderInfoLog(shader)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetShaderParameter( fn GetShaderParameter(&self, cx: JSContext, shader: &WebGLShader, param_id: u32) -> JSVal {
&self,
cx: *mut JSContext,
shader: &WebGLShader,
param_id: u32,
) -> JSVal {
self.base.GetShaderParameter(cx, shader, param_id) self.base.GetShaderParameter(cx, shader, param_id)
} }
@ -551,9 +526,8 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
self.base.GetUniformLocation(program, name) self.base.GetUniformLocation(program, name)
} }
#[allow(unsafe_code)]
/// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 /// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetVertexAttrib(&self, cx: *mut JSContext, index: u32, pname: u32) -> JSVal { fn GetVertexAttrib(&self, cx: JSContext, index: u32, pname: u32) -> JSVal {
self.base.GetVertexAttrib(cx, index, pname) self.base.GetVertexAttrib(cx, index, pname)
} }
@ -815,10 +789,9 @@ impl WebGL2RenderingContextMethods for WebGL2RenderingContext {
} }
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10
#[allow(unsafe_code)] fn GetUniform(
unsafe fn GetUniform(
&self, &self,
cx: *mut JSContext, cx: JSContext,
program: &WebGLProgram, program: &WebGLProgram,
location: &WebGLUniformLocation, location: &WebGLUniformLocation,
) -> JSVal { ) -> JSVal {

View file

@ -48,6 +48,7 @@ use crate::dom::webgltexture::{TexParameterValue, WebGLTexture};
use crate::dom::webgluniformlocation::WebGLUniformLocation; use crate::dom::webgluniformlocation::WebGLUniformLocation;
use crate::dom::webglvertexarrayobjectoes::WebGLVertexArrayObjectOES; use crate::dom::webglvertexarrayobjectoes::WebGLVertexArrayObjectOES;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext as SafeJSContext;
#[cfg(feature = "webgl_backtrace")] #[cfg(feature = "webgl_backtrace")]
use backtrace::Backtrace; use backtrace::Backtrace;
use canvas_traits::webgl::WebGLError::*; use canvas_traits::webgl::WebGLError::*;
@ -1148,9 +1149,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
receiver.recv().unwrap() receiver.recv().unwrap()
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5
unsafe fn GetBufferParameter(&self, _cx: *mut JSContext, target: u32, parameter: u32) -> JSVal { fn GetBufferParameter(&self, _cx: SafeJSContext, target: u32, parameter: u32) -> JSVal {
let buffer = handle_potential_webgl_error!( let buffer = handle_potential_webgl_error!(
self, self,
self.bound_buffer(target) self.bound_buffer(target)
@ -1170,7 +1170,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3
unsafe fn GetParameter(&self, cx: *mut JSContext, parameter: u32) -> JSVal { fn GetParameter(&self, cx: SafeJSContext, parameter: u32) -> JSVal {
if !self if !self
.extension_manager .extension_manager
.is_get_parameter_name_enabled(parameter) .is_get_parameter_name_enabled(parameter)
@ -1180,41 +1180,41 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
} }
match parameter { match parameter {
constants::ARRAY_BUFFER_BINDING => { constants::ARRAY_BUFFER_BINDING => unsafe {
return optional_root_object_to_js_or_null!(cx, &self.bound_buffer_array.get()); return optional_root_object_to_js_or_null!(*cx, &self.bound_buffer_array.get());
}, },
constants::CURRENT_PROGRAM => { constants::CURRENT_PROGRAM => unsafe {
return optional_root_object_to_js_or_null!(cx, &self.current_program.get()); return optional_root_object_to_js_or_null!(*cx, &self.current_program.get());
}, },
constants::ELEMENT_ARRAY_BUFFER_BINDING => { constants::ELEMENT_ARRAY_BUFFER_BINDING => unsafe {
let buffer = self.current_vao().element_array_buffer().get(); let buffer = self.current_vao().element_array_buffer().get();
return optional_root_object_to_js_or_null!(cx, buffer); return optional_root_object_to_js_or_null!(*cx, buffer);
}, },
constants::FRAMEBUFFER_BINDING => { constants::FRAMEBUFFER_BINDING => unsafe {
return optional_root_object_to_js_or_null!(cx, &self.bound_framebuffer.get()); return optional_root_object_to_js_or_null!(*cx, &self.bound_framebuffer.get());
}, },
constants::RENDERBUFFER_BINDING => { constants::RENDERBUFFER_BINDING => unsafe {
return optional_root_object_to_js_or_null!(cx, &self.bound_renderbuffer.get()); return optional_root_object_to_js_or_null!(*cx, &self.bound_renderbuffer.get());
}, },
constants::TEXTURE_BINDING_2D => { constants::TEXTURE_BINDING_2D => unsafe {
let texture = self let texture = self
.textures .textures
.active_texture_slot(constants::TEXTURE_2D) .active_texture_slot(constants::TEXTURE_2D)
.unwrap() .unwrap()
.get(); .get();
return optional_root_object_to_js_or_null!(cx, texture); return optional_root_object_to_js_or_null!(*cx, texture);
}, },
constants::TEXTURE_BINDING_CUBE_MAP => { constants::TEXTURE_BINDING_CUBE_MAP => unsafe {
let texture = self let texture = self
.textures .textures
.active_texture_slot(constants::TEXTURE_CUBE_MAP) .active_texture_slot(constants::TEXTURE_CUBE_MAP)
.unwrap() .unwrap()
.get(); .get();
return optional_root_object_to_js_or_null!(cx, texture); return optional_root_object_to_js_or_null!(*cx, texture);
}, },
OESVertexArrayObjectConstants::VERTEX_ARRAY_BINDING_OES => { OESVertexArrayObjectConstants::VERTEX_ARRAY_BINDING_OES => unsafe {
let vao = self.current_vao.get().filter(|vao| vao.id().is_some()); let vao = self.current_vao.get().filter(|vao| vao.id().is_some());
return optional_root_object_to_js_or_null!(cx, vao); return optional_root_object_to_js_or_null!(*cx, vao);
}, },
// In readPixels we currently support RGBA/UBYTE only. If // In readPixels we currently support RGBA/UBYTE only. If
// we wanted to support other formats, we could ask the // we wanted to support other formats, we could ask the
@ -1227,27 +1227,27 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
constants::IMPLEMENTATION_COLOR_READ_TYPE => { constants::IMPLEMENTATION_COLOR_READ_TYPE => {
return Int32Value(constants::UNSIGNED_BYTE as i32); return Int32Value(constants::UNSIGNED_BYTE as i32);
}, },
constants::COMPRESSED_TEXTURE_FORMATS => { constants::COMPRESSED_TEXTURE_FORMATS => unsafe {
let format_ids = self.extension_manager.get_tex_compression_ids(); let format_ids = self.extension_manager.get_tex_compression_ids();
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let _ = Uint32Array::create(cx, CreateWith::Slice(&format_ids), rval.handle_mut()) let _ = Uint32Array::create(*cx, CreateWith::Slice(&format_ids), rval.handle_mut())
.unwrap(); .unwrap();
return ObjectValue(rval.get()); return ObjectValue(rval.get());
}, },
constants::VERSION => { constants::VERSION => unsafe {
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
"WebGL 1.0".to_jsval(cx, rval.handle_mut()); "WebGL 1.0".to_jsval(*cx, rval.handle_mut());
return rval.get(); return rval.get();
}, },
constants::RENDERER | constants::VENDOR => { constants::RENDERER | constants::VENDOR => unsafe {
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
"Mozilla/Servo".to_jsval(cx, rval.handle_mut()); "Mozilla/Servo".to_jsval(*cx, rval.handle_mut());
return rval.get(); return rval.get();
}, },
constants::SHADING_LANGUAGE_VERSION => { constants::SHADING_LANGUAGE_VERSION => unsafe {
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
"WebGL GLSL ES 1.0".to_jsval(cx, rval.handle_mut()); "WebGL GLSL ES 1.0".to_jsval(*cx, rval.handle_mut());
return rval.get(); return rval.get();
}, },
constants::UNPACK_FLIP_Y_WEBGL => { constants::UNPACK_FLIP_Y_WEBGL => {
@ -1314,11 +1314,11 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
self.send_command(WebGLCommand::GetParameterBool(param, sender)); self.send_command(WebGLCommand::GetParameterBool(param, sender));
BooleanValue(receiver.recv().unwrap()) BooleanValue(receiver.recv().unwrap())
}, },
Parameter::Bool4(param) => { Parameter::Bool4(param) => unsafe {
let (sender, receiver) = webgl_channel().unwrap(); let (sender, receiver) = webgl_channel().unwrap();
self.send_command(WebGLCommand::GetParameterBool4(param, sender)); self.send_command(WebGLCommand::GetParameterBool4(param, sender));
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
receiver.recv().unwrap().to_jsval(cx, rval.handle_mut()); receiver.recv().unwrap().to_jsval(*cx, rval.handle_mut());
rval.get() rval.get()
}, },
Parameter::Int(param) => { Parameter::Int(param) => {
@ -1326,24 +1326,24 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
self.send_command(WebGLCommand::GetParameterInt(param, sender)); self.send_command(WebGLCommand::GetParameterInt(param, sender));
Int32Value(receiver.recv().unwrap()) Int32Value(receiver.recv().unwrap())
}, },
Parameter::Int2(param) => { Parameter::Int2(param) => unsafe {
let (sender, receiver) = webgl_channel().unwrap(); let (sender, receiver) = webgl_channel().unwrap();
self.send_command(WebGLCommand::GetParameterInt2(param, sender)); self.send_command(WebGLCommand::GetParameterInt2(param, sender));
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let _ = Int32Array::create( let _ = Int32Array::create(
cx, *cx,
CreateWith::Slice(&receiver.recv().unwrap()), CreateWith::Slice(&receiver.recv().unwrap()),
rval.handle_mut(), rval.handle_mut(),
) )
.unwrap(); .unwrap();
ObjectValue(rval.get()) ObjectValue(rval.get())
}, },
Parameter::Int4(param) => { Parameter::Int4(param) => unsafe {
let (sender, receiver) = webgl_channel().unwrap(); let (sender, receiver) = webgl_channel().unwrap();
self.send_command(WebGLCommand::GetParameterInt4(param, sender)); self.send_command(WebGLCommand::GetParameterInt4(param, sender));
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let _ = Int32Array::create( let _ = Int32Array::create(
cx, *cx,
CreateWith::Slice(&receiver.recv().unwrap()), CreateWith::Slice(&receiver.recv().unwrap()),
rval.handle_mut(), rval.handle_mut(),
) )
@ -1355,24 +1355,24 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
self.send_command(WebGLCommand::GetParameterFloat(param, sender)); self.send_command(WebGLCommand::GetParameterFloat(param, sender));
DoubleValue(receiver.recv().unwrap() as f64) DoubleValue(receiver.recv().unwrap() as f64)
}, },
Parameter::Float2(param) => { Parameter::Float2(param) => unsafe {
let (sender, receiver) = webgl_channel().unwrap(); let (sender, receiver) = webgl_channel().unwrap();
self.send_command(WebGLCommand::GetParameterFloat2(param, sender)); self.send_command(WebGLCommand::GetParameterFloat2(param, sender));
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let _ = Float32Array::create( let _ = Float32Array::create(
cx, *cx,
CreateWith::Slice(&receiver.recv().unwrap()), CreateWith::Slice(&receiver.recv().unwrap()),
rval.handle_mut(), rval.handle_mut(),
) )
.unwrap(); .unwrap();
ObjectValue(rval.get()) ObjectValue(rval.get())
}, },
Parameter::Float4(param) => { Parameter::Float4(param) => unsafe {
let (sender, receiver) = webgl_channel().unwrap(); let (sender, receiver) = webgl_channel().unwrap();
self.send_command(WebGLCommand::GetParameterFloat4(param, sender)); self.send_command(WebGLCommand::GetParameterFloat4(param, sender));
rooted!(in(cx) let mut rval = ptr::null_mut::<JSObject>()); rooted!(in(*cx) let mut rval = ptr::null_mut::<JSObject>());
let _ = Float32Array::create( let _ = Float32Array::create(
cx, *cx,
CreateWith::Slice(&receiver.recv().unwrap()), CreateWith::Slice(&receiver.recv().unwrap()),
rval.handle_mut(), rval.handle_mut(),
) )
@ -1382,9 +1382,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
} }
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8
unsafe fn GetTexParameter(&self, _cx: *mut JSContext, target: u32, pname: u32) -> JSVal { fn GetTexParameter(&self, _cx: SafeJSContext, target: u32, pname: u32) -> JSVal {
let texture_slot = handle_potential_webgl_error!( let texture_slot = handle_potential_webgl_error!(
self, self,
self.textures.active_texture_slot(target), self.textures.active_texture_slot(target),
@ -1484,13 +1483,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
) )
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14
unsafe fn GetExtension( fn GetExtension(&self, _cx: SafeJSContext, name: DOMString) -> Option<NonNull<JSObject>> {
&self,
_cx: *mut JSContext,
name: DOMString,
) -> Option<NonNull<JSObject>> {
self.extension_manager self.extension_manager
.init_once(|| self.get_gl_extensions()); .init_once(|| self.get_gl_extensions());
self.extension_manager.get_or_init_extension(&name, self) self.extension_manager.get_or_init_extension(&name, self)
@ -2326,9 +2320,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6
unsafe fn GetFramebufferAttachmentParameter( fn GetFramebufferAttachmentParameter(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
target: u32, target: u32,
attachment: u32, attachment: u32,
pname: u32, pname: u32,
@ -2411,14 +2405,14 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
let fb = self.bound_framebuffer.get().unwrap(); let fb = self.bound_framebuffer.get().unwrap();
if let Some(webgl_attachment) = fb.attachment(attachment) { if let Some(webgl_attachment) = fb.attachment(attachment) {
match webgl_attachment { match webgl_attachment {
WebGLFramebufferAttachmentRoot::Renderbuffer(rb) => { WebGLFramebufferAttachmentRoot::Renderbuffer(rb) => unsafe {
rooted!(in(cx) let mut rval = NullValue()); rooted!(in(*cx) let mut rval = NullValue());
rb.to_jsval(cx, rval.handle_mut()); rb.to_jsval(*cx, rval.handle_mut());
return rval.get(); return rval.get();
}, },
WebGLFramebufferAttachmentRoot::Texture(texture) => { WebGLFramebufferAttachmentRoot::Texture(texture) => unsafe {
rooted!(in(cx) let mut rval = NullValue()); rooted!(in(*cx) let mut rval = NullValue());
texture.to_jsval(cx, rval.handle_mut()); texture.to_jsval(*cx, rval.handle_mut());
return rval.get(); return rval.get();
}, },
} }
@ -2435,14 +2429,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
Int32Value(receiver.recv().unwrap()) Int32Value(receiver.recv().unwrap())
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7
unsafe fn GetRenderbufferParameter( fn GetRenderbufferParameter(&self, _cx: SafeJSContext, target: u32, pname: u32) -> JSVal {
&self,
_cx: *mut JSContext,
target: u32,
pname: u32,
) -> JSVal {
let target_matches = target == constants::RENDERBUFFER; let target_matches = target == constants::RENDERBUFFER;
let pname_matches = match pname { let pname_matches = match pname {
@ -2494,14 +2482,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
} }
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetProgramParameter( fn GetProgramParameter(&self, _: SafeJSContext, program: &WebGLProgram, param: u32) -> JSVal {
&self,
_: *mut JSContext,
program: &WebGLProgram,
param: u32,
) -> JSVal {
handle_potential_webgl_error!(self, self.validate_ownership(program), return NullValue()); handle_potential_webgl_error!(self, self.validate_ownership(program), return NullValue());
if program.is_deleted() { if program.is_deleted() {
self.webgl_error(InvalidOperation); self.webgl_error(InvalidOperation);
@ -2541,14 +2523,8 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
Some(shader.info_log()) Some(shader.info_log())
} }
#[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetShaderParameter( fn GetShaderParameter(&self, _: SafeJSContext, shader: &WebGLShader, param: u32) -> JSVal {
&self,
_: *mut JSContext,
shader: &WebGLShader,
param: u32,
) -> JSVal {
handle_potential_webgl_error!(self, self.validate_ownership(shader), return NullValue()); handle_potential_webgl_error!(self, self.validate_ownership(shader), return NullValue());
if shader.is_deleted() { if shader.is_deleted() {
self.webgl_error(InvalidValue); self.webgl_error(InvalidValue);
@ -2620,7 +2596,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
unsafe fn GetVertexAttrib(&self, cx: *mut JSContext, index: u32, param: u32) -> JSVal { fn GetVertexAttrib(&self, cx: SafeJSContext, index: u32, param: u32) -> JSVal {
let current_vao = self.current_vao(); let current_vao = self.current_vao();
let data = handle_potential_webgl_error!( let data = handle_potential_webgl_error!(
self, self,
@ -2636,10 +2612,12 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
self.send_command(WebGLCommand::GetCurrentVertexAttrib(index, sender)); self.send_command(WebGLCommand::GetCurrentVertexAttrib(index, sender));
receiver.recv().unwrap() receiver.recv().unwrap()
}; };
rooted!(in(cx) let mut result = ptr::null_mut::<JSObject>()); unsafe {
let _ = rooted!(in(*cx) let mut result = ptr::null_mut::<JSObject>());
Float32Array::create(cx, CreateWith::Slice(&value), result.handle_mut()).unwrap(); let _ = Float32Array::create(*cx, CreateWith::Slice(&value), result.handle_mut())
return ObjectValue(result.get()); .unwrap();
return ObjectValue(result.get());
}
} }
if !self if !self
@ -2656,10 +2634,10 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
constants::VERTEX_ATTRIB_ARRAY_TYPE => Int32Value(data.type_ as i32), constants::VERTEX_ATTRIB_ARRAY_TYPE => Int32Value(data.type_ as i32),
constants::VERTEX_ATTRIB_ARRAY_NORMALIZED => BooleanValue(data.normalized), constants::VERTEX_ATTRIB_ARRAY_NORMALIZED => BooleanValue(data.normalized),
constants::VERTEX_ATTRIB_ARRAY_STRIDE => Int32Value(data.stride as i32), constants::VERTEX_ATTRIB_ARRAY_STRIDE => Int32Value(data.stride as i32),
constants::VERTEX_ATTRIB_ARRAY_BUFFER_BINDING => { constants::VERTEX_ATTRIB_ARRAY_BUFFER_BINDING => unsafe {
rooted!(in(cx) let mut jsval = NullValue()); rooted!(in(*cx) let mut jsval = NullValue());
if let Some(buffer) = data.buffer() { if let Some(buffer) = data.buffer() {
buffer.to_jsval(cx, jsval.handle_mut()); buffer.to_jsval(*cx, jsval.handle_mut());
} }
jsval.get() jsval.get()
}, },
@ -3432,9 +3410,9 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
// https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10 // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn GetUniform( fn GetUniform(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
program: &WebGLProgram, program: &WebGLProgram,
location: &WebGLUniformLocation, location: &WebGLUniformLocation,
) -> JSVal { ) -> JSVal {
@ -3477,42 +3455,48 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext {
match location.type_() { match location.type_() {
constants::BOOL => BooleanValue(get(triple, WebGLCommand::GetUniformBool)), constants::BOOL => BooleanValue(get(triple, WebGLCommand::GetUniformBool)),
constants::BOOL_VEC2 => { constants::BOOL_VEC2 => unsafe {
rooted!(in(cx) let mut rval = NullValue()); rooted!(in(*cx) let mut rval = NullValue());
get(triple, WebGLCommand::GetUniformBool2).to_jsval(cx, rval.handle_mut()); get(triple, WebGLCommand::GetUniformBool2).to_jsval(*cx, rval.handle_mut());
rval.get() rval.get()
}, },
constants::BOOL_VEC3 => { constants::BOOL_VEC3 => unsafe {
rooted!(in(cx) let mut rval = NullValue()); rooted!(in(*cx) let mut rval = NullValue());
get(triple, WebGLCommand::GetUniformBool3).to_jsval(cx, rval.handle_mut()); get(triple, WebGLCommand::GetUniformBool3).to_jsval(*cx, rval.handle_mut());
rval.get() rval.get()
}, },
constants::BOOL_VEC4 => { constants::BOOL_VEC4 => unsafe {
rooted!(in(cx) let mut rval = NullValue()); rooted!(in(*cx) let mut rval = NullValue());
get(triple, WebGLCommand::GetUniformBool4).to_jsval(cx, rval.handle_mut()); get(triple, WebGLCommand::GetUniformBool4).to_jsval(*cx, rval.handle_mut());
rval.get() rval.get()
}, },
constants::INT | constants::SAMPLER_2D | constants::SAMPLER_CUBE => { constants::INT | constants::SAMPLER_2D | constants::SAMPLER_CUBE => {
Int32Value(get(triple, WebGLCommand::GetUniformInt)) Int32Value(get(triple, WebGLCommand::GetUniformInt))
}, },
constants::INT_VEC2 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt2)), constants::INT_VEC2 => unsafe {
constants::INT_VEC3 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt3)), typed::<Int32>(*cx, &get(triple, WebGLCommand::GetUniformInt2))
constants::INT_VEC4 => typed::<Int32>(cx, &get(triple, WebGLCommand::GetUniformInt4)), },
constants::INT_VEC3 => unsafe {
typed::<Int32>(*cx, &get(triple, WebGLCommand::GetUniformInt3))
},
constants::INT_VEC4 => unsafe {
typed::<Int32>(*cx, &get(triple, WebGLCommand::GetUniformInt4))
},
constants::FLOAT => DoubleValue(get(triple, WebGLCommand::GetUniformFloat) as f64), constants::FLOAT => DoubleValue(get(triple, WebGLCommand::GetUniformFloat) as f64),
constants::FLOAT_VEC2 => { constants::FLOAT_VEC2 => unsafe {
typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat2)) typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat2))
}, },
constants::FLOAT_VEC3 => { constants::FLOAT_VEC3 => unsafe {
typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat3)) typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat3))
}, },
constants::FLOAT_VEC4 | constants::FLOAT_MAT2 => { constants::FLOAT_VEC4 | constants::FLOAT_MAT2 => unsafe {
typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat4)) typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat4))
}, },
constants::FLOAT_MAT3 => { constants::FLOAT_MAT3 => unsafe {
typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat9)) typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat9))
}, },
constants::FLOAT_MAT4 => { constants::FLOAT_MAT4 => unsafe {
typed::<Float32>(cx, &get(triple, WebGLCommand::GetUniformFloat16)) typed::<Float32>(*cx, &get(triple, WebGLCommand::GetUniformFloat16))
}, },
_ => panic!("wrong uniform type"), _ => panic!("wrong uniform type"),
} }

View file

@ -615,26 +615,28 @@ impl WindowMethods for Window {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener // https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn Opener(&self, cx: *mut JSContext) -> JSVal { fn Opener(&self, cx: SafeJSContext) -> JSVal {
self.window_proxy().opener(cx) unsafe { self.window_proxy().opener(*cx) }
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener // https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn SetOpener(&self, cx: *mut JSContext, value: HandleValue) { fn SetOpener(&self, cx: SafeJSContext, value: HandleValue) {
// Step 1. // Step 1.
if value.is_null() { if value.is_null() {
return self.window_proxy().disown(); return self.window_proxy().disown();
} }
// Step 2. // Step 2.
let obj = self.reflector().get_jsobject(); let obj = self.reflector().get_jsobject();
assert!(JS_DefineProperty( unsafe {
cx, assert!(JS_DefineProperty(
obj, *cx,
"opener\0".as_ptr() as *const libc::c_char, obj,
value, "opener\0".as_ptr() as *const libc::c_char,
JSPROP_ENUMERATE as u32 value,
)); JSPROP_ENUMERATE as u32
));
}
} }
// https://html.spec.whatwg.org/multipage/#dom-window-closed // https://html.spec.whatwg.org/multipage/#dom-window-closed
@ -739,11 +741,10 @@ impl WindowMethods for Window {
self.navigator.or_init(|| Navigator::new(self)) self.navigator.or_init(|| Navigator::new(self))
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
unsafe fn SetTimeout( fn SetTimeout(
&self, &self,
_cx: *mut JSContext, _cx: SafeJSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -756,11 +757,10 @@ impl WindowMethods for Window {
) )
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
unsafe fn SetTimeout_( fn SetTimeout_(
&self, &self,
_cx: *mut JSContext, _cx: SafeJSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -779,11 +779,10 @@ impl WindowMethods for Window {
.clear_timeout_or_interval(handle); .clear_timeout_or_interval(handle);
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
unsafe fn SetInterval( fn SetInterval(
&self, &self,
_cx: *mut JSContext, _cx: SafeJSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -796,11 +795,10 @@ impl WindowMethods for Window {
) )
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
unsafe fn SetInterval_( fn SetInterval_(
&self, &self,
_cx: *mut JSContext, _cx: SafeJSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -903,11 +901,10 @@ impl WindowMethods for Window {
doc.cancel_animation_frame(ident); doc.cancel_animation_frame(ident);
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-window-postmessage // https://html.spec.whatwg.org/multipage/#dom-window-postmessage
unsafe fn PostMessage( fn PostMessage(
&self, &self,
cx: *mut JSContext, cx: SafeJSContext,
message: HandleValue, message: HandleValue,
origin: DOMString, origin: DOMString,
) -> ErrorResult { ) -> ErrorResult {
@ -926,7 +923,7 @@ impl WindowMethods for Window {
// Step 1-2, 6-8. // Step 1-2, 6-8.
// TODO(#12717): Should implement the `transfer` argument. // TODO(#12717): Should implement the `transfer` argument.
let data = StructuredCloneData::write(cx, message)?; let data = StructuredCloneData::write(*cx, message)?;
// Step 9. // Step 9.
self.post_message(origin, &*source.window_proxy(), data); self.post_message(origin, &*source.window_proxy(), data);
@ -961,8 +958,8 @@ impl WindowMethods for Window {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn WebdriverCallback(&self, cx: *mut JSContext, val: HandleValue) { fn WebdriverCallback(&self, cx: SafeJSContext, val: HandleValue) {
let rv = jsval_to_webdriver(cx, val); let rv = unsafe { jsval_to_webdriver(*cx, val) };
let opt_chan = self.webdriver_script_chan.borrow_mut().take(); let opt_chan = self.webdriver_script_chan.borrow_mut().take();
if let Some(chan) = opt_chan { if let Some(chan) = opt_chan {
chan.send(rv).unwrap(); chan.send(rv).unwrap();

View file

@ -21,12 +21,13 @@ use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope; use crate::dom::globalscope::GlobalScope;
use crate::dom::messageevent::MessageEvent; use crate::dom::messageevent::MessageEvent;
use crate::dom::workerglobalscope::prepare_workerscope_init; use crate::dom::workerglobalscope::prepare_workerscope_init;
use crate::script_runtime::JSContext;
use crate::task::TaskOnce; use crate::task::TaskOnce;
use crossbeam_channel::{unbounded, Sender}; use crossbeam_channel::{unbounded, Sender};
use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg}; use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
use dom_struct::dom_struct; use dom_struct::dom_struct;
use ipc_channel::ipc; use ipc_channel::ipc;
use js::jsapi::{JSContext, JS_RequestInterruptCallback}; use js::jsapi::JS_RequestInterruptCallback;
use js::jsval::UndefinedValue; use js::jsval::UndefinedValue;
use js::rust::HandleValue; use js::rust::HandleValue;
use script_traits::WorkerScriptLoadOrigin; use script_traits::WorkerScriptLoadOrigin;
@ -158,10 +159,9 @@ impl Worker {
} }
impl WorkerMethods for Worker { impl WorkerMethods for Worker {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage // https://html.spec.whatwg.org/multipage/#dom-worker-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult { fn PostMessage(&self, cx: JSContext, message: HandleValue) -> ErrorResult {
let data = StructuredCloneData::write(cx, message)?; let data = StructuredCloneData::write(*cx, message)?;
let address = Trusted::new(self); let address = Trusted::new(self);
// NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage // NOTE: step 9 of https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage

View file

@ -26,6 +26,7 @@ use crate::dom::window::{base64_atob, base64_btoa};
use crate::dom::workerlocation::WorkerLocation; use crate::dom::workerlocation::WorkerLocation;
use crate::dom::workernavigator::WorkerNavigator; use crate::dom::workernavigator::WorkerNavigator;
use crate::fetch; use crate::fetch;
use crate::script_runtime::JSContext as SafeJSContext;
use crate::script_runtime::{get_reports, CommonScriptMsg, Runtime, ScriptChan, ScriptPort}; use crate::script_runtime::{get_reports, CommonScriptMsg, Runtime, ScriptChan, ScriptPort};
use crate::task::TaskCanceller; use crate::task::TaskCanceller;
use crate::task_source::dom_manipulation::DOMManipulationTaskSource; use crate::task_source::dom_manipulation::DOMManipulationTaskSource;
@ -288,11 +289,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
base64_atob(atob) base64_atob(atob)
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
unsafe fn SetTimeout( fn SetTimeout(
&self, &self,
_cx: *mut JSContext, _cx: SafeJSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -305,11 +305,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
) )
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
unsafe fn SetTimeout_( fn SetTimeout_(
&self, &self,
_cx: *mut JSContext, _cx: SafeJSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -328,11 +327,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
.clear_timeout_or_interval(handle); .clear_timeout_or_interval(handle);
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
unsafe fn SetInterval( fn SetInterval(
&self, &self,
_cx: *mut JSContext, _cx: SafeJSContext,
callback: Rc<Function>, callback: Rc<Function>,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,
@ -345,11 +343,10 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope {
) )
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
unsafe fn SetInterval_( fn SetInterval_(
&self, &self,
_cx: *mut JSContext, _cx: SafeJSContext,
callback: DOMString, callback: DOMString,
timeout: i32, timeout: i32,
args: Vec<HandleValue>, args: Vec<HandleValue>,

View file

@ -13,8 +13,8 @@ use crate::dom::document::{Document, DocumentSource, HasBrowsingContext, IsHTMLD
use crate::dom::location::Location; use crate::dom::location::Location;
use crate::dom::node::Node; use crate::dom::node::Node;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::JSContext;
use js::jsapi::JSObject; use js::jsapi::JSObject;
use mime::Mime; use mime::Mime;
use script_traits::DocumentActivity; use script_traits::DocumentActivity;
@ -106,13 +106,8 @@ impl XMLDocumentMethods for XMLDocument {
self.upcast::<Document>().SupportedPropertyNames() self.upcast::<Document>().SupportedPropertyNames()
} }
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter
unsafe fn NamedGetter( fn NamedGetter(&self, _cx: JSContext, name: DOMString) -> Option<NonNull<JSObject>> {
&self,
_cx: *mut JSContext,
name: DOMString,
) -> Option<NonNull<JSObject>> {
self.upcast::<Document>().NamedGetter(_cx, name) self.upcast::<Document>().NamedGetter(_cx, name)
} }
} }

View file

@ -38,6 +38,7 @@ use crate::dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget;
use crate::dom::xmlhttprequestupload::XMLHttpRequestUpload; use crate::dom::xmlhttprequestupload::XMLHttpRequestUpload;
use crate::fetch::FetchCanceller; use crate::fetch::FetchCanceller;
use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener}; use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener};
use crate::script_runtime::JSContext as SafeJSContext;
use crate::task_source::networking::NetworkingTaskSource; use crate::task_source::networking::NetworkingTaskSource;
use crate::task_source::TaskSourceName; use crate::task_source::TaskSourceName;
use crate::timers::{OneshotTimerCallback, OneshotTimerHandle}; use crate::timers::{OneshotTimerCallback, OneshotTimerHandle};
@ -877,19 +878,19 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
#[allow(unsafe_code)] #[allow(unsafe_code)]
// https://xhr.spec.whatwg.org/#the-response-attribute // https://xhr.spec.whatwg.org/#the-response-attribute
unsafe fn Response(&self, cx: *mut JSContext) -> JSVal { fn Response(&self, cx: SafeJSContext) -> JSVal {
rooted!(in(cx) let mut rval = UndefinedValue()); rooted!(in(*cx) let mut rval = UndefinedValue());
match self.response_type.get() { match self.response_type.get() {
XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => { XMLHttpRequestResponseType::_empty | XMLHttpRequestResponseType::Text => unsafe {
let ready_state = self.ready_state.get(); let ready_state = self.ready_state.get();
// Step 2 // Step 2
if ready_state == XMLHttpRequestState::Done || if ready_state == XMLHttpRequestState::Done ||
ready_state == XMLHttpRequestState::Loading ready_state == XMLHttpRequestState::Loading
{ {
self.text_response().to_jsval(cx, rval.handle_mut()); self.text_response().to_jsval(*cx, rval.handle_mut());
} else { } else {
// Step 1 // Step 1
"".to_jsval(cx, rval.handle_mut()); "".to_jsval(*cx, rval.handle_mut());
} }
}, },
// Step 1 // Step 1
@ -897,18 +898,20 @@ impl XMLHttpRequestMethods for XMLHttpRequest {
return NullValue(); return NullValue();
}, },
// Step 2 // Step 2
XMLHttpRequestResponseType::Document => { XMLHttpRequestResponseType::Document => unsafe {
self.document_response().to_jsval(cx, rval.handle_mut()); self.document_response().to_jsval(*cx, rval.handle_mut());
}, },
XMLHttpRequestResponseType::Json => { XMLHttpRequestResponseType::Json => unsafe {
self.json_response(cx).to_jsval(cx, rval.handle_mut()); self.json_response(*cx).to_jsval(*cx, rval.handle_mut());
}, },
XMLHttpRequestResponseType::Blob => { XMLHttpRequestResponseType::Blob => unsafe {
self.blob_response().to_jsval(cx, rval.handle_mut()); self.blob_response().to_jsval(*cx, rval.handle_mut());
}, },
XMLHttpRequestResponseType::Arraybuffer => match self.arraybuffer_response(cx) { XMLHttpRequestResponseType::Arraybuffer => unsafe {
Some(js_object) => js_object.to_jsval(cx, rval.handle_mut()), match self.arraybuffer_response(*cx) {
None => return NullValue(), Some(js_object) => js_object.to_jsval(*cx, rval.handle_mut()),
None => return NullValue(),
}
}, },
} }
rval.get() rval.get()

View file

@ -15,9 +15,10 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::vrframedata::create_typed_array; use crate::dom::vrframedata::create_typed_array;
use crate::dom::window::Window; use crate::dom::window::Window;
use crate::dom::xrsession::ApiRigidTransform; use crate::dom::xrsession::ApiRigidTransform;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use euclid::{RigidTransform3D, Rotation3D, Vector3D}; use euclid::{RigidTransform3D, Rotation3D, Vector3D};
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use std::ptr::NonNull; use std::ptr::NonNull;
#[dom_struct] #[dom_struct]
@ -119,9 +120,9 @@ impl XRRigidTransformMethods for XRRigidTransform {
} }
// https://immersive-web.github.io/webxr/#dom-xrrigidtransform-matrix // https://immersive-web.github.io/webxr/#dom-xrrigidtransform-matrix
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn Matrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn Matrix(&self, _cx: JSContext) -> NonNull<JSObject> {
if self.matrix.get().is_null() { if self.matrix.get().is_null() {
let cx = self.global().get_cx(); let cx = unsafe { JSContext::from_ptr(self.global().get_cx()) };
// According to the spec all matrices are column-major, // According to the spec all matrices are column-major,
// however euclid uses row vectors so we use .to_row_major_array() // however euclid uses row vectors so we use .to_row_major_array()
let arr = self.transform.to_transform().to_row_major_array(); let arr = self.transform.to_transform().to_row_major_array();

View file

@ -10,8 +10,9 @@ use crate::dom::globalscope::GlobalScope;
use crate::dom::vrframedata::create_typed_array; use crate::dom::vrframedata::create_typed_array;
use crate::dom::xrrigidtransform::XRRigidTransform; use crate::dom::xrrigidtransform::XRRigidTransform;
use crate::dom::xrsession::{cast_transform, ApiViewerPose, XRSession}; use crate::dom::xrsession::{cast_transform, ApiViewerPose, XRSession};
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{Heap, JSObject};
use std::ptr::NonNull; use std::ptr::NonNull;
use webxr_api::View; use webxr_api::View;
@ -64,10 +65,8 @@ impl XRView {
// row_major since euclid uses row vectors // row_major since euclid uses row vectors
let proj = view.projection.to_row_major_array(); let proj = view.projection.to_row_major_array();
let cx = global.get_cx(); let cx = unsafe { JSContext::from_ptr(global.get_cx()) };
unsafe { create_typed_array(cx, &proj, &ret.proj);
create_typed_array(cx, &proj, &ret.proj);
}
ret ret
} }
@ -82,9 +81,8 @@ impl XRViewMethods for XRView {
self.eye self.eye
} }
#[allow(unsafe_code)]
/// https://immersive-web.github.io/webxr/#dom-xrview-projectionmatrix /// https://immersive-web.github.io/webxr/#dom-xrview-projectionmatrix
unsafe fn ProjectionMatrix(&self, _cx: *mut JSContext) -> NonNull<JSObject> { fn ProjectionMatrix(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new(self.proj.get()).unwrap() NonNull::new(self.proj.get()).unwrap()
} }

View file

@ -12,9 +12,10 @@ use crate::dom::xrpose::XRPose;
use crate::dom::xrrigidtransform::XRRigidTransform; use crate::dom::xrrigidtransform::XRRigidTransform;
use crate::dom::xrsession::{cast_transform, ApiViewerPose, XRSession}; use crate::dom::xrsession::{cast_transform, ApiViewerPose, XRSession};
use crate::dom::xrview::XRView; use crate::dom::xrview::XRView;
use crate::script_runtime::JSContext;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::conversions::ToJSValConvertible; use js::conversions::ToJSValConvertible;
use js::jsapi::{Heap, JSContext}; use js::jsapi::Heap;
use js::jsval::{JSVal, UndefinedValue}; use js::jsval::{JSVal, UndefinedValue};
use webxr_api::Views; use webxr_api::Views;
@ -69,8 +70,7 @@ impl XRViewerPose {
impl XRViewerPoseMethods for XRViewerPose { impl XRViewerPoseMethods for XRViewerPose {
/// https://immersive-web.github.io/webxr/#dom-xrviewerpose-views /// https://immersive-web.github.io/webxr/#dom-xrviewerpose-views
#[allow(unsafe_code)] fn Views(&self, _cx: JSContext) -> JSVal {
unsafe fn Views(&self, _cx: *mut JSContext) -> JSVal {
self.views.get() self.views.get()
} }
} }