script: Include constructors and static methods in generated DOM traits (#33665)

* Add all constructors, special operations, and static methods to generated DOM interface traits.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Move all constructors and static methods defined in bare impl blocks inside FooMethods trait impls.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

* Add missing doc links.

Signed-off-by: Josh Matthews <josh@joshmatthews.net>

---------

Signed-off-by: Josh Matthews <josh@joshmatthews.net>
This commit is contained in:
Josh Matthews 2024-10-07 21:51:58 -04:00 committed by GitHub
parent 946fa9cdee
commit 7d931e673a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
133 changed files with 1479 additions and 1438 deletions

View file

@ -131,9 +131,14 @@ impl AnalyserNode {
Ok(object)
}
pub fn push_block(&self, block: Block) {
self.engine.borrow_mut().push(block)
}
}
impl AnalyserNodeMethods for AnalyserNode {
/// <https://webaudio.github.io/web-audio-api/#dom-analysernode-analysernode>
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -143,12 +148,6 @@ impl AnalyserNode {
AnalyserNode::new_with_proto(window, proto, context, options, can_gc)
}
pub fn push_block(&self, block: Block) {
self.engine.borrow_mut().push(block)
}
}
impl AnalyserNodeMethods for AnalyserNode {
#[allow(unsafe_code)]
/// <https://webaudio.github.io/web-audio-api/#dom-analysernode-getfloatfrequencydata>
fn GetFloatFrequencyData(&self, mut array: CustomAutoRooterGuard<Float32Array>) {

View file

@ -61,9 +61,11 @@ impl AnimationEvent {
}
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl AnimationEventMethods for AnimationEvent {
// https://drafts.csswg.org/css-animations/#dom-animationevent-animationevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -72,9 +74,7 @@ impl AnimationEvent {
) -> DomRoot<AnimationEvent> {
AnimationEvent::new_with_proto(window, proto, Atom::from(type_), init, can_gc)
}
}
impl AnimationEventMethods for AnimationEvent {
// https://drafts.csswg.org/css-animations/#interface-animationevent-attributes
fn AnimationName(&self) -> DOMString {
DOMString::from(&*self.animation_name)

View file

@ -109,33 +109,6 @@ impl AudioBuffer {
buffer
}
// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-audiobuffer
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
options: &AudioBufferOptions,
) -> Fallible<DomRoot<AudioBuffer>> {
if options.length == 0 ||
options.numberOfChannels == 0 ||
options.numberOfChannels > MAX_CHANNEL_COUNT ||
*options.sampleRate < MIN_SAMPLE_RATE ||
*options.sampleRate > MAX_SAMPLE_RATE
{
return Err(Error::NotSupported);
}
Ok(AudioBuffer::new_with_proto(
window,
proto,
options.numberOfChannels,
options.length,
*options.sampleRate,
None,
can_gc,
))
}
// Initialize the underlying channels data with initial data provided by
// the user or silence otherwise.
fn set_initial_data(&self, initial_data: Option<&[Vec<f32>]>) {
@ -210,6 +183,32 @@ impl AudioBuffer {
}
impl AudioBufferMethods for AudioBuffer {
// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-audiobuffer
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
options: &AudioBufferOptions,
) -> Fallible<DomRoot<AudioBuffer>> {
if options.length == 0 ||
options.numberOfChannels == 0 ||
options.numberOfChannels > MAX_CHANNEL_COUNT ||
*options.sampleRate < MIN_SAMPLE_RATE ||
*options.sampleRate > MAX_SAMPLE_RATE
{
return Err(Error::NotSupported);
}
Ok(AudioBuffer::new_with_proto(
window,
proto,
options.numberOfChannels,
options.length,
*options.sampleRate,
None,
can_gc,
))
}
// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-samplerate
fn SampleRate(&self) -> Finite<f32> {
Finite::wrap(self.sample_rate)

View file

@ -120,9 +120,11 @@ impl AudioBufferSourceNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl AudioBufferSourceNodeMethods for AudioBufferSourceNode {
// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-audiobuffersourcenode
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -131,9 +133,7 @@ impl AudioBufferSourceNode {
) -> Fallible<DomRoot<AudioBufferSourceNode>> {
AudioBufferSourceNode::new_with_proto(window, proto, context, options, can_gc)
}
}
impl AudioBufferSourceNodeMethods for AudioBufferSourceNode {
// https://webaudio.github.io/web-audio-api/#dom-audiobuffersourcenode-buffer
fn GetBuffer(&self) -> Fallible<Option<DomRoot<AudioBuffer>>> {
Ok(self.buffer.get())

View file

@ -96,17 +96,6 @@ impl AudioContext {
Ok(context)
}
// https://webaudio.github.io/web-audio-api/#AudioContext-constructors
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
options: &AudioContextOptions,
) -> Fallible<DomRoot<AudioContext>> {
AudioContext::new(window, proto, options, can_gc)
}
fn resume(&self) {
// Step 5.
if self.context.is_allowed_to_start() {
@ -121,6 +110,16 @@ impl AudioContext {
}
impl AudioContextMethods for AudioContext {
// https://webaudio.github.io/web-audio-api/#AudioContext-constructors
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
options: &AudioContextOptions,
) -> Fallible<DomRoot<AudioContext>> {
AudioContext::new(window, proto, options, can_gc)
}
// https://webaudio.github.io/web-audio-api/#dom-audiocontext-baselatency
fn BaseLatency(&self) -> Finite<f64> {
Finite::wrap(self.base_latency)

View file

@ -2176,6 +2176,7 @@ class CGImports(CGWrapper):
types += componentTypes(returnType)
for arg in arguments:
types += componentTypes(arg.type)
return types
def getIdentifier(t):
@ -2198,6 +2199,7 @@ class CGImports(CGWrapper):
return normalized
types = []
descriptorProvider = config.getDescriptorProvider()
for d in descriptors:
if not d.interface.isCallback():
types += [d.interface]
@ -2216,6 +2218,11 @@ class CGImports(CGWrapper):
for m in members:
if m.isMethod():
types += relatedTypesForSignatures(m)
if m.isStatic():
types += [
descriptorProvider.getDescriptor(iface).interface
for iface in d.interface.exposureSet
]
elif m.isAttr():
types += componentTypes(m.type)
@ -6292,7 +6299,7 @@ class CGDOMJSProxyHandlerDOMClass(CGThing):
class CGInterfaceTrait(CGThing):
def __init__(self, descriptor):
def __init__(self, descriptor, descriptorProvider):
CGThing.__init__(self)
def attribute_arguments(needCx, argument=None, inRealm=False, canGc=False):
@ -6310,7 +6317,7 @@ class CGInterfaceTrait(CGThing):
def members():
for m in descriptor.interface.members:
if (m.isMethod() and not m.isStatic()
if (m.isMethod()
and not m.isMaplikeOrSetlikeOrIterableMethod()
and (not m.isIdentifierLess() or (m.isStringifier() and not m.underlyingAttr))
and not m.isDefaultToJSON()):
@ -6321,8 +6328,8 @@ class CGInterfaceTrait(CGThing):
inRealm=name in descriptor.inRealmMethods,
canGc=name in descriptor.canGcMethods)
rettype = return_type(descriptor, rettype, infallible)
yield f"{name}{'_' * idx}", arguments, rettype
elif m.isAttr() and not m.isStatic():
yield f"{name}{'_' * idx}", arguments, rettype, m.isStatic()
elif m.isAttr():
name = CGSpecializedGetter.makeNativeName(descriptor, m)
infallible = 'infallible' in descriptor.getExtendedAttributes(m, getter=True)
yield (name,
@ -6331,7 +6338,8 @@ class CGInterfaceTrait(CGThing):
inRealm=name in descriptor.inRealmMethods,
canGc=name in descriptor.canGcMethods
),
return_type(descriptor, m.type, infallible))
return_type(descriptor, m.type, infallible),
m.isStatic())
if not m.readonly:
name = CGSpecializedSetter.makeNativeName(descriptor, m)
@ -6347,7 +6355,8 @@ class CGInterfaceTrait(CGThing):
inRealm=name in descriptor.inRealmMethods,
canGc=name in descriptor.canGcMethods
),
rettype)
rettype,
m.isStatic())
if descriptor.proxy or descriptor.isGlobal():
for name, operation in descriptor.operations.items():
@ -6371,18 +6380,19 @@ class CGInterfaceTrait(CGThing):
# WebIDL, Second Draft, section 3.2.4.5
# https://heycam.github.io/webidl/#idl-named-properties
if operation.isNamed():
yield "SupportedPropertyNames", [], "Vec<DOMString>"
yield "SupportedPropertyNames", [], "Vec<DOMString>", False
else:
arguments = method_arguments(descriptor, rettype, arguments,
inRealm=name in descriptor.inRealmMethods,
canGc=name in descriptor.canGcMethods)
rettype = return_type(descriptor, rettype, infallible)
yield name, arguments, rettype
yield name, arguments, rettype, False
def fmt(arguments):
def fmt(arguments, leadingComma=True):
keywords = {"async"}
return "".join(
f", {name if name not in keywords else f'r#{name}'}: {type_}"
prefix = "" if not leadingComma else ", "
return prefix + ", ".join(
f"{name if name not in keywords else f'r#{name}'}: {type_}"
for name, type_ in arguments
)
@ -6392,11 +6402,54 @@ class CGInterfaceTrait(CGThing):
return functools.reduce((lambda x, y: x or y[1] == '*mut JSContext'), arguments, False)
methods = []
for name, arguments, rettype in members():
exposureSet = list(descriptor.interface.exposureSet)
exposedGlobal = "GlobalScope" if len(exposureSet) > 1 else exposureSet[0]
hasLength = False
for name, arguments, rettype, isStatic in members():
if name == "Length":
hasLength = True
arguments = list(arguments)
unsafe = 'unsafe ' if contains_unsafe_arg(arguments) else ''
returnType = f" -> {rettype}" if rettype != '()' else ''
methods.append(CGGeneric(f"{unsafe}fn {name}(&self{fmt(arguments)}){returnType};\n"))
selfArg = "&self" if not isStatic else ""
extra = [("global", f"&{exposedGlobal}")] if isStatic else []
if arguments and arguments[0][0] == "cx":
arguments = [arguments[0]] + extra + arguments[1:]
else:
arguments = extra + arguments
methods.append(CGGeneric(
f"{unsafe}fn {name}({selfArg}"
f"{fmt(arguments, leadingComma=not isStatic)}){returnType};\n"
))
def ctorMethod(ctor, baseName=None):
infallible = 'infallible' in descriptor.getExtendedAttributes(ctor)
for (i, (rettype, arguments)) in enumerate(ctor.signatures()):
name = (baseName or ctor.identifier.name) + ('_' * i)
args = list(method_arguments(descriptor, rettype, arguments))
extra = [
("global", f"&{exposedGlobal}"),
("proto", "Option<HandleObject>"),
("can_gc", "CanGc"),
]
if args and args[0][0] == "cx":
args = [args[0]] + extra + args[1:]
else:
args = extra + args
yield CGGeneric(
f"fn {name}({fmt(args, leadingComma=False)}) -> "
f"{return_type(descriptorProvider, rettype, infallible)};\n"
)
ctor = descriptor.interface.ctor()
if ctor and not ctor.isHTMLConstructor():
methods.extend(list(ctorMethod(ctor, "Constructor")))
for ctor in descriptor.interface.legacyFactoryFunctions:
methods.extend(list(ctorMethod(ctor)))
if descriptor.operations['IndexedGetter'] and not hasLength:
methods.append(CGGeneric("fn Length(&self) -> u32;\n"))
if methods:
self.cgRoot = CGWrapper(CGIndenter(CGList(methods, "")),
@ -6572,14 +6625,15 @@ class CGDescriptor(CGThing):
if descriptor.concrete or descriptor.hasDescendants():
cgThings.append(CGIDLInterface(descriptor))
interfaceTrait = CGInterfaceTrait(descriptor)
if descriptor.weakReferenceable:
cgThings.append(CGWeakReferenceableTrait(descriptor))
if not descriptor.interface.isCallback():
interfaceTrait = CGInterfaceTrait(descriptor, config.getDescriptorProvider())
cgThings.append(interfaceTrait)
if not interfaceTrait.empty:
reexports.append(f'{descriptor.name}Methods')
if descriptor.weakReferenceable:
cgThings.append(CGWeakReferenceableTrait(descriptor))
legacyWindowAliases = descriptor.interface.legacyWindowAliases
haveLegacyWindowAliases = len(legacyWindowAliases) != 0
if haveLegacyWindowAliases:

View file

@ -137,9 +137,11 @@ impl BiquadFilterNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl BiquadFilterNodeMethods for BiquadFilterNode {
// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-biquadfilternode-context-options
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -148,9 +150,7 @@ impl BiquadFilterNode {
) -> Fallible<DomRoot<BiquadFilterNode>> {
BiquadFilterNode::new_with_proto(window, proto, context, options, can_gc)
}
}
impl BiquadFilterNodeMethods for BiquadFilterNode {
// https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-gain
fn Gain(&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.gain)

View file

@ -69,29 +69,6 @@ impl Blob {
}
}
// https://w3c.github.io/FileAPI/#constructorBlob
#[allow(non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
blobParts: Option<Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>>,
blobPropertyBag: &BlobBinding::BlobPropertyBag,
) -> Fallible<DomRoot<Blob>> {
let bytes: Vec<u8> = match blobParts {
None => Vec::new(),
Some(blobparts) => match blob_parts_to_bytes(blobparts) {
Ok(bytes) => bytes,
Err(_) => return Err(Error::InvalidCharacter),
},
};
let type_string = normalize_type_string(blobPropertyBag.type_.as_ref());
let blob_impl = BlobImpl::new_from_bytes(bytes, type_string);
Ok(Blob::new_with_proto(global, proto, blob_impl, can_gc))
}
/// Get a slice to inner data, this might incur synchronous read and caching
pub fn get_bytes(&self) -> Result<Vec<u8>, ()> {
self.global().get_blob_bytes(&self.blob_id)
@ -225,6 +202,29 @@ pub fn blob_parts_to_bytes(
}
impl BlobMethods for Blob {
// https://w3c.github.io/FileAPI/#constructorBlob
#[allow(non_snake_case)]
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
blobParts: Option<Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>>,
blobPropertyBag: &BlobBinding::BlobPropertyBag,
) -> Fallible<DomRoot<Blob>> {
let bytes: Vec<u8> = match blobParts {
None => Vec::new(),
Some(blobparts) => match blob_parts_to_bytes(blobparts) {
Ok(bytes) => bytes,
Err(_) => return Err(Error::InvalidCharacter),
},
};
let type_string = normalize_type_string(blobPropertyBag.type_.as_ref());
let blob_impl = BlobImpl::new_from_bytes(bytes, type_string);
Ok(Blob::new_with_proto(global, proto, blob_impl, can_gc))
}
// https://w3c.github.io/FileAPI/#dfn-size
fn Size(&self) -> u64 {
self.global().get_blob_size(&self.blob_id)

View file

@ -79,9 +79,12 @@ impl BluetoothAdvertisingEvent {
}
ev
}
}
impl BluetoothAdvertisingEventMethods for BluetoothAdvertisingEvent {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingevent-bluetoothadvertisingevent
pub fn Constructor(
#[allow(non_snake_case)]
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -109,9 +112,7 @@ impl BluetoothAdvertisingEvent {
can_gc,
))
}
}
impl BluetoothAdvertisingEventMethods for BluetoothAdvertisingEvent {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingevent-device
fn Device(&self) -> DomRoot<BluetoothDevice> {
DomRoot::from_ref(&*self.device)

View file

@ -5,6 +5,7 @@
use dom_struct::dom_struct;
use regex::Regex;
use crate::dom::bindings::codegen::Bindings::BluetoothUUIDBinding::BluetoothUUIDMethods;
use crate::dom::bindings::codegen::UnionTypes::StringOrUnsignedLong;
use crate::dom::bindings::error::Error::Type;
use crate::dom::bindings::error::Fallible;
@ -583,25 +584,24 @@ const CHARACTERISTIC_ERROR_MESSAGE: &str =
const DESCRIPTOR_ERROR_MESSAGE: &str = "https://developer.bluetooth.org/gatt/descriptors/Pages/\
DescriptorsHomePage.aspx\ne.g. 'gatt.characteristic_presentation_format'.";
#[allow(non_snake_case)]
impl BluetoothUUID {
impl BluetoothUUIDMethods for BluetoothUUID {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-canonicaluuid
pub fn CanonicalUUID(_: &Window, alias: u32) -> UUID {
fn CanonicalUUID(_: &Window, alias: u32) -> UUID {
canonical_uuid(alias)
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-getservice
pub fn GetService(_: &Window, name: BluetoothServiceUUID) -> Fallible<UUID> {
fn GetService(_: &Window, name: BluetoothServiceUUID) -> Fallible<UUID> {
Self::service(name)
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-getcharacteristic
pub fn GetCharacteristic(_: &Window, name: BluetoothCharacteristicUUID) -> Fallible<UUID> {
fn GetCharacteristic(_: &Window, name: BluetoothCharacteristicUUID) -> Fallible<UUID> {
Self::characteristic(name)
}
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-getdescriptor
pub fn GetDescriptor(_: &Window, name: BluetoothDescriptorUUID) -> Fallible<UUID> {
fn GetDescriptor(_: &Window, name: BluetoothDescriptorUUID) -> Fallible<UUID> {
Self::descriptor(name)
}
}

View file

@ -29,17 +29,6 @@ pub struct BroadcastChannel {
}
impl BroadcastChannel {
/// <https://html.spec.whatwg.org/multipage/#broadcastchannel>
#[allow(non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
name: DOMString,
) -> DomRoot<BroadcastChannel> {
BroadcastChannel::new(global, proto, name, can_gc)
}
fn new(
global: &GlobalScope,
proto: Option<HandleObject>,
@ -78,6 +67,16 @@ impl BroadcastChannel {
}
impl BroadcastChannelMethods for BroadcastChannel {
/// <https://html.spec.whatwg.org/multipage/#broadcastchannel>
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
name: DOMString,
) -> DomRoot<BroadcastChannel> {
BroadcastChannel::new(global, proto, name, can_gc)
}
/// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage>
fn PostMessage(&self, cx: SafeJSContext, message: HandleValue) -> ErrorResult {
// Step 3, if closed.

View file

@ -12,7 +12,9 @@ use crate::dom::baseaudiocontext::BaseAudioContext;
use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
ChannelCountMode, ChannelInterpretation,
};
use crate::dom::bindings::codegen::Bindings::ChannelMergerNodeBinding::ChannelMergerOptions;
use crate::dom::bindings::codegen::Bindings::ChannelMergerNodeBinding::{
ChannelMergerNodeMethods, ChannelMergerOptions,
};
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::reflect_dom_object_with_proto;
use crate::dom::bindings::root::DomRoot;
@ -79,9 +81,11 @@ impl ChannelMergerNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl ChannelMergerNodeMethods for ChannelMergerNode {
/// <https://webaudio.github.io/web-audio-api/#dom-channelmergernode-channelmergernode>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,

View file

@ -11,7 +11,9 @@ use crate::dom::baseaudiocontext::BaseAudioContext;
use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
ChannelCountMode, ChannelInterpretation,
};
use crate::dom::bindings::codegen::Bindings::ChannelSplitterNodeBinding::ChannelSplitterOptions;
use crate::dom::bindings::codegen::Bindings::ChannelSplitterNodeBinding::{
ChannelSplitterNodeMethods, ChannelSplitterOptions,
};
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::reflect_dom_object_with_proto;
use crate::dom::bindings::root::DomRoot;
@ -81,9 +83,11 @@ impl ChannelSplitterNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl ChannelSplitterNodeMethods for ChannelSplitterNode {
/// <https://webaudio.github.io/web-audio-api/#dom-channelsplitternode-channelsplitternode>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,

View file

@ -79,8 +79,11 @@ impl CloseEvent {
}
ev
}
}
pub fn Constructor(
impl CloseEventMethods for CloseEvent {
// https://websockets.spec.whatwg.org/#the-closeevent-interface
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -101,20 +104,18 @@ impl CloseEvent {
can_gc,
))
}
}
impl CloseEventMethods for CloseEvent {
// https://html.spec.whatwg.org/multipage/#dom-closeevent-wasclean
// https://websockets.spec.whatwg.org/#dom-closeevent-wasclean
fn WasClean(&self) -> bool {
self.was_clean
}
// https://html.spec.whatwg.org/multipage/#dom-closeevent-code
// https://websockets.spec.whatwg.org/#dom-closeevent-code
fn Code(&self) -> u16 {
self.code
}
// https://html.spec.whatwg.org/multipage/#dom-closeevent-reason
// https://websockets.spec.whatwg.org/#dom-closeevent-reason
fn Reason(&self) -> DOMString {
self.reason.clone()
}

View file

@ -5,6 +5,7 @@
use dom_struct::dom_struct;
use js::rust::HandleObject;
use crate::dom::bindings::codegen::Bindings::CommentBinding::CommentMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::root::DomRoot;
@ -39,9 +40,11 @@ impl Comment {
proto,
)
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl CommentMethods for Comment {
/// <https://dom.spec.whatwg.org/#dom-comment-comment>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
_can_gc: CanGc,

View file

@ -83,8 +83,14 @@ impl CompositionEvent {
ev
}
#[allow(non_snake_case)]
pub fn Constructor(
pub fn data(&self) -> &str {
&self.data
}
}
impl CompositionEventMethods for CompositionEvent {
// https://w3c.github.io/uievents/#dom-compositionevent-compositionevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -105,12 +111,6 @@ impl CompositionEvent {
Ok(event)
}
pub fn data(&self) -> &str {
&self.data
}
}
impl CompositionEventMethods for CompositionEvent {
// https://w3c.github.io/uievents/#dom-compositionevent-data
fn Data(&self) -> DOMString {
self.data.clone()

View file

@ -14,6 +14,7 @@ use js::rust::wrappers::{
};
use js::rust::{describe_scripted_caller, HandleValue, IdVector};
use crate::dom::bindings::codegen::Bindings::ConsoleBinding::consoleMethods;
use crate::dom::bindings::conversions::jsstring_to_str;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::str::DOMString;
@ -53,6 +54,11 @@ impl Console {
chan.send(devtools_message).unwrap();
}
}
// Directly logs a DOMString, without processing the message
pub fn internal_warn(global: &GlobalScope, message: DOMString) {
console_message(global, message, LogLevel::Warn)
}
}
// In order to avoid interleaving the stdout output of the Console API methods
@ -221,45 +227,40 @@ fn console_message(global: &GlobalScope, message: DOMString, level: LogLevel) {
})
}
#[allow(non_snake_case)]
impl Console {
impl consoleMethods for Console {
// https://developer.mozilla.org/en-US/docs/Web/API/Console/log
pub fn Log(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
fn Log(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
console_messages(global, messages, LogLevel::Log)
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/clear
pub fn Clear(global: &GlobalScope) {
fn Clear(global: &GlobalScope) {
let message: Vec<HandleValue> = Vec::new();
console_messages(global, message, LogLevel::Clear)
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console
pub fn Debug(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
fn Debug(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
console_messages(global, messages, LogLevel::Debug)
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/info
pub fn Info(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
fn Info(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
console_messages(global, messages, LogLevel::Info)
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/warn
pub fn Warn(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
fn Warn(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
console_messages(global, messages, LogLevel::Warn)
}
// Directly logs a DOMString, without processing the message
pub fn internal_warn(global: &GlobalScope, message: DOMString) {
console_message(global, message, LogLevel::Warn)
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/error
pub fn Error(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
fn Error(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
console_messages(global, messages, LogLevel::Error)
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/assert
pub fn Assert(_cx: JSContext, global: &GlobalScope, condition: bool, message: HandleValue) {
fn Assert(_cx: JSContext, global: &GlobalScope, condition: bool, message: HandleValue) {
if !condition {
let message = if message.is_undefined() {
DOMString::from("no message")
@ -272,7 +273,7 @@ impl Console {
}
// https://console.spec.whatwg.org/#time
pub fn Time(global: &GlobalScope, label: DOMString) {
fn Time(global: &GlobalScope, label: DOMString) {
if let Ok(()) = global.time(label.clone()) {
let message = DOMString::from(format!("{label}: timer started"));
console_message(global, message, LogLevel::Log);
@ -280,7 +281,7 @@ impl Console {
}
// https://console.spec.whatwg.org/#timelog
pub fn TimeLog(_cx: JSContext, global: &GlobalScope, label: DOMString, data: Vec<HandleValue>) {
fn TimeLog(_cx: JSContext, global: &GlobalScope, label: DOMString, data: Vec<HandleValue>) {
if let Ok(delta) = global.time_log(&label) {
let message = DOMString::from(format!(
"{label}: {delta}ms {}",
@ -291,7 +292,7 @@ impl Console {
}
// https://console.spec.whatwg.org/#timeend
pub fn TimeEnd(global: &GlobalScope, label: DOMString) {
fn TimeEnd(global: &GlobalScope, label: DOMString) {
if let Ok(delta) = global.time_end(&label) {
let message = DOMString::from(format!("{label}: {delta}ms"));
console_message(global, message, LogLevel::Log);
@ -299,29 +300,29 @@ impl Console {
}
// https://console.spec.whatwg.org/#group
pub fn Group(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
fn Group(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
global.push_console_group(stringify_handle_values(messages));
}
// https://console.spec.whatwg.org/#groupcollapsed
pub fn GroupCollapsed(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
fn GroupCollapsed(_cx: JSContext, global: &GlobalScope, messages: Vec<HandleValue>) {
global.push_console_group(stringify_handle_values(messages));
}
// https://console.spec.whatwg.org/#groupend
pub fn GroupEnd(global: &GlobalScope) {
fn GroupEnd(global: &GlobalScope) {
global.pop_console_group();
}
/// <https://console.spec.whatwg.org/#count>
pub fn Count(global: &GlobalScope, label: DOMString) {
fn Count(global: &GlobalScope, label: DOMString) {
let count = global.increment_console_count(&label);
let message = DOMString::from(format!("{label}: {count}"));
console_message(global, message, LogLevel::Log);
}
/// <https://console.spec.whatwg.org/#countreset>
pub fn CountReset(global: &GlobalScope, label: DOMString) {
fn CountReset(global: &GlobalScope, label: DOMString) {
if global.reset_console_count(&label).is_err() {
Self::internal_warn(
global,

View file

@ -87,9 +87,11 @@ impl ConstantSourceNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl ConstantSourceNodeMethods for ConstantSourceNode {
// https://webaudio.github.io/web-audio-api/#dom-constantsourcenode-constantsourcenode
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -98,9 +100,7 @@ impl ConstantSourceNode {
) -> Fallible<DomRoot<ConstantSourceNode>> {
ConstantSourceNode::new_with_proto(window, proto, context, options, can_gc)
}
}
impl ConstantSourceNodeMethods for ConstantSourceNode {
// https://webaudio.github.io/web-audio-api/#dom-constantsourcenode-offset
fn Offset(&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.offset)

View file

@ -10,6 +10,7 @@ use style::stylesheets::supports_rule::{parse_condition_or_declaration, Declarat
use style::stylesheets::{CssRuleType, Origin, UrlExtraData};
use style_traits::ParsingMode;
use crate::dom::bindings::codegen::Bindings::CSSBinding::CSSMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::Reflector;
@ -24,17 +25,16 @@ pub struct CSS {
reflector_: Reflector,
}
#[allow(non_snake_case)]
impl CSS {
/// <http://dev.w3.org/csswg/cssom/#serialize-an-identifier>
pub fn Escape(_: &Window, ident: DOMString) -> Fallible<DOMString> {
impl CSSMethods for CSS {
/// <https://drafts.csswg.org/cssom/#the-css.escape()-method>
fn Escape(_: &Window, ident: DOMString) -> Fallible<DOMString> {
let mut escaped = String::new();
serialize_identifier(&ident, &mut escaped).unwrap();
Ok(DOMString::from(escaped))
}
/// <https://drafts.csswg.org/css-conditional/#dom-css-supports>
pub fn Supports(win: &Window, property: DOMString, value: DOMString) -> bool {
fn Supports(win: &Window, property: DOMString, value: DOMString) -> bool {
let mut decl = String::new();
serialize_identifier(&property, &mut decl).unwrap();
decl.push_str(": ");
@ -55,7 +55,7 @@ impl CSS {
}
/// <https://drafts.csswg.org/css-conditional/#dom-css-supports>
pub fn Supports_(win: &Window, condition: DOMString) -> bool {
fn Supports_(win: &Window, condition: DOMString) -> bool {
let mut input = ParserInput::new(&condition);
let mut input = Parser::new(&mut input);
let cond = match parse_condition_or_declaration(&mut input) {
@ -78,7 +78,7 @@ impl CSS {
}
/// <https://drafts.css-houdini.org/css-paint-api-1/#paint-worklet>
pub fn PaintWorklet(win: &Window) -> DomRoot<Worklet> {
fn PaintWorklet(win: &Window) -> DomRoot<Worklet> {
win.paint_worklet()
}
}

View file

@ -67,25 +67,6 @@ impl CustomEvent {
ev
}
#[allow(unsafe_code, non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
type_: DOMString,
init: RootedTraceableBox<CustomEventBinding::CustomEventInit>,
) -> DomRoot<CustomEvent> {
CustomEvent::new(
global,
proto,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
init.detail.handle(),
can_gc,
)
}
fn init_custom_event(
&self,
type_: Atom,
@ -104,6 +85,25 @@ impl CustomEvent {
}
impl CustomEventMethods for CustomEvent {
// https://dom.spec.whatwg.org/#dom-customevent-customevent
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
type_: DOMString,
init: RootedTraceableBox<CustomEventBinding::CustomEventInit>,
) -> DomRoot<CustomEvent> {
CustomEvent::new(
global,
proto,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
init.detail.handle(),
can_gc,
)
}
// https://dom.spec.whatwg.org/#dom-customevent-detail
fn Detail(&self, _cx: JSContext) -> JSVal {
self.detail.get()

View file

@ -3440,35 +3440,6 @@ impl Document {
);
}
// https://dom.spec.whatwg.org/#dom-document-document
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> Fallible<DomRoot<Document>> {
let doc = window.Document();
let docloader = DocumentLoader::new(&doc.loader());
Ok(Document::new_with_proto(
window,
proto,
HasBrowsingContext::No,
None,
doc.origin().clone(),
IsHTMLDocument::NonHTMLDocument,
None,
None,
DocumentActivity::Inactive,
DocumentSource::NotFromParser,
docloader,
None,
None,
None,
Default::default(),
can_gc,
))
}
#[allow(clippy::too_many_arguments)]
pub fn new(
window: &Window,
@ -4180,6 +4151,34 @@ impl ProfilerMetadataFactory for Document {
}
impl DocumentMethods for Document {
// https://dom.spec.whatwg.org/#dom-document-document
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> Fallible<DomRoot<Document>> {
let doc = window.Document();
let docloader = DocumentLoader::new(&doc.loader());
Ok(Document::new_with_proto(
window,
proto,
HasBrowsingContext::No,
None,
doc.origin().clone(),
IsHTMLDocument::NonHTMLDocument,
None,
None,
DocumentActivity::Inactive,
DocumentSource::NotFromParser,
docloader,
None,
None,
None,
Default::default(),
can_gc,
))
}
// https://w3c.github.io/editing/ActiveDocuments/execCommand.html#querycommandsupported()
fn QueryCommandSupported(&self, _command: DOMString) -> bool {
false

View file

@ -55,8 +55,14 @@ impl DocumentFragment {
)
}
#[allow(non_snake_case)]
pub fn Constructor(
pub fn id_map(&self) -> &DomRefCell<HashMapTracedValues<Atom, Vec<Dom<Element>>>> {
&self.id_map
}
}
impl DocumentFragmentMethods for DocumentFragment {
// https://dom.spec.whatwg.org/#dom-documentfragment-documentfragment
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
_can_gc: CanGc,
@ -66,12 +72,6 @@ impl DocumentFragment {
Ok(DocumentFragment::new_with_proto(&document, proto))
}
pub fn id_map(&self) -> &DomRefCell<HashMapTracedValues<Atom, Vec<Dom<Element>>>> {
&self.id_map
}
}
impl DocumentFragmentMethods for DocumentFragment {
// https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(&self) -> DomRoot<HTMLCollection> {
let window = window_from_node(self);

View file

@ -147,8 +147,15 @@ impl DOMException {
reflect_dom_object(Box::new(DOMException::new_inherited(message, name)), global)
}
#[allow(non_snake_case)]
pub fn Constructor(
// not an IDL stringifier, used internally
pub fn stringifier(&self) -> DOMString {
DOMString::from(format!("{}: {}", self.name, self.message))
}
}
impl DOMExceptionMethods for DOMException {
// https://webidl.spec.whatwg.org/#dom-domexception-domexception
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -163,14 +170,7 @@ impl DOMException {
))
}
// not an IDL stringifier, used internally
pub fn stringifier(&self) -> DOMString {
DOMString::from(format!("{}: {}", self.name, self.message))
}
}
impl DOMExceptionMethods for DOMException {
// https://heycam.github.io/webidl/#dom-domexception-code
// https://webidl.spec.whatwg.org/#dom-domexception-code
fn Code(&self) -> u16 {
match DOMErrorName::from(&self.name) {
Some(code) if code <= DOMErrorName::DataCloneError => code as u16,
@ -178,12 +178,12 @@ impl DOMExceptionMethods for DOMException {
}
}
// https://heycam.github.io/webidl/#idl-DOMException-error-names
// https://webidl.spec.whatwg.org/#dom-domexception-name
fn Name(&self) -> DOMString {
self.name.clone()
}
// https://heycam.github.io/webidl/#error-names
// https://webidl.spec.whatwg.org/#dom-domexception-message
fn Message(&self) -> DOMString {
self.message.clone()
}

View file

@ -51,8 +51,15 @@ impl DOMMatrix {
}
}
pub fn from_readonly(global: &GlobalScope, ro: &DOMMatrixReadOnly) -> DomRoot<Self> {
Self::new(global, ro.is2D(), *ro.matrix())
}
}
#[allow(non_snake_case)]
impl DOMMatrixMethods for DOMMatrix {
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -88,16 +95,12 @@ impl DOMMatrix {
}
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-frommatrix
pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<DomRoot<Self>> {
fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<DomRoot<Self>> {
dommatrixinit_to_matrix(other).map(|(is2D, matrix)| Self::new(global, is2D, matrix))
}
pub fn from_readonly(global: &GlobalScope, ro: &DOMMatrixReadOnly) -> DomRoot<Self> {
Self::new(global, ro.is2D(), *ro.matrix())
}
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-fromfloat32array
pub fn FromFloat32Array(
fn FromFloat32Array(
global: &GlobalScope,
array: CustomAutoRooterGuard<Float32Array>,
) -> Fallible<DomRoot<DOMMatrix>> {
@ -111,7 +114,7 @@ impl DOMMatrix {
}
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-fromfloat64array
pub fn FromFloat64Array(
fn FromFloat64Array(
global: &GlobalScope,
array: CustomAutoRooterGuard<Float64Array>,
) -> Fallible<DomRoot<DOMMatrix>> {
@ -123,10 +126,7 @@ impl DOMMatrix {
Some(StringOrUnrestrictedDoubleSequence::UnrestrictedDoubleSequence(vec)),
)
}
}
#[allow(non_snake_case)]
impl DOMMatrixMethods for DOMMatrix {
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-m11
fn M11(&self) -> f64 {
self.upcast::<DOMMatrixReadOnly>().M11()

View file

@ -67,47 +67,6 @@ impl DOMMatrixReadOnly {
}
}
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
init: Option<StringOrUnrestrictedDoubleSequence>,
) -> Fallible<DomRoot<Self>> {
if init.is_none() {
return Ok(Self::new_with_proto(
global,
proto,
true,
Transform3D::identity(),
can_gc,
));
}
match init.unwrap() {
StringOrUnrestrictedDoubleSequence::String(ref s) => {
if global.downcast::<Window>().is_none() {
return Err(error::Error::Type(
"String constructor is only supported in the main thread.".to_owned(),
));
}
if s.is_empty() {
return Ok(Self::new(global, true, Transform3D::identity()));
}
transform_to_matrix(s.to_string())
.map(|(is2D, matrix)| Self::new_with_proto(global, proto, is2D, matrix, can_gc))
},
StringOrUnrestrictedDoubleSequence::UnrestrictedDoubleSequence(ref entries) => {
entries_to_matrix(&entries[..])
.map(|(is2D, matrix)| Self::new_with_proto(global, proto, is2D, matrix, can_gc))
},
}
}
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-frommatrix
pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<DomRoot<Self>> {
dommatrixinit_to_matrix(other).map(|(is2D, matrix)| Self::new(global, is2D, matrix))
}
pub fn matrix(&self) -> Ref<Transform3D<f64>> {
self.matrix.borrow()
}
@ -403,10 +362,53 @@ impl DOMMatrixReadOnly {
})
// Step 3 in DOMMatrix.InvertSelf
}
}
#[allow(non_snake_case)]
impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly {
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
init: Option<StringOrUnrestrictedDoubleSequence>,
) -> Fallible<DomRoot<Self>> {
if init.is_none() {
return Ok(Self::new_with_proto(
global,
proto,
true,
Transform3D::identity(),
can_gc,
));
}
match init.unwrap() {
StringOrUnrestrictedDoubleSequence::String(ref s) => {
if global.downcast::<Window>().is_none() {
return Err(error::Error::Type(
"String constructor is only supported in the main thread.".to_owned(),
));
}
if s.is_empty() {
return Ok(Self::new(global, true, Transform3D::identity()));
}
transform_to_matrix(s.to_string())
.map(|(is2D, matrix)| Self::new_with_proto(global, proto, is2D, matrix, can_gc))
},
StringOrUnrestrictedDoubleSequence::UnrestrictedDoubleSequence(ref entries) => {
entries_to_matrix(&entries[..])
.map(|(is2D, matrix)| Self::new_with_proto(global, proto, is2D, matrix, can_gc))
},
}
}
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-frommatrix
fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<DomRoot<Self>> {
dommatrixinit_to_matrix(other).map(|(is2D, matrix)| Self::new(global, is2D, matrix))
}
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-fromfloat32array
#[allow(unsafe_code)]
pub fn FromFloat32Array(
fn FromFloat32Array(
global: &GlobalScope,
array: CustomAutoRooterGuard<Float32Array>,
) -> Fallible<DomRoot<DOMMatrixReadOnly>> {
@ -420,8 +422,7 @@ impl DOMMatrixReadOnly {
}
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-fromfloat64array
#[allow(unsafe_code)]
pub fn FromFloat64Array(
fn FromFloat64Array(
global: &GlobalScope,
array: CustomAutoRooterGuard<Float64Array>,
) -> Fallible<DomRoot<DOMMatrixReadOnly>> {
@ -433,10 +434,7 @@ impl DOMMatrixReadOnly {
Some(StringOrUnrestrictedDoubleSequence::UnrestrictedDoubleSequence(vec)),
)
}
}
#[allow(non_snake_case)]
impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly {
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-m11
fn M11(&self) -> f64 {
self.matrix.borrow().m11

View file

@ -45,19 +45,19 @@ impl DOMParser {
can_gc,
)
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl DOMParserMethods for DOMParser {
/// <https://html.spec.whatwg.org/multipage/#dom-domparser-constructor>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> Fallible<DomRoot<DOMParser>> {
Ok(DOMParser::new(window, proto, can_gc))
}
}
impl DOMParserMethods for DOMParser {
// https://w3c.github.io/DOM-Parsing/#the-domparser-interface
/// <https://html.spec.whatwg.org/multipage/#dom-domparser-parsefromstring>
fn ParseFromString(
&self,
s: DOMString,

View file

@ -49,7 +49,14 @@ impl DOMPoint {
)
}
pub fn Constructor(
pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> DomRoot<DOMPoint> {
DOMPoint::new(global, p.x, p.y, p.z, p.w)
}
}
impl DOMPointMethods for DOMPoint {
// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-dompointreadonly
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -62,16 +69,10 @@ impl DOMPoint {
}
// https://drafts.fxtf.org/geometry/#dom-dompoint-frompoint
pub fn FromPoint(global: &GlobalScope, init: &DOMPointInit) -> DomRoot<Self> {
fn FromPoint(global: &GlobalScope, init: &DOMPointInit) -> DomRoot<Self> {
Self::new_from_init(global, init)
}
pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> DomRoot<DOMPoint> {
DOMPoint::new(global, p.x, p.y, p.z, p.w)
}
}
impl DOMPointMethods for DOMPoint {
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn X(&self) -> f64 {
self.point.X()

View file

@ -57,8 +57,12 @@ impl DOMPointReadOnly {
can_gc,
)
}
}
pub fn Constructor(
#[allow(non_snake_case)]
impl DOMPointReadOnlyMethods for DOMPointReadOnly {
// https://drafts.fxtf.org/geometry/#dom-dompoint-dompoint
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -73,13 +77,10 @@ impl DOMPointReadOnly {
}
// https://drafts.fxtf.org/geometry/#dom-dompointreadonly-frompoint
pub fn FromPoint(global: &GlobalScope, init: &DOMPointInit) -> DomRoot<Self> {
fn FromPoint(global: &GlobalScope, init: &DOMPointInit) -> DomRoot<Self> {
Self::new(global, init.x, init.y, init.z, init.w)
}
}
#[allow(non_snake_case)]
impl DOMPointReadOnlyMethods for DOMPointReadOnly {
// https://dev.w3.org/fxtf/geometry/Overview.html#dom-dompointreadonly-x
fn X(&self) -> f64 {
self.x.get()

View file

@ -26,7 +26,6 @@ pub struct DOMQuad {
p4: Dom<DOMPoint>,
}
#[allow(non_snake_case)]
impl DOMQuad {
fn new_inherited(p1: &DOMPoint, p2: &DOMPoint, p3: &DOMPoint, p4: &DOMPoint) -> DOMQuad {
DOMQuad {
@ -64,8 +63,11 @@ impl DOMQuad {
can_gc,
)
}
}
pub fn Constructor(
impl DOMQuadMethods for DOMQuad {
// https://drafts.fxtf.org/geometry/#dom-domquad-domquad
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -86,7 +88,7 @@ impl DOMQuad {
}
// https://drafts.fxtf.org/geometry/#dom-domquad-fromrect
pub fn FromRect(global: &GlobalScope, other: &DOMRectInit) -> DomRoot<DOMQuad> {
fn FromRect(global: &GlobalScope, other: &DOMRectInit) -> DomRoot<DOMQuad> {
DOMQuad::new(
global,
&DOMPoint::new(global, other.x, other.y, 0f64, 1f64),
@ -103,7 +105,7 @@ impl DOMQuad {
}
// https://drafts.fxtf.org/geometry/#dom-domquad-fromquad
pub fn FromQuad(global: &GlobalScope, other: &DOMQuadInit) -> DomRoot<DOMQuad> {
fn FromQuad(global: &GlobalScope, other: &DOMQuadInit) -> DomRoot<DOMQuad> {
DOMQuad::new(
global,
&DOMPoint::new_from_init(global, &other.p1),
@ -112,9 +114,7 @@ impl DOMQuad {
&DOMPoint::new_from_init(global, &other.p4),
)
}
}
impl DOMQuadMethods for DOMQuad {
// https://drafts.fxtf.org/geometry/#dom-domquad-p1
fn P1(&self) -> DomRoot<DOMPoint> {
DomRoot::from_ref(&self.p1)

View file

@ -46,9 +46,11 @@ impl DOMRect {
can_gc,
)
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl DOMRectMethods for DOMRect {
// https://drafts.fxtf.org/geometry/#dom-domrect-domrect
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -61,9 +63,7 @@ impl DOMRect {
global, proto, x, y, width, height, can_gc,
))
}
}
impl DOMRectMethods for DOMRect {
// https://drafts.fxtf.org/geometry/#dom-domrect-x
fn X(&self) -> f64 {
self.rect.X()

View file

@ -51,21 +51,6 @@ impl DOMRectReadOnly {
)
}
#[allow(non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
x: f64,
y: f64,
width: f64,
height: f64,
) -> Fallible<DomRoot<DOMRectReadOnly>> {
Ok(DOMRectReadOnly::new(
global, proto, x, y, width, height, can_gc,
))
}
pub fn set_x(&self, value: f64) {
self.x.set(value);
}
@ -84,6 +69,21 @@ impl DOMRectReadOnly {
}
impl DOMRectReadOnlyMethods for DOMRectReadOnly {
// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-domrectreadonly
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
x: f64,
y: f64,
width: f64,
height: f64,
) -> Fallible<DomRoot<DOMRectReadOnly>> {
Ok(DOMRectReadOnly::new(
global, proto, x, y, width, height, can_gc,
))
}
// https://drafts.fxtf.org/geometry/#dom-domrectreadonly-x
fn X(&self) -> f64 {
self.x.get()

View file

@ -108,9 +108,11 @@ impl ErrorEvent {
ev.error.set(error.get());
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl ErrorEventMethods for ErrorEvent {
// https://html.spec.whatwg.org/multipage/#errorevent
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -150,9 +152,7 @@ impl ErrorEvent {
);
Ok(event)
}
}
impl ErrorEventMethods for ErrorEvent {
// https://html.spec.whatwg.org/multipage/#dom-errorevent-lineno
fn Lineno(&self) -> u32 {
self.lineno.get()

View file

@ -109,26 +109,6 @@ impl Event {
event
}
#[allow(non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
type_: DOMString,
init: &EventBinding::EventInit,
) -> Fallible<DomRoot<Event>> {
let bubbles = EventBubbles::from(init.bubbles);
let cancelable = EventCancelable::from(init.cancelable);
Ok(Event::new_with_proto(
global,
proto,
Atom::from(type_),
bubbles,
cancelable,
can_gc,
))
}
pub fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) {
if self.dispatching.get() {
return;
@ -404,6 +384,26 @@ impl Event {
}
impl EventMethods for Event {
/// <https://dom.spec.whatwg.org/#dom-event-event>
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
type_: DOMString,
init: &EventBinding::EventInit,
) -> Fallible<DomRoot<Event>> {
let bubbles = EventBubbles::from(init.bubbles);
let cancelable = EventCancelable::from(init.cancelable);
Ok(Event::new_with_proto(
global,
proto,
Atom::from(type_),
bubbles,
cancelable,
can_gc,
))
}
/// <https://dom.spec.whatwg.org/#dom-event-eventphase>
fn EventPhase(&self) -> u16 {
self.phase.get() as u16

View file

@ -514,10 +514,20 @@ impl EventSource {
pub fn url(&self) -> &ServoUrl {
&self.url
}
}
// https://html.spec.whatwg.org/multipage/#garbage-collection-2
impl Drop for EventSource {
fn drop(&mut self) {
// If an EventSource object is garbage collected while its connection is still open,
// the user agent must abort any instance of the fetch algorithm opened by this EventSource.
self.canceller.borrow_mut().cancel();
}
}
impl EventSourceMethods for EventSource {
// https://html.spec.whatwg.org/multipage/#dom-eventsource
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -610,18 +620,7 @@ impl EventSource {
// Step 13
Ok(ev)
}
}
// https://html.spec.whatwg.org/multipage/#garbage-collection-2
impl Drop for EventSource {
fn drop(&mut self) {
// If an EventSource object is garbage collected while its connection is still open,
// the user agent must abort any instance of the fetch algorithm opened by this EventSource.
self.canceller.borrow_mut().cancel();
}
}
impl EventSourceMethods for EventSource {
// https://html.spec.whatwg.org/multipage/#handler-eventsource-onopen
event_handler!(open, GetOnopen, SetOnopen);

View file

@ -374,15 +374,6 @@ impl EventTarget {
)
}
#[allow(non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> Fallible<DomRoot<EventTarget>> {
Ok(EventTarget::new(global, proto, can_gc))
}
/// Determine if there are any listeners for a given event type.
/// See <https://github.com/whatwg/dom/issues/453>.
pub fn has_listeners_for(&self, type_: &Atom) -> bool {
@ -757,6 +748,15 @@ impl EventTarget {
}
impl EventTargetMethods for EventTarget {
// https://dom.spec.whatwg.org/#dom-eventtarget-eventtarget
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> Fallible<DomRoot<EventTarget>> {
Ok(EventTarget::new(global, proto, can_gc))
}
// https://dom.spec.whatwg.org/#dom-eventtarget-addeventlistener
fn AddEventListener(
&self,

View file

@ -7,7 +7,9 @@ use js::rust::{HandleObject, HandleValue};
use servo_atoms::Atom;
use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindings::ExtendableEventBinding;
use crate::dom::bindings::codegen::Bindings::ExtendableEventBinding::{
ExtendableEventInit, ExtendableEventMethods,
};
use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::reflect_dom_object_with_proto;
@ -62,13 +64,16 @@ impl ExtendableEvent {
}
ev
}
}
pub fn Constructor(
impl ExtendableEventMethods for ExtendableEvent {
// https://w3c.github.io/ServiceWorker/#dom-extendableevent-extendableevent
fn Constructor(
worker: &ServiceWorkerGlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
type_: DOMString,
init: &ExtendableEventBinding::ExtendableEventInit,
init: &ExtendableEventInit,
) -> Fallible<DomRoot<ExtendableEvent>> {
Ok(ExtendableEvent::new_with_proto(
worker,
@ -81,7 +86,7 @@ impl ExtendableEvent {
}
// https://w3c.github.io/ServiceWorker/#wait-until-method
pub fn WaitUntil(&self, _cx: JSContext, _val: HandleValue) -> ErrorResult {
fn WaitUntil(&self, _cx: JSContext, _val: HandleValue) -> ErrorResult {
// Step 1
if !self.extensions_allowed {
return Err(Error::InvalidState);
@ -92,12 +97,12 @@ impl ExtendableEvent {
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
pub fn IsTrusted(&self) -> bool {
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
impl Default for ExtendableEventBinding::ExtendableEventInit {
impl Default for ExtendableEventInit {
fn default() -> Self {
Self::empty()
}

View file

@ -9,6 +9,7 @@ use js::rust::{HandleObject, HandleValue};
use servo_atoms::Atom;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::ExtendableEventBinding::ExtendableEvent_Binding::ExtendableEventMethods;
use crate::dom::bindings::codegen::Bindings::ExtendableMessageEventBinding;
use crate::dom::bindings::codegen::Bindings::ExtendableMessageEventBinding::ExtendableMessageEventMethods;
use crate::dom::bindings::error::Fallible;
@ -116,29 +117,6 @@ impl ExtendableMessageEvent {
ev
}
pub fn Constructor(
worker: &ServiceWorkerGlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
type_: DOMString,
init: RootedTraceableBox<ExtendableMessageEventBinding::ExtendableMessageEventInit>,
) -> Fallible<DomRoot<ExtendableMessageEvent>> {
let global = worker.upcast::<GlobalScope>();
let ev = ExtendableMessageEvent::new_with_proto(
global,
proto,
Atom::from(type_),
init.parent.parent.bubbles,
init.parent.parent.cancelable,
init.data.handle(),
init.origin.clone(),
init.lastEventId.clone(),
vec![],
can_gc,
);
Ok(ev)
}
}
#[allow(non_snake_case)]
@ -179,22 +157,46 @@ impl ExtendableMessageEvent {
}
impl ExtendableMessageEventMethods for ExtendableMessageEvent {
// https://w3c.github.io/ServiceWorker/#extendablemessage-event-data-attribute
/// <https://w3c.github.io/ServiceWorker/#dom-extendablemessageevent-extendablemessageevent>
fn Constructor(
worker: &ServiceWorkerGlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
type_: DOMString,
init: RootedTraceableBox<ExtendableMessageEventBinding::ExtendableMessageEventInit>,
) -> Fallible<DomRoot<ExtendableMessageEvent>> {
let global = worker.upcast::<GlobalScope>();
let ev = ExtendableMessageEvent::new_with_proto(
global,
proto,
Atom::from(type_),
init.parent.parent.bubbles,
init.parent.parent.cancelable,
init.data.handle(),
init.origin.clone(),
init.lastEventId.clone(),
vec![],
can_gc,
);
Ok(ev)
}
/// <https://w3c.github.io/ServiceWorker/#dom-extendablemessageevent-data>
fn Data(&self, _cx: JSContext) -> JSVal {
self.data.get()
}
// https://w3c.github.io/ServiceWorker/#extendablemessage-event-origin-attribute
/// <https://w3c.github.io/ServiceWorker/#dom-extendablemessageevent-origin>
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://w3c.github.io/ServiceWorker/#extendablemessage-event-lasteventid-attribute
/// <https://w3c.github.io/ServiceWorker/#dom-extendablemessageevent-lasteventid>
fn LastEventId(&self) -> DOMString {
self.lastEventId.clone()
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
/// <https://dom.spec.whatwg.org/#dom-event-istrusted>
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}

View file

@ -91,9 +91,15 @@ impl File {
)
}
pub fn name(&self) -> &DOMString {
&self.name
}
}
impl FileMethods for File {
// https://w3c.github.io/FileAPI/#file-constructor
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -126,12 +132,6 @@ impl File {
))
}
pub fn name(&self) -> &DOMString {
&self.name
}
}
impl FileMethods for File {
// https://w3c.github.io/FileAPI/#dfn-name
fn Name(&self) -> DOMString {
self.name.clone()

View file

@ -161,15 +161,6 @@ impl FileReader {
reflect_dom_object_with_proto(Box::new(FileReader::new_inherited()), global, proto, can_gc)
}
#[allow(non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> Fallible<DomRoot<FileReader>> {
Ok(FileReader::new(global, proto, can_gc))
}
//https://w3c.github.io/FileAPI/#dfn-error-steps
pub fn process_read_error(
filereader: TrustedFileReader,
@ -334,6 +325,15 @@ impl FileReader {
}
impl FileReaderMethods for FileReader {
// https://w3c.github.io/FileAPI/#filereaderConstrctr
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> Fallible<DomRoot<FileReader>> {
Ok(FileReader::new(global, proto, can_gc))
}
// https://w3c.github.io/FileAPI/#dfn-onloadstart
event_handler!(loadstart, GetOnloadstart, SetOnloadstart);

View file

@ -46,8 +46,14 @@ impl FileReaderSync {
)
}
#[allow(non_snake_case)]
pub fn Constructor(
fn get_blob_bytes(blob: &Blob) -> Result<Vec<u8>, Error> {
blob.get_bytes().map_err(|_| Error::NotReadable)
}
}
impl FileReaderSyncMethods for FileReaderSync {
/// <https://w3c.github.io/FileAPI/#filereadersyncConstrctr>
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -55,12 +61,6 @@ impl FileReaderSync {
Ok(FileReaderSync::new(global, proto, can_gc))
}
fn get_blob_bytes(blob: &Blob) -> Result<Vec<u8>, Error> {
blob.get_bytes().map_err(|_| Error::NotReadable)
}
}
impl FileReaderSyncMethods for FileReaderSync {
/// <https://w3c.github.io/FileAPI/#readAsBinaryStringSyncSection>
fn ReadAsBinaryString(&self, blob: &Blob) -> Fallible<DOMString> {
// step 1

View file

@ -92,9 +92,11 @@ impl FocusEvent {
ev.related_target.set(related_target);
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl FocusEventMethods for FocusEvent {
// https://w3c.github.io/uievents/#dom-focusevent-focusevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -116,9 +118,7 @@ impl FocusEvent {
);
Ok(event)
}
}
impl FocusEventMethods for FocusEvent {
// https://w3c.github.io/uievents/#widl-FocusEvent-relatedTarget
fn GetRelatedTarget(&self) -> Option<DomRoot<EventTarget>> {
self.related_target.get()

View file

@ -62,10 +62,11 @@ impl FormData {
can_gc,
)
}
}
impl FormDataMethods for FormData {
// https://xhr.spec.whatwg.org/#dom-formdata
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -85,9 +86,7 @@ impl FormData {
Ok(FormData::new_with_proto(None, global, proto, can_gc))
}
}
impl FormDataMethods for FormData {
// https://xhr.spec.whatwg.org/#dom-formdata-append
fn Append(&self, name: USVString, str_value: USVString) {
let datum = FormDatum {

View file

@ -70,9 +70,11 @@ impl FormDataEvent {
}
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl FormDataEventMethods for FormDataEvent {
// https://html.spec.whatwg.org/multipage/#formdataevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -94,9 +96,7 @@ impl FormDataEvent {
Ok(event)
}
}
impl FormDataEventMethods for FormDataEvent {
// https://html.spec.whatwg.org/multipage/#dom-formdataevent-formdata
fn FormData(&self) -> DomRoot<FormData> {
DomRoot::from_ref(&*self.form_data)

View file

@ -89,9 +89,11 @@ impl GainNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl GainNodeMethods for GainNode {
// https://webaudio.github.io/web-audio-api/#dom-gainnode-gainnode
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -100,9 +102,7 @@ impl GainNode {
) -> Fallible<DomRoot<GainNode>> {
GainNode::new_with_proto(window, proto, context, options, can_gc)
}
}
impl GainNodeMethods for GainNode {
// https://webaudio.github.io/web-audio-api/#dom-gainnode-gain
fn Gain(&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.gain)

View file

@ -91,10 +91,11 @@ impl GamepadEvent {
GamepadEvent::new(global, name.into(), false, false, gamepad)
}
}
impl GamepadEventMethods for GamepadEvent {
// https://w3c.github.io/gamepad/#gamepadevent-interface
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -111,9 +112,7 @@ impl GamepadEvent {
can_gc,
))
}
}
impl GamepadEventMethods for GamepadEvent {
// https://w3c.github.io/gamepad/#gamepadevent-interface
fn Gamepad(&self) -> DomRoot<Gamepad> {
DomRoot::from_ref(&*self.gamepad)

View file

@ -6,6 +6,7 @@ use dom_struct::dom_struct;
use js::rust::HandleObject;
use super::types::GPUError;
use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPUInternalError_Binding::GPUInternalErrorMethods;
use crate::dom::bindings::reflector::reflect_dom_object_with_proto;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
@ -37,10 +38,11 @@ impl GPUInternalError {
can_gc,
)
}
}
impl GPUInternalErrorMethods for GPUInternalError {
/// <https://gpuweb.github.io/gpuweb/#dom-GPUInternalError-GPUInternalError>
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,

View file

@ -6,6 +6,7 @@ use dom_struct::dom_struct;
use js::rust::HandleObject;
use super::types::GPUError;
use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPUOutOfMemoryError_Binding::GPUOutOfMemoryErrorMethods;
use crate::dom::bindings::reflector::reflect_dom_object_with_proto;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
@ -37,10 +38,11 @@ impl GPUOutOfMemoryError {
can_gc,
)
}
}
impl GPUOutOfMemoryErrorMethods for GPUOutOfMemoryError {
/// <https://gpuweb.github.io/gpuweb/#dom-GPUOutOfMemoryError-GPUOutOfMemoryError>
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,

View file

@ -52,10 +52,11 @@ impl GPUPipelineError {
) -> DomRoot<Self> {
Self::new_with_proto(global, None, message, reason, CanGc::note())
}
}
impl GPUPipelineErrorMethods for GPUPipelineError {
/// <https://gpuweb.github.io/gpuweb/#dom-gpupipelineerror-constructor>
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -64,9 +65,7 @@ impl GPUPipelineError {
) -> DomRoot<Self> {
Self::new_with_proto(global, proto, message, options.reason, can_gc)
}
}
impl GPUPipelineErrorMethods for GPUPipelineError {
/// <https://gpuweb.github.io/gpuweb/#dom-gpupipelineerror-reason>
fn Reason(&self) -> GPUPipelineErrorReason {
self.reason

View file

@ -62,9 +62,14 @@ impl GPUUncapturedErrorEvent {
ev
}
pub fn event(&self) -> &Event {
&self.event
}
}
impl GPUUncapturedErrorEventMethods for GPUUncapturedErrorEvent {
/// <https://gpuweb.github.io/gpuweb/#dom-gpuuncapturederrorevent-gpuuncapturederrorevent>
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -73,15 +78,7 @@ impl GPUUncapturedErrorEvent {
) -> DomRoot<Self> {
GPUUncapturedErrorEvent::new_with_proto(global, proto, type_, init, can_gc)
}
}
impl GPUUncapturedErrorEvent {
pub fn event(&self) -> &Event {
&self.event
}
}
impl GPUUncapturedErrorEventMethods for GPUUncapturedErrorEvent {
/// <https://gpuweb.github.io/gpuweb/#dom-gpuuncapturederrorevent-error>
fn Error(&self) -> DomRoot<GPUError> {
DomRoot::from_ref(&self.gpu_error)

View file

@ -6,6 +6,7 @@ use dom_struct::dom_struct;
use js::rust::HandleObject;
use super::types::GPUError;
use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPUValidationError_Binding::GPUValidationErrorMethods;
use crate::dom::bindings::reflector::reflect_dom_object_with_proto;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
@ -37,10 +38,11 @@ impl GPUValidationError {
can_gc,
)
}
}
impl GPUValidationErrorMethods for GPUValidationError {
/// <https://gpuweb.github.io/gpuweb/#dom-gpuvalidationerror-gpuvalidationerror>
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,

View file

@ -94,9 +94,11 @@ impl HashChangeEvent {
}
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl HashChangeEventMethods for HashChangeEvent {
// https://html.spec.whatwg.org/multipage/#hashchangeevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -114,9 +116,7 @@ impl HashChangeEvent {
can_gc,
))
}
}
impl HashChangeEventMethods for HashChangeEvent {
// https://html.spec.whatwg.org/multipage/#dom-hashchangeevent-oldurl
fn OldURL(&self) -> USVString {
USVString(self.old_url.clone())

View file

@ -63,10 +63,11 @@ impl Headers {
) -> DomRoot<Headers> {
reflect_dom_object_with_proto(Box::new(Headers::new_inherited()), global, proto, can_gc)
}
}
impl HeadersMethods for Headers {
// https://fetch.spec.whatwg.org/#dom-headers
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -76,9 +77,7 @@ impl Headers {
dom_headers_new.fill(init)?;
Ok(dom_headers_new)
}
}
impl HeadersMethods for Headers {
// https://fetch.spec.whatwg.org/#concept-headers-append
fn Append(&self, name: ByteString, value: ByteString) -> ErrorResult {
// Step 1

View file

@ -7,6 +7,7 @@ use html5ever::{local_name, namespace_url, ns, LocalName, Prefix, QualName};
use js::rust::HandleObject;
use crate::dom::bindings::codegen::Bindings::ElementBinding::Element_Binding::ElementMethods;
use crate::dom::bindings::codegen::Bindings::HTMLAudioElementBinding::HTMLAudioElementMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
@ -50,10 +51,11 @@ impl HTMLAudioElement {
proto,
)
}
}
impl HTMLAudioElementMethods for HTMLAudioElement {
// https://html.spec.whatwg.org/multipage/#dom-audio
#[allow(non_snake_case)]
pub fn Audio(
fn Audio(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,

View file

@ -50,16 +50,16 @@ impl HTMLFormControlsCollection {
window,
)
}
// FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of
// HTMLFormControlsCollection) implements Length
#[allow(non_snake_case)]
pub fn Length(&self) -> u32 {
self.collection.Length()
}
}
impl HTMLFormControlsCollectionMethods for HTMLFormControlsCollection {
// FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of
// HTMLFormControlsCollection) implements Length
// https://dom.spec.whatwg.org/#dom-htmlcollection-length
fn Length(&self) -> u32 {
self.collection.Length()
}
// https://html.spec.whatwg.org/multipage/#dom-htmlformcontrolscollection-nameditem
fn NamedItem(&self, name: DOMString) -> Option<RadioNodeListOrElement> {
// Step 1

View file

@ -38,6 +38,7 @@ use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputE
use crate::dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::{NodeConstants, NodeMethods};
use crate::dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
use crate::dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
use crate::dom::bindings::codegen::UnionTypes::RadioNodeListOrElement;
use crate::dom::bindings::error::{Error, Fallible};

View file

@ -1356,37 +1356,6 @@ impl HTMLImageElement {
)
}
pub fn Image(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
width: Option<u32>,
height: Option<u32>,
) -> Fallible<DomRoot<HTMLImageElement>> {
let element = Element::create(
QualName::new(None, ns!(html), local_name!("img")),
None,
&window.Document(),
ElementCreator::ScriptCreated,
CustomElementCreationMode::Synchronous,
proto,
can_gc,
);
let image = DomRoot::downcast::<HTMLImageElement>(element).unwrap();
if let Some(w) = width {
image.SetWidth(w);
}
if let Some(h) = height {
image.SetHeight(h);
}
// run update_the_image_data when the element is created.
// https://html.spec.whatwg.org/multipage/#when-to-obtain-images
image.update_the_image_data(can_gc);
Ok(image)
}
pub fn areas(&self) -> Option<Vec<DomRoot<HTMLAreaElement>>> {
let elem = self.upcast::<Element>();
let usemap_attr = elem.get_attribute(&ns!(), &local_name!("usemap"))?;
@ -1568,6 +1537,39 @@ fn get_correct_referrerpolicy_from_raw_token(token: &DOMString) -> DOMString {
}
impl HTMLImageElementMethods for HTMLImageElement {
// https://html.spec.whatwg.org/multipage/#dom-image
fn Image(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
width: Option<u32>,
height: Option<u32>,
) -> Fallible<DomRoot<HTMLImageElement>> {
let element = Element::create(
QualName::new(None, ns!(html), local_name!("img")),
None,
&window.Document(),
ElementCreator::ScriptCreated,
CustomElementCreationMode::Synchronous,
proto,
can_gc,
);
let image = DomRoot::downcast::<HTMLImageElement>(element).unwrap();
if let Some(w) = width {
image.SetWidth(w);
}
if let Some(h) = height {
image.SetHeight(h);
}
// run update_the_image_data when the element is created.
// https://html.spec.whatwg.org/multipage/#when-to-obtain-images
image.update_the_image_data(can_gc);
Ok(image)
}
// https://html.spec.whatwg.org/multipage/#dom-img-alt
make_getter!(Alt, "alt");
// https://html.spec.whatwg.org/multipage/#dom-img-alt

View file

@ -55,6 +55,7 @@ use crate::dom::bindings::codegen::Bindings::MediaErrorBinding::MediaErrorMethod
use crate::dom::bindings::codegen::Bindings::NavigatorBinding::Navigator_Binding::NavigatorMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::Node_Binding::NodeMethods;
use crate::dom::bindings::codegen::Bindings::TextTrackBinding::{TextTrackKind, TextTrackMode};
use crate::dom::bindings::codegen::Bindings::URLBinding::URLMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::Window_Binding::WindowMethods;
use crate::dom::bindings::codegen::InheritTypes::{
ElementTypeId, HTMLElementTypeId, HTMLMediaElementTypeId, NodeTypeId,

View file

@ -82,43 +82,6 @@ impl HTMLOptionElement {
)
}
// https://html.spec.whatwg.org/multipage/#dom-option
#[allow(non_snake_case)]
pub fn Option(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
text: DOMString,
value: Option<DOMString>,
default_selected: bool,
selected: bool,
) -> Fallible<DomRoot<HTMLOptionElement>> {
let element = Element::create(
QualName::new(None, ns!(html), local_name!("option")),
None,
&window.Document(),
ElementCreator::ScriptCreated,
CustomElementCreationMode::Synchronous,
proto,
can_gc,
);
let option = DomRoot::downcast::<HTMLOptionElement>(element).unwrap();
if !text.is_empty() {
option.upcast::<Node>().SetTextContent(Some(text))
}
if let Some(val) = value {
option.SetValue(val)
}
option.SetDefaultSelected(default_selected);
option.set_selectedness(selected);
option.update_select_validity();
Ok(option)
}
pub fn set_selectedness(&self, selected: bool) {
self.selectedness.set(selected);
}
@ -210,6 +173,42 @@ fn collect_text(element: &Element, value: &mut String) {
}
impl HTMLOptionElementMethods for HTMLOptionElement {
// https://html.spec.whatwg.org/multipage/#dom-option
fn Option(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
text: DOMString,
value: Option<DOMString>,
default_selected: bool,
selected: bool,
) -> Fallible<DomRoot<HTMLOptionElement>> {
let element = Element::create(
QualName::new(None, ns!(html), local_name!("option")),
None,
&window.Document(),
ElementCreator::ScriptCreated,
CustomElementCreationMode::Synchronous,
proto,
can_gc,
);
let option = DomRoot::downcast::<HTMLOptionElement>(element).unwrap();
if !text.is_empty() {
option.upcast::<Node>().SetTextContent(Some(text))
}
if let Some(val) = value {
option.SetValue(val)
}
option.SetDefaultSelected(default_selected);
option.set_selectedness(selected);
option.update_select_validity();
Ok(option)
}
// https://html.spec.whatwg.org/multipage/#dom-option-disabled
make_bool_getter!(Disabled, "disabled");

View file

@ -92,9 +92,11 @@ impl IIRFilterNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl IIRFilterNodeMethods for IIRFilterNode {
/// <https://webaudio.github.io/web-audio-api/#dom-iirfilternode-iirfilternode>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -103,9 +105,7 @@ impl IIRFilterNode {
) -> Fallible<DomRoot<IIRFilterNode>> {
IIRFilterNode::new_with_proto(window, proto, context, options, can_gc)
}
}
impl IIRFilterNodeMethods for IIRFilterNode {
#[allow(unsafe_code)]
/// <https://webaudio.github.io/web-audio-api/#dom-iirfilternode-getfrequencyresponse>
fn GetFrequencyResponse(

View file

@ -146,30 +146,18 @@ impl ImageData {
imagedata, global, proto, can_gc,
))
}
/// <https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-3>
#[allow(non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
width: u32,
height: u32,
) -> Fallible<DomRoot<Self>> {
Self::new_without_jsobject(global, proto, width, height, can_gc)
#[allow(unsafe_code)]
pub fn to_shared_memory(&self) -> IpcSharedMemory {
IpcSharedMemory::from_bytes(unsafe { self.as_slice() })
}
/// <https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-4>
#[allow(unused_variables, non_snake_case)]
pub fn Constructor_(
cx: JSContext,
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
jsobject: *mut JSObject,
width: u32,
opt_height: Option<u32>,
) -> Fallible<DomRoot<Self>> {
Self::new_with_jsobject(global, proto, width, opt_height, jsobject, can_gc)
#[allow(unsafe_code)]
pub unsafe fn get_rect(&self, rect: Rect<u64>) -> Cow<[u8]> {
pixels::rgba8_get_rect(self.as_slice(), self.get_size().to_u64(), rect)
}
pub fn get_size(&self) -> Size2D<u32> {
Size2D::new(self.Width(), self.Height())
}
/// Nothing must change the array on the JS side while the slice is live.
@ -188,23 +176,33 @@ impl ImageData {
let ptr: *const [u8] = internal_data.as_slice() as *const _;
&*ptr
}
#[allow(unsafe_code)]
pub fn to_shared_memory(&self) -> IpcSharedMemory {
IpcSharedMemory::from_bytes(unsafe { self.as_slice() })
}
#[allow(unsafe_code)]
pub unsafe fn get_rect(&self, rect: Rect<u64>) -> Cow<[u8]> {
pixels::rgba8_get_rect(self.as_slice(), self.get_size().to_u64(), rect)
}
pub fn get_size(&self) -> Size2D<u32> {
Size2D::new(self.Width(), self.Height())
}
}
impl ImageDataMethods for ImageData {
/// <https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-3>
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
width: u32,
height: u32,
) -> Fallible<DomRoot<Self>> {
Self::new_without_jsobject(global, proto, width, height, can_gc)
}
/// <https://html.spec.whatwg.org/multipage/#pixel-manipulation:dom-imagedata-4>
fn Constructor_(
_cx: JSContext,
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
jsobject: *mut JSObject,
width: u32,
opt_height: Option<u32>,
) -> Fallible<DomRoot<Self>> {
Self::new_with_jsobject(global, proto, width, opt_height, jsobject, can_gc)
}
/// <https://html.spec.whatwg.org/multipage/#dom-imagedata-width>
fn Width(&self) -> u32 {
self.width

View file

@ -50,9 +50,11 @@ impl InputEvent {
.InitUIEvent(type_, can_bubble, cancelable, view, detail);
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl InputEventMethods for InputEvent {
// https://w3c.github.io/uievents/#dom-inputevent-inputevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -73,9 +75,7 @@ impl InputEvent {
);
Ok(event)
}
}
impl InputEventMethods for InputEvent {
// https://w3c.github.io/uievents/#dom-inputevent-data
fn GetData(&self) -> Option<DOMString> {
self.data.clone()

View file

@ -148,8 +148,18 @@ impl KeyboardEvent {
ev
}
#[allow(non_snake_case)]
pub fn Constructor(
pub fn key(&self) -> Key {
self.typed_key.borrow().clone()
}
pub fn modifiers(&self) -> Modifiers {
self.modifiers.get()
}
}
impl KeyboardEventMethods for KeyboardEvent {
/// <https://w3c.github.io/uievents/#dom-keyboardevent-keyboardevent>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -182,19 +192,7 @@ impl KeyboardEvent {
*event.key.borrow_mut() = init.key.clone();
Ok(event)
}
}
impl KeyboardEvent {
pub fn key(&self) -> Key {
self.typed_key.borrow().clone()
}
pub fn modifiers(&self) -> Modifiers {
self.modifiers.get()
}
}
impl KeyboardEventMethods for KeyboardEvent {
// https://w3c.github.io/uievents/#widl-KeyboardEvent-initKeyboardEvent
fn InitKeyboardEvent(
&self,
@ -219,52 +217,52 @@ impl KeyboardEventMethods for KeyboardEvent {
self.repeat.set(repeat);
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-key
/// <https://w3c.github.io/uievents/#dom-keyboardevent-initkeyboardevent>
fn Key(&self) -> DOMString {
self.key.borrow().clone()
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-code
/// <https://w3c.github.io/uievents/#dom-keyboardevent-code>
fn Code(&self) -> DOMString {
self.code.borrow().clone()
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-location
/// <https://w3c.github.io/uievents/#dom-keyboardevent-location>
fn Location(&self) -> u32 {
self.location.get()
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-ctrlKey
/// <https://w3c.github.io/uievents/#dom-keyboardevent-ctrlkey>
fn CtrlKey(&self) -> bool {
self.modifiers.get().contains(Modifiers::CONTROL)
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-shiftKey
/// <https://w3c.github.io/uievents/#dom-keyboardevent-shiftkey>
fn ShiftKey(&self) -> bool {
self.modifiers.get().contains(Modifiers::SHIFT)
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-altKey
/// <https://w3c.github.io/uievents/#dom-keyboardevent-altkey>
fn AltKey(&self) -> bool {
self.modifiers.get().contains(Modifiers::ALT)
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-metaKey
/// <https://w3c.github.io/uievents/#dom-keyboardevent-metakey>
fn MetaKey(&self) -> bool {
self.modifiers.get().contains(Modifiers::META)
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-repeat
/// <https://w3c.github.io/uievents/#dom-keyboardevent-repeat>
fn Repeat(&self) -> bool {
self.repeat.get()
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-isComposing
/// <https://w3c.github.io/uievents/#dom-keyboardevent-iscomposing>
fn IsComposing(&self) -> bool {
self.is_composing.get()
}
// https://w3c.github.io/uievents/#dom-keyboardevent-getmodifierstate
/// <https://w3c.github.io/uievents/#dom-keyboardevent-getmodifierstate>
fn GetModifierState(&self, key_arg: DOMString) -> bool {
self.modifiers.get().contains(match &*key_arg {
"Alt" => Modifiers::ALT,
@ -283,17 +281,17 @@ impl KeyboardEventMethods for KeyboardEvent {
})
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-charCode
/// <https://w3c.github.io/uievents/#dom-keyboardevent-charcode>
fn CharCode(&self) -> u32 {
self.char_code.get()
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-keyCode
/// <https://w3c.github.io/uievents/#dom-keyboardevent-keycode>
fn KeyCode(&self) -> u32 {
self.key_code.get()
}
// https://w3c.github.io/uievents/#widl-KeyboardEvent-which
/// <https://w3c.github.io/uievents/#dom-uievent-which>
fn Which(&self) -> u32 {
if self.char_code.get() != 0 {
self.char_code.get()
@ -302,7 +300,7 @@ impl KeyboardEventMethods for KeyboardEvent {
}
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
/// <https://dom.spec.whatwg.org/#dom-event-istrusted>
fn IsTrusted(&self) -> bool {
self.uievent.IsTrusted()
}

View file

@ -78,9 +78,11 @@ impl MediaElementAudioSourceNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl MediaElementAudioSourceNodeMethods for MediaElementAudioSourceNode {
/// <https://webaudio.github.io/web-audio-api/#dom-mediaelementaudiosourcenode-mediaelementaudiosourcenode>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -95,9 +97,7 @@ impl MediaElementAudioSourceNode {
can_gc,
)
}
}
impl MediaElementAudioSourceNodeMethods for MediaElementAudioSourceNode {
/// <https://webaudio.github.io/web-audio-api/#dom-mediaelementaudiosourcenode-mediaelement>
fn MediaElement(&self) -> DomRoot<HTMLMediaElement> {
DomRoot::from_ref(&*self.media_element)

View file

@ -55,17 +55,6 @@ impl MediaMetadata {
)
}
/// <https://w3c.github.io/mediasession/#dom-mediametadata-mediametadata>
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
init: &MediaMetadataInit,
) -> Fallible<DomRoot<MediaMetadata>> {
Ok(MediaMetadata::new_with_proto(window, proto, init, can_gc))
}
fn queue_update_metadata_algorithm(&self) {
if self.session.get().is_none() {}
}
@ -76,6 +65,16 @@ impl MediaMetadata {
}
impl MediaMetadataMethods for MediaMetadata {
/// <https://w3c.github.io/mediasession/#dom-mediametadata-mediametadata>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
init: &MediaMetadataInit,
) -> Fallible<DomRoot<MediaMetadata>> {
Ok(MediaMetadata::new_with_proto(window, proto, init, can_gc))
}
/// <https://w3c.github.io/mediasession/#dom-mediametadata-title>
fn Title(&self) -> DOMString {
self.title.borrow().clone()

View file

@ -84,9 +84,11 @@ impl MediaQueryListEvent {
}
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl MediaQueryListEventMethods for MediaQueryListEvent {
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-mediaquerylistevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -105,9 +107,7 @@ impl MediaQueryListEvent {
can_gc,
))
}
}
impl MediaQueryListEventMethods for MediaQueryListEvent {
// https://drafts.csswg.org/cssom-view/#dom-mediaquerylistevent-media
fn Media(&self) -> DOMString {
self.media.clone()

View file

@ -25,7 +25,6 @@ pub struct MediaStream {
tracks: DomRefCell<Vec<Dom<MediaStreamTrack>>>,
}
#[allow(non_snake_case)]
impl MediaStream {
pub fn new_inherited() -> MediaStream {
MediaStream {
@ -62,7 +61,18 @@ impl MediaStream {
this
}
pub fn Constructor(
pub fn get_tracks(&self) -> Ref<[Dom<MediaStreamTrack>]> {
Ref::map(self.tracks.borrow(), |tracks| &**tracks)
}
pub fn add_track(&self, track: &MediaStreamTrack) {
self.tracks.borrow_mut().push(Dom::from_ref(track))
}
}
impl MediaStreamMethods for MediaStream {
/// <https://w3c.github.io/mediacapture-main/#dom-mediastream-constructor>
fn Constructor(
global: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -70,7 +80,8 @@ impl MediaStream {
Ok(MediaStream::new_with_proto(&global.global(), proto, can_gc))
}
pub fn Constructor_(
/// <https://w3c.github.io/mediacapture-main/#dom-mediastream-constructor>
fn Constructor_(
_: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -79,7 +90,8 @@ impl MediaStream {
Ok(stream.clone_with_proto(proto, can_gc))
}
pub fn Constructor__(
/// <https://w3c.github.io/mediacapture-main/#dom-mediastream-constructor>
fn Constructor__(
global: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -94,16 +106,6 @@ impl MediaStream {
Ok(new)
}
pub fn get_tracks(&self) -> Ref<[Dom<MediaStreamTrack>]> {
Ref::map(self.tracks.borrow(), |tracks| &**tracks)
}
pub fn add_track(&self, track: &MediaStreamTrack) {
self.tracks.borrow_mut().push(Dom::from_ref(track))
}
}
impl MediaStreamMethods for MediaStream {
/// <https://w3c.github.io/mediacapture-main/#dom-mediastream-gettracks>
fn GetTracks(&self) -> Vec<DomRoot<MediaStreamTrack>> {
self.tracks

View file

@ -79,9 +79,11 @@ impl MediaStreamAudioDestinationNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl MediaStreamAudioDestinationNodeMethods for MediaStreamAudioDestinationNode {
/// <https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiodestinationnode-mediastreamaudiodestinationnode>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -90,9 +92,7 @@ impl MediaStreamAudioDestinationNode {
) -> Fallible<DomRoot<MediaStreamAudioDestinationNode>> {
MediaStreamAudioDestinationNode::new_with_proto(window, proto, context, options, can_gc)
}
}
impl MediaStreamAudioDestinationNodeMethods for MediaStreamAudioDestinationNode {
/// <https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiodestinationnode-stream>
fn Stream(&self) -> DomRoot<MediaStream> {
DomRoot::from_ref(&self.stream)

View file

@ -75,9 +75,11 @@ impl MediaStreamAudioSourceNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl MediaStreamAudioSourceNodeMethods for MediaStreamAudioSourceNode {
/// <https://webaudio.github.io/web-audio-api/#dom-mediastreamaudiosourcenode-mediastreamaudiosourcenode>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -92,9 +94,7 @@ impl MediaStreamAudioSourceNode {
can_gc,
)
}
}
impl MediaStreamAudioSourceNodeMethods for MediaStreamAudioSourceNode {
/// <https://webaudio.github.io/web-audio-api/#dom-MediaStreamAudioSourceNode-stream>
fn MediaStream(&self) -> DomRoot<MediaStream> {
DomRoot::from_ref(&self.stream)

View file

@ -8,7 +8,9 @@ use servo_media::audio::node::AudioNodeInit;
use crate::dom::audiocontext::AudioContext;
use crate::dom::audionode::AudioNode;
use crate::dom::bindings::codegen::Bindings::MediaStreamTrackAudioSourceNodeBinding::MediaStreamTrackAudioSourceOptions;
use crate::dom::bindings::codegen::Bindings::MediaStreamTrackAudioSourceNodeBinding::{
MediaStreamTrackAudioSourceNodeMethods, MediaStreamTrackAudioSourceOptions,
};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::reflect_dom_object_with_proto;
@ -66,9 +68,11 @@ impl MediaStreamTrackAudioSourceNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl MediaStreamTrackAudioSourceNodeMethods for MediaStreamTrackAudioSourceNode {
/// <https://webaudio.github.io/web-audio-api/#dom-mediastreamtrackaudiosourcenode-mediastreamtrackaudiosourcenode>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,

View file

@ -20,16 +20,6 @@ pub struct MessageChannel {
}
impl MessageChannel {
/// <https://html.spec.whatwg.org/multipage/#dom-messagechannel>
#[allow(non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> DomRoot<MessageChannel> {
MessageChannel::new(global, proto, can_gc)
}
/// <https://html.spec.whatwg.org/multipage/#dom-messagechannel>
fn new(
incumbent: &GlobalScope,
@ -67,6 +57,15 @@ impl MessageChannel {
}
impl MessageChannelMethods for MessageChannel {
/// <https://html.spec.whatwg.org/multipage/#dom-messagechannel>
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> DomRoot<MessageChannel> {
MessageChannel::new(global, proto, can_gc)
}
/// <https://html.spec.whatwg.org/multipage/#dom-messagechannel-port1>
fn Port1(&self) -> DomRoot<MessagePort> {
DomRoot::from_ref(&*self.port1)

View file

@ -193,31 +193,6 @@ impl MessageEvent {
ev
}
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
type_: DOMString,
init: RootedTraceableBox<MessageEventBinding::MessageEventInit>,
) -> Fallible<DomRoot<MessageEvent>> {
let ev = MessageEvent::new_with_proto(
global,
proto,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
init.data.handle(),
init.origin.clone(),
init.source.as_ref(),
init.lastEventId.clone(),
init.ports.clone(),
can_gc,
);
Ok(ev)
}
}
impl MessageEvent {
pub fn dispatch_jsval(
target: &EventTarget,
scope: &GlobalScope,
@ -262,6 +237,30 @@ impl MessageEvent {
}
impl MessageEventMethods for MessageEvent {
/// <https://html.spec.whatwg.org/multipage/#messageevent>
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
type_: DOMString,
init: RootedTraceableBox<MessageEventBinding::MessageEventInit>,
) -> Fallible<DomRoot<MessageEvent>> {
let ev = MessageEvent::new_with_proto(
global,
proto,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
init.data.handle(),
init.origin.clone(),
init.source.as_ref(),
init.lastEventId.clone(),
init.ports.clone(),
can_gc,
);
Ok(ev)
}
/// <https://html.spec.whatwg.org/multipage/#dom-messageevent-data>
fn Data(&self, _cx: JSContext) -> JSVal {
self.data.get()

View file

@ -181,8 +181,14 @@ impl MouseEvent {
ev
}
#[allow(non_snake_case)]
pub fn Constructor(
pub fn point_in_target(&self) -> Option<Point2D<f32>> {
self.point_in_target.get()
}
}
impl MouseEventMethods for MouseEvent {
// https://w3c.github.io/uievents/#dom-mouseevent-mouseevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -216,12 +222,6 @@ impl MouseEvent {
Ok(event)
}
pub fn point_in_target(&self) -> Option<Point2D<f32>> {
self.point_in_target.get()
}
}
impl MouseEventMethods for MouseEvent {
// https://w3c.github.io/uievents/#widl-MouseEvent-screenX
fn ScreenX(&self) -> i32 {
self.screen_x.get()

View file

@ -88,19 +88,6 @@ impl MutationObserver {
}
}
#[allow(non_snake_case)]
pub fn Constructor(
global: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
callback: Rc<MutationCallback>,
) -> Fallible<DomRoot<MutationObserver>> {
global.set_exists_mut_observer();
let observer = MutationObserver::new_with_proto(global, proto, callback, can_gc);
ScriptThread::add_mutation_observer(&observer);
Ok(observer)
}
/// <https://dom.spec.whatwg.org/#queue-a-mutation-observer-compound-microtask>
pub fn queue_mutation_observer_microtask() {
// Step 1
@ -261,6 +248,19 @@ impl MutationObserver {
}
impl MutationObserverMethods for MutationObserver {
/// <https://dom.spec.whatwg.org/#dom-mutationobserver-mutationobserver>
fn Constructor(
global: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
callback: Rc<MutationCallback>,
) -> Fallible<DomRoot<MutationObserver>> {
global.set_exists_mut_observer();
let observer = MutationObserver::new_with_proto(global, proto, callback, can_gc);
ScriptThread::add_mutation_observer(&observer);
Ok(observer)
}
/// <https://dom.spec.whatwg.org/#dom-mutationobserver-observe>
fn Observe(&self, target: &Node, options: &MutationObserverInit) -> Fallible<()> {
let attribute_filter = options.attributeFilter.clone().unwrap_or_default();

View file

@ -69,9 +69,11 @@ impl OfflineAudioCompletionEvent {
}
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl OfflineAudioCompletionEventMethods for OfflineAudioCompletionEvent {
// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocompletionevent-offlineaudiocompletionevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -90,9 +92,7 @@ impl OfflineAudioCompletionEvent {
can_gc,
))
}
}
impl OfflineAudioCompletionEventMethods for OfflineAudioCompletionEvent {
// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocompletionevent-renderedbuffer
fn RenderedBuffer(&self) -> DomRoot<AudioBuffer> {
DomRoot::from_ref(&*self.rendered_buffer)

View file

@ -44,7 +44,6 @@ pub struct OfflineAudioContext {
pending_rendering_promise: DomRefCell<Option<Rc<Promise>>>,
}
#[allow(non_snake_case)]
impl OfflineAudioContext {
#[allow(crown::unrooted_must_root)]
fn new_inherited(
@ -97,8 +96,11 @@ impl OfflineAudioContext {
can_gc,
))
}
}
pub fn Constructor(
impl OfflineAudioContextMethods for OfflineAudioContext {
// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-offlineaudiocontext
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -114,7 +116,8 @@ impl OfflineAudioContext {
)
}
pub fn Constructor_(
// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-offlineaudiocontext-numberofchannels-length-samplerate
fn Constructor_(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -131,9 +134,7 @@ impl OfflineAudioContext {
can_gc,
)
}
}
impl OfflineAudioContextMethods for OfflineAudioContext {
// https://webaudio.github.io/web-audio-api/#dom-offlineaudiocontext-oncomplete
event_handler!(complete, GetOncomplete, SetOncomplete);

View file

@ -73,18 +73,6 @@ impl OffscreenCanvas {
)
}
#[allow(non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
width: u64,
height: u64,
) -> Fallible<DomRoot<OffscreenCanvas>> {
let offscreencanvas = OffscreenCanvas::new(global, proto, width, height, None, can_gc);
Ok(offscreencanvas)
}
pub fn get_size(&self) -> Size2D<u64> {
Size2D::new(self.Width(), self.Height())
}
@ -151,6 +139,18 @@ impl OffscreenCanvas {
}
impl OffscreenCanvasMethods for OffscreenCanvas {
// https://html.spec.whatwg.org/multipage/#dom-offscreencanvas
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
width: u64,
height: u64,
) -> Fallible<DomRoot<OffscreenCanvas>> {
let offscreencanvas = OffscreenCanvas::new(global, proto, width, height, None, can_gc);
Ok(offscreencanvas)
}
// https://html.spec.whatwg.org/multipage/#dom-offscreencanvas-getcontext
fn GetContext(
&self,

View file

@ -111,9 +111,11 @@ impl OscillatorNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl OscillatorNodeMethods for OscillatorNode {
// https://webaudio.github.io/web-audio-api/#dom-oscillatornode-oscillatornode
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -122,9 +124,7 @@ impl OscillatorNode {
) -> Fallible<DomRoot<OscillatorNode>> {
OscillatorNode::new_with_proto(window, proto, context, options, can_gc)
}
}
impl OscillatorNodeMethods for OscillatorNode {
// https://webaudio.github.io/web-audio-api/#dom-oscillatornode-frequency
fn Frequency(&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.frequency)

View file

@ -83,9 +83,11 @@ impl PageTransitionEvent {
}
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl PageTransitionEventMethods for PageTransitionEvent {
// https://html.spec.whatwg.org/multipage/#pagetransitionevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -102,9 +104,7 @@ impl PageTransitionEvent {
can_gc,
))
}
}
impl PageTransitionEventMethods for PageTransitionEvent {
// https://html.spec.whatwg.org/multipage/#dom-pagetransitionevent-persisted
fn Persisted(&self) -> bool {
self.persisted.get()

View file

@ -204,9 +204,11 @@ impl PannerNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl PannerNodeMethods for PannerNode {
// https://webaudio.github.io/web-audio-api/#dom-pannernode-pannernode
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -215,9 +217,7 @@ impl PannerNode {
) -> Fallible<DomRoot<PannerNode>> {
PannerNode::new_with_proto(window, proto, context, options, can_gc)
}
}
impl PannerNodeMethods for PannerNode {
// https://webaudio.github.io/web-audio-api/#dom-pannernode-positionx
fn PositionX(&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.position_x)

View file

@ -86,22 +86,6 @@ impl PerformanceObserver {
reflect_dom_object_with_proto(Box::new(observer), global, proto, can_gc)
}
#[allow(non_snake_case)]
pub fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
callback: Rc<PerformanceObserverCallback>,
) -> Fallible<DomRoot<PerformanceObserver>> {
Ok(PerformanceObserver::new_with_proto(
global,
proto,
callback,
Vec::new(),
can_gc,
))
}
/// Buffer a new performance entry.
pub fn queue_entry(&self, entry: &PerformanceEntry) {
self.entries.borrow_mut().push(DomRoot::from_ref(entry));
@ -132,17 +116,32 @@ impl PerformanceObserver {
pub fn set_entries(&self, entries: DOMPerformanceEntryList) {
*self.entries.borrow_mut() = entries;
}
}
impl PerformanceObserverMethods for PerformanceObserver {
// https://w3c.github.io/performance-timeline/#dom-performanceobserver-constructor
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
callback: Rc<PerformanceObserverCallback>,
) -> Fallible<DomRoot<PerformanceObserver>> {
Ok(PerformanceObserver::new_with_proto(
global,
proto,
callback,
Vec::new(),
can_gc,
))
}
// https://w3c.github.io/performance-timeline/#supportedentrytypes-attribute
#[allow(non_snake_case)]
pub fn SupportedEntryTypes(cx: JSContext, global: &GlobalScope) -> JSVal {
fn SupportedEntryTypes(cx: JSContext, global: &GlobalScope) -> JSVal {
// While this is exposed through a method of PerformanceObserver,
// it is specified as associated with the global scope.
global.supported_performance_entry_types(cx)
}
}
impl PerformanceObserverMethods for PerformanceObserver {
// https://w3c.github.io/performance-timeline/#dom-performanceobserver-observe()
fn Observe(&self, options: &PerformanceObserverInit) -> Fallible<()> {
// Step 1 is self

View file

@ -69,8 +69,23 @@ impl PopStateEvent {
ev
}
#[allow(non_snake_case)]
pub fn Constructor(
pub fn dispatch_jsval(target: &EventTarget, window: &Window, state: HandleValue) {
let event = PopStateEvent::new(
window,
None,
atom!("popstate"),
false,
false,
state,
CanGc::note(),
);
event.upcast::<Event>().fire(target);
}
}
impl PopStateEventMethods for PopStateEvent {
// https://html.spec.whatwg.org/multipage/#popstateevent
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -88,21 +103,6 @@ impl PopStateEvent {
))
}
pub fn dispatch_jsval(target: &EventTarget, window: &Window, state: HandleValue) {
let event = PopStateEvent::new(
window,
None,
atom!("popstate"),
false,
false,
state,
CanGc::note(),
);
event.upcast::<Event>().fire(target);
}
}
impl PopStateEventMethods for PopStateEvent {
// https://html.spec.whatwg.org/multipage/#dom-popstateevent-state
fn State(&self, _cx: JSContext) -> JSVal {
self.state.get()

View file

@ -86,9 +86,11 @@ impl ProgressEvent {
}
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl ProgressEventMethods for ProgressEvent {
// https://xhr.spec.whatwg.org/#dom-progressevent-progressevent
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -110,9 +112,7 @@ impl ProgressEvent {
);
Ok(ev)
}
}
impl ProgressEventMethods for ProgressEvent {
// https://xhr.spec.whatwg.org/#dom-progressevent-lengthcomputable
fn LengthComputable(&self) -> bool {
self.length_computable

View file

@ -92,9 +92,11 @@ impl PromiseRejectionEvent {
}
ev
}
}
#[allow(crown::unrooted_must_root, non_snake_case)]
pub fn Constructor(
impl PromiseRejectionEventMethods for PromiseRejectionEvent {
// https://html.spec.whatwg.org/multipage/#promiserejectionevent
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -117,9 +119,7 @@ impl PromiseRejectionEvent {
);
Ok(event)
}
}
impl PromiseRejectionEventMethods for PromiseRejectionEvent {
// https://html.spec.whatwg.org/multipage/#dom-promiserejectionevent-promise
fn Promise(&self, _cx: JSContext) -> NonNull<JSObject> {
NonNull::new(self.promise.get()).unwrap()

View file

@ -61,16 +61,15 @@ impl RadioNodeList {
NodeListType::Radio(RadioList::new(form, RadioListMode::Images, name.clone())),
)
}
// https://dom.spec.whatwg.org/#dom-nodelist-length
// https://github.com/servo/servo/issues/5875
#[allow(non_snake_case)]
pub fn Length(&self) -> u32 {
self.node_list.Length()
}
}
impl RadioNodeListMethods for RadioNodeList {
// https://dom.spec.whatwg.org/#dom-nodelist-length
// https://github.com/servo/servo/issues/5875
fn Length(&self) -> u32 {
self.node_list.Length()
}
// https://html.spec.whatwg.org/multipage/#dom-radionodelist-value
fn Value(&self) -> DOMString {
self.upcast::<NodeList>()

View file

@ -127,17 +127,6 @@ impl Range {
range
}
/// <https://dom.spec.whatwg.org/#dom-range>
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> Fallible<DomRoot<Range>> {
let document = window.Document();
Ok(Range::new_with_doc(&document, proto, can_gc))
}
/// <https://dom.spec.whatwg.org/#contained>
fn contains(&self, node: &Node) -> bool {
matches!(
@ -338,6 +327,16 @@ impl Range {
}
impl RangeMethods for Range {
/// <https://dom.spec.whatwg.org/#dom-range>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
) -> Fallible<DomRoot<Range>> {
let document = window.Document();
Ok(Range::new_with_doc(&document, proto, can_gc))
}
/// <https://dom.spec.whatwg.org/#dom-range-commonancestorcontainer>
fn CommonAncestorContainer(&self) -> DomRoot<Node> {
self.end_container()

View file

@ -74,9 +74,89 @@ impl Request {
)
}
fn from_net_request(
global: &GlobalScope,
proto: Option<HandleObject>,
net_request: NetTraitsRequest,
can_gc: CanGc,
) -> DomRoot<Request> {
let r = Request::new(global, proto, net_request.current_url(), can_gc);
*r.request.borrow_mut() = net_request;
r
}
fn clone_from(r: &Request, can_gc: CanGc) -> Fallible<DomRoot<Request>> {
let req = r.request.borrow();
let url = req.url();
let headers_guard = r.Headers().get_guard();
let r_clone = Request::new(&r.global(), None, url, can_gc);
r_clone.request.borrow_mut().pipeline_id = req.pipeline_id;
{
let mut borrowed_r_request = r_clone.request.borrow_mut();
borrowed_r_request.origin = req.origin.clone();
}
*r_clone.request.borrow_mut() = req.clone();
r_clone.Headers().copy_from_headers(r.Headers())?;
r_clone.Headers().set_guard(headers_guard);
Ok(r_clone)
}
pub fn get_request(&self) -> NetTraitsRequest {
self.request.borrow().clone()
}
}
fn net_request_from_global(global: &GlobalScope, url: ServoUrl) -> NetTraitsRequest {
let origin = Origin::Origin(global.get_url().origin());
let https_state = global.get_https_state();
let pipeline_id = global.pipeline_id();
let referrer = global.get_referrer();
NetTraitsRequest::new(url, Some(origin), referrer, Some(pipeline_id), https_state)
}
// https://fetch.spec.whatwg.org/#concept-method-normalize
fn normalize_method(m: &str) -> Result<HttpMethod, InvalidMethod> {
match_ignore_ascii_case! { m,
"delete" => return Ok(HttpMethod::DELETE),
"get" => return Ok(HttpMethod::GET),
"head" => return Ok(HttpMethod::HEAD),
"options" => return Ok(HttpMethod::OPTIONS),
"post" => return Ok(HttpMethod::POST),
"put" => return Ok(HttpMethod::PUT),
_ => (),
}
debug!("Method: {:?}", m);
HttpMethod::from_str(m)
}
// https://fetch.spec.whatwg.org/#concept-method
fn is_method(m: &ByteString) -> bool {
m.as_str().is_some()
}
// https://fetch.spec.whatwg.org/#cors-safelisted-method
fn is_cors_safelisted_method(m: &HttpMethod) -> bool {
m == HttpMethod::GET || m == HttpMethod::HEAD || m == HttpMethod::POST
}
// https://url.spec.whatwg.org/#include-credentials
fn includes_credentials(input: &ServoUrl) -> bool {
!input.username().is_empty() || input.password().is_some()
}
// https://fetch.spec.whatwg.org/#concept-body-disturbed
fn request_is_disturbed(input: &Request) -> bool {
input.is_disturbed()
}
// https://fetch.spec.whatwg.org/#concept-body-locked
fn request_is_locked(input: &Request) -> bool {
input.is_locked()
}
impl RequestMethods for Request {
// https://fetch.spec.whatwg.org/#dom-request
#[allow(non_snake_case)]
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -441,90 +521,7 @@ impl Request {
// Step 42
Ok(r)
}
}
impl Request {
fn from_net_request(
global: &GlobalScope,
proto: Option<HandleObject>,
net_request: NetTraitsRequest,
can_gc: CanGc,
) -> DomRoot<Request> {
let r = Request::new(global, proto, net_request.current_url(), can_gc);
*r.request.borrow_mut() = net_request;
r
}
fn clone_from(r: &Request, can_gc: CanGc) -> Fallible<DomRoot<Request>> {
let req = r.request.borrow();
let url = req.url();
let headers_guard = r.Headers().get_guard();
let r_clone = Request::new(&r.global(), None, url, can_gc);
r_clone.request.borrow_mut().pipeline_id = req.pipeline_id;
{
let mut borrowed_r_request = r_clone.request.borrow_mut();
borrowed_r_request.origin = req.origin.clone();
}
*r_clone.request.borrow_mut() = req.clone();
r_clone.Headers().copy_from_headers(r.Headers())?;
r_clone.Headers().set_guard(headers_guard);
Ok(r_clone)
}
pub fn get_request(&self) -> NetTraitsRequest {
self.request.borrow().clone()
}
}
fn net_request_from_global(global: &GlobalScope, url: ServoUrl) -> NetTraitsRequest {
let origin = Origin::Origin(global.get_url().origin());
let https_state = global.get_https_state();
let pipeline_id = global.pipeline_id();
let referrer = global.get_referrer();
NetTraitsRequest::new(url, Some(origin), referrer, Some(pipeline_id), https_state)
}
// https://fetch.spec.whatwg.org/#concept-method-normalize
fn normalize_method(m: &str) -> Result<HttpMethod, InvalidMethod> {
match_ignore_ascii_case! { m,
"delete" => return Ok(HttpMethod::DELETE),
"get" => return Ok(HttpMethod::GET),
"head" => return Ok(HttpMethod::HEAD),
"options" => return Ok(HttpMethod::OPTIONS),
"post" => return Ok(HttpMethod::POST),
"put" => return Ok(HttpMethod::PUT),
_ => (),
}
debug!("Method: {:?}", m);
HttpMethod::from_str(m)
}
// https://fetch.spec.whatwg.org/#concept-method
fn is_method(m: &ByteString) -> bool {
m.as_str().is_some()
}
// https://fetch.spec.whatwg.org/#cors-safelisted-method
fn is_cors_safelisted_method(m: &HttpMethod) -> bool {
m == HttpMethod::GET || m == HttpMethod::HEAD || m == HttpMethod::POST
}
// https://url.spec.whatwg.org/#include-credentials
fn includes_credentials(input: &ServoUrl) -> bool {
!input.username().is_empty() || input.password().is_some()
}
// https://fetch.spec.whatwg.org/#concept-body-disturbed
fn request_is_disturbed(input: &Request) -> bool {
input.is_disturbed()
}
// https://fetch.spec.whatwg.org/#concept-body-locked
fn request_is_locked(input: &Request) -> bool {
input.is_locked()
}
impl RequestMethods for Request {
// https://fetch.spec.whatwg.org/#dom-request-method
fn Method(&self) -> ByteString {
let r = self.request.borrow();

View file

@ -68,20 +68,6 @@ impl ResizeObserver {
reflect_dom_object_with_proto(observer, window, proto, can_gc)
}
/// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-resizeobserver>
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
callback: Rc<ResizeObserverCallback>,
) -> DomRoot<ResizeObserver> {
let rooted_observer = ResizeObserver::new(window, proto, callback, can_gc);
let document = window.Document();
document.add_resize_observer(&rooted_observer);
rooted_observer
}
/// <https://drafts.csswg.org/resize-observer/#gather-active-observations-h>
/// <https://drafts.csswg.org/resize-observer/#has-active-resize-observations>
pub fn gather_active_resize_observations_at_depth(
@ -169,6 +155,19 @@ impl ResizeObserver {
}
impl ResizeObserverMethods for ResizeObserver {
/// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-resizeobserver>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
callback: Rc<ResizeObserverCallback>,
) -> DomRoot<ResizeObserver> {
let rooted_observer = ResizeObserver::new(window, proto, callback, can_gc);
let document = window.Document();
document.add_resize_observer(&rooted_observer);
rooted_observer
}
/// <https://drafts.csswg.org/resize-observer/#dom-resizeobserver-observe>
fn Observe(&self, target: &Element, options: &ResizeObserverOptions) {
let is_present = self

View file

@ -89,8 +89,60 @@ impl Response {
)
}
pub fn error_stream(&self, error: Error) {
if let Some(body) = self.body_stream.get() {
body.error_native(error);
}
}
}
impl BodyMixin for Response {
fn is_disturbed(&self) -> bool {
self.body_stream
.get()
.is_some_and(|stream| stream.is_disturbed())
}
fn is_locked(&self) -> bool {
self.body_stream
.get()
.is_some_and(|stream| stream.is_locked())
}
fn body(&self) -> Option<DomRoot<ReadableStream>> {
self.body_stream.get()
}
fn get_mime_type(&self) -> Vec<u8> {
let headers = self.Headers();
headers.extract_mime_type()
}
}
// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}
// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_status_text(status_text: &ByteString) -> bool {
// reason-phrase = *( HTAB / SP / VCHAR / obs-text )
for byte in status_text.iter() {
if !(*byte == b'\t' || *byte == b' ' || is_vchar(*byte) || is_obs_text(*byte)) {
return false;
}
}
true
}
// https://fetch.spec.whatwg.org/#null-body-status
fn is_null_body_status(status: u16) -> bool {
status == 101 || status == 204 || status == 205 || status == 304
}
impl ResponseMethods for Response {
// https://fetch.spec.whatwg.org/#initialize-a-response
pub fn Constructor(
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -166,7 +218,7 @@ impl Response {
}
// https://fetch.spec.whatwg.org/#dom-response-error
pub fn Error(global: &GlobalScope) -> DomRoot<Response> {
fn Error(global: &GlobalScope) -> DomRoot<Response> {
let r = Response::new(global);
*r.response_type.borrow_mut() = DOMResponseType::Error;
r.Headers().set_guard(Guard::Immutable);
@ -175,11 +227,7 @@ impl Response {
}
// https://fetch.spec.whatwg.org/#dom-response-redirect
pub fn Redirect(
global: &GlobalScope,
url: USVString,
status: u16,
) -> Fallible<DomRoot<Response>> {
fn Redirect(global: &GlobalScope, url: USVString, status: u16) -> Fallible<DomRoot<Response>> {
// Step 1
let base_url = global.api_base_url();
let parsed_url = base_url.join(&url.0);
@ -216,58 +264,6 @@ impl Response {
Ok(r)
}
pub fn error_stream(&self, error: Error) {
if let Some(body) = self.body_stream.get() {
body.error_native(error);
}
}
}
impl BodyMixin for Response {
fn is_disturbed(&self) -> bool {
self.body_stream
.get()
.is_some_and(|stream| stream.is_disturbed())
}
fn is_locked(&self) -> bool {
self.body_stream
.get()
.is_some_and(|stream| stream.is_locked())
}
fn body(&self) -> Option<DomRoot<ReadableStream>> {
self.body_stream.get()
}
fn get_mime_type(&self) -> Vec<u8> {
let headers = self.Headers();
headers.extract_mime_type()
}
}
// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}
// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_status_text(status_text: &ByteString) -> bool {
// reason-phrase = *( HTAB / SP / VCHAR / obs-text )
for byte in status_text.iter() {
if !(*byte == b'\t' || *byte == b' ' || is_vchar(*byte) || is_obs_text(*byte)) {
return false;
}
}
true
}
// https://fetch.spec.whatwg.org/#null-body-status
fn is_null_body_status(status: u16) -> bool {
status == 101 || status == 204 || status == 205 || status == 304
}
impl ResponseMethods for Response {
// https://fetch.spec.whatwg.org/#dom-response-type
fn Type(&self) -> DOMResponseType {
*self.response_type.borrow() //into()

View file

@ -73,9 +73,11 @@ impl RTCDataChannelEvent {
}
event
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl RTCDataChannelEventMethods for RTCDataChannelEvent {
// https://www.w3.org/TR/webrtc/#dom-rtcdatachannelevent-constructor
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -92,9 +94,7 @@ impl RTCDataChannelEvent {
can_gc,
)
}
}
impl RTCDataChannelEventMethods for RTCDataChannelEvent {
// https://www.w3.org/TR/webrtc/#dom-datachannelevent-channel
fn Channel(&self) -> DomRoot<RTCDataChannel> {
DomRoot::from_ref(&*self.channel)

View file

@ -61,9 +61,11 @@ impl RTCError {
can_gc,
)
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl RTCErrorMethods for RTCError {
// https://www.w3.org/TR/webrtc/#dom-rtcerror-constructor
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -72,9 +74,7 @@ impl RTCError {
) -> DomRoot<RTCError> {
RTCError::new_with_proto(&window.global(), proto, init, message, can_gc)
}
}
impl RTCErrorMethods for RTCError {
// https://www.w3.org/TR/webrtc/#dom-rtcerror-errordetail
fn ErrorDetail(&self) -> RTCErrorDetailType {
self.error_detail

View file

@ -73,9 +73,11 @@ impl RTCErrorEvent {
}
event
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl RTCErrorEventMethods for RTCErrorEvent {
// https://www.w3.org/TR/webrtc/#dom-rtcerrorevent-constructor
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -92,9 +94,7 @@ impl RTCErrorEvent {
can_gc,
)
}
}
impl RTCErrorEventMethods for RTCErrorEvent {
// https://www.w3.org/TR/webrtc/#dom-rtcerrorevent-error
fn Error(&self) -> DomRoot<RTCError> {
DomRoot::from_ref(&*self.error)

View file

@ -80,9 +80,11 @@ impl RTCIceCandidate {
can_gc,
)
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl RTCIceCandidateMethods for RTCIceCandidate {
/// <https://w3c.github.io/webrtc-pc/#dom-rtcicecandidate-constructor>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -103,9 +105,7 @@ impl RTCIceCandidate {
can_gc,
))
}
}
impl RTCIceCandidateMethods for RTCIceCandidate {
/// <https://w3c.github.io/webrtc-pc/#dom-rtcicecandidate-candidate>
fn Candidate(&self) -> DOMString {
self.candidate.clone()

View file

@ -26,7 +26,7 @@ use crate::dom::bindings::codegen::Bindings::RTCPeerConnectionBinding::{
RTCSignalingState,
};
use crate::dom::bindings::codegen::Bindings::RTCSessionDescriptionBinding::{
RTCSdpType, RTCSessionDescriptionInit,
RTCSdpType, RTCSessionDescriptionInit, RTCSessionDescriptionMethods,
};
use crate::dom::bindings::codegen::UnionTypes::{MediaStreamTrackOrString, StringOrStringSequence};
use crate::dom::bindings::error::{Error, Fallible};
@ -231,21 +231,6 @@ impl RTCPeerConnection {
this
}
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
config: &RTCConfiguration,
) -> Fallible<DomRoot<RTCPeerConnection>> {
Ok(RTCPeerConnection::new(
&window.global(),
proto,
config,
can_gc,
))
}
pub fn get_webrtc_controller(&self) -> &DomRefCell<Option<WebRtcController>> {
&self.controller
}
@ -525,6 +510,21 @@ impl RTCPeerConnection {
}
impl RTCPeerConnectionMethods for RTCPeerConnection {
// https://w3c.github.io/webrtc-pc/#dom-peerconnection
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
config: &RTCConfiguration,
) -> Fallible<DomRoot<RTCPeerConnection>> {
Ok(RTCPeerConnection::new(
&window.global(),
proto,
config,
can_gc,
))
}
// https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-icecandidate
event_handler!(icecandidate, GetOnicecandidate, SetOnicecandidate);

View file

@ -70,9 +70,11 @@ impl RTCPeerConnectionIceEvent {
evt.set_trusted(trusted);
e
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl RTCPeerConnectionIceEventMethods for RTCPeerConnectionIceEvent {
/// <https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnectioniceevent-constructor>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -92,9 +94,7 @@ impl RTCPeerConnectionIceEvent {
can_gc,
))
}
}
impl RTCPeerConnectionIceEventMethods for RTCPeerConnectionIceEvent {
/// <https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnectioniceevent-candidate>
fn GetCandidate(&self) -> Option<DomRoot<RTCIceCandidate>> {
self.candidate.as_ref().map(|x| DomRoot::from_ref(&**x))

View file

@ -46,9 +46,11 @@ impl RTCSessionDescription {
can_gc,
)
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl RTCSessionDescriptionMethods for RTCSessionDescription {
/// <https://w3c.github.io/webrtc-pc/#dom-sessiondescription>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -62,9 +64,7 @@ impl RTCSessionDescription {
can_gc,
))
}
}
impl RTCSessionDescriptionMethods for RTCSessionDescription {
/// <https://w3c.github.io/webrtc-pc/#dom-rtcsessiondescription-type>
fn Type(&self) -> RTCSdpType {
self.ty

View file

@ -73,9 +73,11 @@ impl RTCTrackEvent {
}
trackevent
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl RTCTrackEventMethods for RTCTrackEvent {
// https://w3c.github.io/webrtc-pc/#dom-rtctrackevent-constructor
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -92,9 +94,7 @@ impl RTCTrackEvent {
can_gc,
))
}
}
impl RTCTrackEventMethods for RTCTrackEvent {
// https://w3c.github.io/webrtc-pc/#dom-rtctrackevent-track
fn Track(&self) -> DomRoot<MediaStreamTrack> {
DomRoot::from_ref(&*self.track)

View file

@ -104,9 +104,12 @@ impl SecurityPolicyViolationEvent {
CanGc::note(),
)
}
}
#[allow(non_snake_case)]
pub fn Constructor(
#[allow(non_snake_case)]
impl SecurityPolicyViolationEventMethods for SecurityPolicyViolationEvent {
/// <https://w3c.github.io/webappsec-csp/#dom-securitypolicyviolationevent-securitypolicyviolationevent>
fn Constructor(
global: &GlobalScope,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -123,10 +126,7 @@ impl SecurityPolicyViolationEvent {
can_gc,
)
}
}
#[allow(non_snake_case)]
impl SecurityPolicyViolationEventMethods for SecurityPolicyViolationEvent {
/// <https://w3c.github.io/webappsec-csp/#dom-securitypolicyviolationevent-documenturi>
fn DocumentURI(&self) -> USVString {
self.document_uri.clone()

View file

@ -98,9 +98,11 @@ impl StereoPannerNode {
can_gc,
))
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl StereoPannerNodeMethods for StereoPannerNode {
// https://webaudio.github.io/web-audio-api/#dom-stereopannernode-stereopannernode
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -109,9 +111,7 @@ impl StereoPannerNode {
) -> Fallible<DomRoot<StereoPannerNode>> {
StereoPannerNode::new_with_proto(window, proto, context, options, can_gc)
}
}
impl StereoPannerNodeMethods for StereoPannerNode {
// https://webaudio.github.io/web-audio-api/#dom-stereopannernode-pan
fn Pan(&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.pan)

View file

@ -126,8 +126,12 @@ impl StorageEvent {
}
ev
}
}
pub fn Constructor(
#[allow(non_snake_case)]
impl StorageEventMethods for StorageEvent {
// https://html.spec.whatwg.org/multipage/#storageevent
fn Constructor(
global: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -156,10 +160,7 @@ impl StorageEvent {
);
Ok(event)
}
}
#[allow(non_snake_case)]
impl StorageEventMethods for StorageEvent {
// https://html.spec.whatwg.org/multipage/#dom-storageevent-key
fn GetKey(&self) -> Option<DOMString> {
self.key.borrow().clone()

View file

@ -73,9 +73,11 @@ impl SubmitEvent {
}
ev
}
}
#[allow(non_snake_case)]
pub fn Constructor(
impl SubmitEventMethods for SubmitEvent {
/// <https://html.spec.whatwg.org/multipage/#submitevent>
fn Constructor(
window: &Window,
proto: Option<HandleObject>,
can_gc: CanGc,
@ -92,9 +94,7 @@ impl SubmitEvent {
can_gc,
)
}
}
impl SubmitEventMethods for SubmitEvent {
/// <https://dom.spec.whatwg.org/#dom-event-istrusted>
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()

Some files were not shown because too many files have changed in this diff Show more